diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 3c003313c8b..586b3675305 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -529,8 +529,8 @@ interface NumberConstructor { /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ declare const Number: NumberConstructor; -interface TemplateStringsArray extends Array { - readonly raw: string[]; +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: ReadonlyArray } interface Math { @@ -1022,7 +1022,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[]): T[]; + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1071,6 +1076,12 @@ interface ReadonlyArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. @@ -1124,6 +1135,11 @@ interface Array { * Removes the last element from an array and returns it. */ pop(): T | undefined; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. @@ -1271,13 +1287,44 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * 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(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * 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( + onfulfilled?: ((value: T) => T | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): PromiseLike; + + /** + * 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( + onfulfilled: ((value: T) => T | PromiseLike) | undefined | null, + onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * 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( + onfulfilled: (value: T) => TResult | PromiseLike, + onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseLike; + + /** + * 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( + onfulfilled: (value: T) => TResult1 | PromiseLike, + onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; } interface ArrayLike { @@ -1537,7 +1584,7 @@ interface Int8Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -1545,7 +1592,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1810,7 +1857,7 @@ interface Uint8Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -1818,7 +1865,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2084,7 +2131,7 @@ interface Uint8ClampedArray { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2092,7 +2139,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2357,7 +2404,7 @@ interface Int16Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2365,7 +2412,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2631,7 +2678,7 @@ interface Uint16Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2639,7 +2686,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2904,7 +2951,7 @@ interface Int32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2912,7 +2959,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3177,7 +3224,7 @@ interface Uint32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3185,7 +3232,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3450,7 +3497,7 @@ interface Float32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3458,7 +3505,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3724,7 +3771,7 @@ interface Float64Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3732,7 +3779,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3949,12 +3996,9 @@ declare module Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new (locales?: string[], options?: CollatorOptions): Collator; - new (locale?: string, options?: CollatorOptions): Collator; - (locales?: string[], options?: CollatorOptions): Collator; - (locale?: string, options?: CollatorOptions): Collator; - supportedLocalesOf(locales: string[], options?: CollatorOptions): string[]; - supportedLocalesOf(locale: string, options?: CollatorOptions): string[]; + new (locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; } interface NumberFormatOptions { @@ -3989,12 +4033,9 @@ declare module Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string[], options?: NumberFormatOptions): NumberFormat; - new (locale?: string, options?: NumberFormatOptions): NumberFormat; - (locales?: string[], options?: NumberFormatOptions): NumberFormat; - (locale?: string, options?: NumberFormatOptions): NumberFormat; - supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; - supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; } interface DateTimeFormatOptions { @@ -4035,90 +4076,51 @@ declare module Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; - new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; - (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; - (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; - supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; - supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; } } interface String { /** - * Determines whether two strings are equivalent in the current locale. + * Determines whether two strings are equivalent in the current or specified locale. * @param that String to compare to target string - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. */ - localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. - * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. - */ - localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number; + localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; } interface Number { /** * Converts a number to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; - - /** - * Converts a number to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; + toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; } interface Date { /** * Converts a date and time to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a date to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a date and time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a date to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string; + toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; } ///////////////////////////// @@ -4248,6 +4250,7 @@ interface KeyAlgorithm { } interface KeyboardEventInit extends EventModifierInit { + code?: string; key?: string; location?: number; repeat?: boolean; @@ -6410,7 +6413,7 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode { /** * Sets or gets the URL for the current document. */ @@ -7473,7 +7476,7 @@ declare var Document: { new(): Document; } -interface DocumentFragment extends Node, NodeSelector { +interface DocumentFragment extends Node, NodeSelector, ParentNode { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7542,7 +7545,7 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; } -interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode { +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { readonly classList: DOMTokenList; className: string; readonly clientHeight: number; @@ -7797,6 +7800,16 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + insertAdjacentElement(position: string, insertedElement: Element): Element | null; + insertAdjacentHTML(where: string, html: string): void; + insertAdjacentText(where: string, text: string): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -8568,7 +8581,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -8743,11 +8756,7 @@ interface HTMLElement extends Element { click(): void; dragDrop(): boolean; focus(): void; - insertAdjacentElement(position: string, insertedElement: Element): Element; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; msGetInputContext(): MSInputMethodContext; - scrollIntoView(top?: boolean): void; setActive(): void; addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -10012,6 +10021,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { */ type: string; import?: Document; + integrity: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10300,7 +10310,7 @@ interface HTMLMediaElement extends HTMLElement { */ canPlayType(type: string): string; /** - * Fires immediately after the client loads the object. + * Resets the audio or video object and loads a new media resource. */ load(): void; /** @@ -10873,6 +10883,7 @@ interface HTMLScriptElement extends HTMLElement { * Sets or retrieves the MIME type for the associated scripting engine. */ type: string; + integrity: string; } declare var HTMLScriptElement: { @@ -11878,6 +11889,7 @@ interface KeyboardEvent extends UIEvent { readonly repeat: boolean; readonly shiftKey: boolean; readonly which: number; + readonly code: string; getModifierState(keyArg: string): boolean; initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; readonly DOM_KEY_LOCATION_JOYSTICK: number; @@ -13250,6 +13262,7 @@ interface PerformanceTiming { readonly responseStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly secureConnectionStart: number; toJSON(): any; } @@ -15527,8 +15540,8 @@ declare var StereoPannerNode: { interface Storage { readonly length: number; clear(): void; - getItem(key: string): string; - key(index: number): string; + getItem(key: string): string | null; + key(index: number): string | null; removeItem(key: string): void; setItem(key: string, data: string): void; [key: string]: any; @@ -17069,7 +17082,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window onunload: (this: this, ev: Event) => any; onvolumechange: (this: this, ev: Event) => any; onwaiting: (this: this, ev: Event) => any; - readonly opener: Window; + opener: any; orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; @@ -17124,6 +17137,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + scroll(options?: ScrollToOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollBy(options?: ScrollToOptions): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -18151,6 +18167,20 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + interface ClipboardEventInit extends EventInit { data?: string; dataType?: string; @@ -18194,7 +18224,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { @@ -18330,6 +18360,13 @@ interface JsonWebKey { k?: string; } +interface ParentNode { + readonly children: HTMLCollection; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly childElementCount: number; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -18400,7 +18437,7 @@ declare var location: Location; declare var locationbar: BarProp; declare var menubar: BarProp; declare var msCredentials: MSCredentials; -declare var name: string; +declare const name: never; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; declare var onabort: (this: Window, ev: UIEvent) => any; @@ -18494,7 +18531,7 @@ declare var ontouchstart: (ev: TouchEvent) => any; declare var onunload: (this: Window, ev: Event) => any; declare var onvolumechange: (this: Window, ev: Event) => any; declare var onwaiting: (this: Window, ev: Event) => any; -declare var opener: Window; +declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; declare var outerWidth: number; @@ -18547,6 +18584,9 @@ declare function webkitCancelAnimationFrame(handle: number): void; declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function scroll(options?: ScrollToOptions): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; @@ -18702,6 +18742,8 @@ type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index ec23413c089..4e45a38c17e 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -142,6 +142,7 @@ interface KeyAlgorithm { } interface KeyboardEventInit extends EventModifierInit { + code?: string; key?: string; location?: number; repeat?: boolean; @@ -2304,7 +2305,7 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode { /** * Sets or gets the URL for the current document. */ @@ -3367,7 +3368,7 @@ declare var Document: { new(): Document; } -interface DocumentFragment extends Node, NodeSelector { +interface DocumentFragment extends Node, NodeSelector, ParentNode { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -3436,7 +3437,7 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; } -interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode { +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { readonly classList: DOMTokenList; className: string; readonly clientHeight: number; @@ -3691,6 +3692,16 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + insertAdjacentElement(position: string, insertedElement: Element): Element | null; + insertAdjacentHTML(where: string, html: string): void; + insertAdjacentText(where: string, text: string): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -4462,7 +4473,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -4637,11 +4648,7 @@ interface HTMLElement extends Element { click(): void; dragDrop(): boolean; focus(): void; - insertAdjacentElement(position: string, insertedElement: Element): Element; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; msGetInputContext(): MSInputMethodContext; - scrollIntoView(top?: boolean): void; setActive(): void; addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -5906,6 +5913,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { */ type: string; import?: Document; + integrity: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6194,7 +6202,7 @@ interface HTMLMediaElement extends HTMLElement { */ canPlayType(type: string): string; /** - * Fires immediately after the client loads the object. + * Resets the audio or video object and loads a new media resource. */ load(): void; /** @@ -6767,6 +6775,7 @@ interface HTMLScriptElement extends HTMLElement { * Sets or retrieves the MIME type for the associated scripting engine. */ type: string; + integrity: string; } declare var HTMLScriptElement: { @@ -7772,6 +7781,7 @@ interface KeyboardEvent extends UIEvent { readonly repeat: boolean; readonly shiftKey: boolean; readonly which: number; + readonly code: string; getModifierState(keyArg: string): boolean; initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; readonly DOM_KEY_LOCATION_JOYSTICK: number; @@ -9144,6 +9154,7 @@ interface PerformanceTiming { readonly responseStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly secureConnectionStart: number; toJSON(): any; } @@ -11421,8 +11432,8 @@ declare var StereoPannerNode: { interface Storage { readonly length: number; clear(): void; - getItem(key: string): string; - key(index: number): string; + getItem(key: string): string | null; + key(index: number): string | null; removeItem(key: string): void; setItem(key: string, data: string): void; [key: string]: any; @@ -12963,7 +12974,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window onunload: (this: this, ev: Event) => any; onvolumechange: (this: this, ev: Event) => any; onwaiting: (this: this, ev: Event) => any; - readonly opener: Window; + opener: any; orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; @@ -13018,6 +13029,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + scroll(options?: ScrollToOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollBy(options?: ScrollToOptions): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -14045,6 +14059,20 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + interface ClipboardEventInit extends EventInit { data?: string; dataType?: string; @@ -14088,7 +14116,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { @@ -14224,6 +14252,13 @@ interface JsonWebKey { k?: string; } +interface ParentNode { + readonly children: HTMLCollection; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly childElementCount: number; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -14294,7 +14329,7 @@ declare var location: Location; declare var locationbar: BarProp; declare var menubar: BarProp; declare var msCredentials: MSCredentials; -declare var name: string; +declare const name: never; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; declare var onabort: (this: Window, ev: UIEvent) => any; @@ -14388,7 +14423,7 @@ declare var ontouchstart: (ev: TouchEvent) => any; declare var onunload: (this: Window, ev: Event) => any; declare var onvolumechange: (this: Window, ev: Event) => any; declare var onwaiting: (this: Window, ev: Event) => any; -declare var opener: Window; +declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; declare var outerWidth: number; @@ -14441,6 +14476,9 @@ declare function webkitCancelAnimationFrame(handle: number): void; declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function scroll(options?: ScrollToOptions): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; @@ -14596,6 +14634,8 @@ type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; \ No newline at end of file diff --git a/lib/lib.dom.iterable.d.ts b/lib/lib.dom.iterable.d.ts index e9cf451bf49..397e0ab111e 100644 --- a/lib/lib.dom.iterable.d.ts +++ b/lib/lib.dom.iterable.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ /// -/// +/// interface DOMTokenList { [Symbol.iterator](): IterableIterator; diff --git a/lib/lib.es2015.collection.d.ts b/lib/lib.es2015.collection.d.ts index 175f4f8725e..24c737df74b 100644 --- a/lib/lib.es2015.collection.d.ts +++ b/lib/lib.es2015.collection.d.ts @@ -17,10 +17,10 @@ and limitations under the License. interface Map { clear(): void; delete(key: K): boolean; - forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; get(key: K): V | undefined; has(key: K): boolean; - set(key: K, value: V): this; + set(key: K, value?: V): this; readonly size: number; } @@ -31,12 +31,18 @@ interface MapConstructor { } declare var Map: MapConstructor; +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V|undefined; + has(key: K): boolean; + readonly size: number; +} + interface WeakMap { - clear(): void; delete(key: K): boolean; get(key: K): V | undefined; has(key: K): boolean; - set(key: K, value: V): this; + set(key: K, value?: V): this; } interface WeakMapConstructor { @@ -50,7 +56,7 @@ interface Set { add(value: T): this; clear(): void; delete(value: T): boolean; - forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; has(value: T): boolean; readonly size: number; } @@ -62,9 +68,14 @@ interface SetConstructor { } declare var Set: SetConstructor; +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + interface WeakSet { add(value: T): this; - clear(): void; delete(value: T): boolean; has(value: T): boolean; } diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index c7c7afb821b..49a81a220ce 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -29,15 +29,15 @@ interface Array { find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value @@ -84,6 +84,10 @@ interface ArrayConstructor { of(...items: T[]): Array; } +interface DateConstructor { + new (value: Date): Date; +} + interface Function { /** * Returns the name of the function. Function names are read-only and can not be changed. @@ -242,7 +246,7 @@ interface NumberConstructor { /** * The value of the largest integer n such that n and n + 1 are both exactly representable as * a Number value. - * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. */ readonly MAX_SAFE_INTEGER: number; @@ -359,6 +363,30 @@ interface ObjectConstructor { defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; } +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; +} + interface RegExp { /** * Returns a string indicating the flags of the regular expression in question. This field is read-only. diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index a62d2635fae..1c27525d432 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -79,6 +79,26 @@ interface ArrayConstructor { from(iterable: Iterable): Array; } +interface ReadonlyArray { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + interface IArguments { /** Iterator */ [Symbol.iterator](): IterableIterator; diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 905cc13cba5..36fe9e7777f 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -24,7 +24,7 @@ interface Promise { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + then(onfulfilled?: ((value: T) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): Promise; /** * Attaches callbacks for the resolution and/or rejection of the Promise. @@ -32,20 +32,30 @@ interface Promise { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled: ((value: T) => T | PromiseLike) | undefined | null, onrejected: (reason: any) => TResult | PromiseLike): Promise; /** * 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(onfulfilled: (value: T) => TResult | PromiseLike): Promise; + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; /** - * Creates a new Promise with the same internal state of this Promise. - * @returns A Promise. + * 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(): Promise; + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + + /** + * 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 | PromiseLike) | undefined | null): Promise; /** * Attaches a callback for only the rejection of the Promise. @@ -53,13 +63,6 @@ interface Promise { * @returns A Promise for the completion of the callback. */ catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; - - /** - * 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 | PromiseLike): Promise; } interface PromiseConstructor { @@ -156,6 +159,86 @@ interface PromiseConstructor { */ all(values: (T | PromiseLike)[]): Promise; + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. diff --git a/lib/lib.es2015.proxy.d.ts b/lib/lib.es2015.proxy.d.ts index fa7527ef1c4..3908e97c17c 100644 --- a/lib/lib.es2015.proxy.d.ts +++ b/lib/lib.es2015.proxy.d.ts @@ -19,7 +19,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; @@ -35,4 +35,4 @@ interface ProxyConstructor { revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; new (target: T, handler: ProxyHandler): T } -declare var Proxy: ProxyConstructor; +declare var Proxy: ProxyConstructor; \ No newline at end of file diff --git a/lib/lib.es2015.reflect.d.ts b/lib/lib.es2015.reflect.d.ts index c53cdaf88ac..0f1a491ebcf 100644 --- a/lib/lib.es2015.reflect.d.ts +++ b/lib/lib.es2015.reflect.d.ts @@ -22,8 +22,7 @@ declare namespace Reflect { function get(target: any, propertyKey: PropertyKey, receiver?: any): any; function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: string): boolean; - function has(target: any, propertyKey: symbol): boolean; + function has(target: any, propertyKey: PropertyKey): boolean; function isExtensible(target: any): boolean; function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index e082101411d..5df0d7d4068 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -529,8 +529,8 @@ interface NumberConstructor { /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ declare const Number: NumberConstructor; -interface TemplateStringsArray extends Array { - readonly raw: string[]; +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: ReadonlyArray } interface Math { @@ -1022,7 +1022,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[]): T[]; + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1071,6 +1076,12 @@ interface ReadonlyArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. @@ -1124,6 +1135,11 @@ interface Array { * Removes the last element from an array and returns it. */ pop(): T | undefined; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. @@ -1271,13 +1287,44 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * 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(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * 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( + onfulfilled?: ((value: T) => T | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): PromiseLike; + + /** + * 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( + onfulfilled: ((value: T) => T | PromiseLike) | undefined | null, + onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * 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( + onfulfilled: (value: T) => TResult | PromiseLike, + onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseLike; + + /** + * 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( + onfulfilled: (value: T) => TResult1 | PromiseLike, + onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; } interface ArrayLike { @@ -1537,7 +1584,7 @@ interface Int8Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -1545,7 +1592,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1810,7 +1857,7 @@ interface Uint8Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -1818,7 +1865,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2084,7 +2131,7 @@ interface Uint8ClampedArray { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2092,7 +2139,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2357,7 +2404,7 @@ interface Int16Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2365,7 +2412,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2631,7 +2678,7 @@ interface Uint16Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2639,7 +2686,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2904,7 +2951,7 @@ interface Int32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2912,7 +2959,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3177,7 +3224,7 @@ interface Uint32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3185,7 +3232,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3450,7 +3497,7 @@ interface Float32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3458,7 +3505,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3724,7 +3771,7 @@ interface Float64Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3732,7 +3779,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3949,12 +3996,9 @@ declare module Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new (locales?: string[], options?: CollatorOptions): Collator; - new (locale?: string, options?: CollatorOptions): Collator; - (locales?: string[], options?: CollatorOptions): Collator; - (locale?: string, options?: CollatorOptions): Collator; - supportedLocalesOf(locales: string[], options?: CollatorOptions): string[]; - supportedLocalesOf(locale: string, options?: CollatorOptions): string[]; + new (locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; } interface NumberFormatOptions { @@ -3989,12 +4033,9 @@ declare module Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string[], options?: NumberFormatOptions): NumberFormat; - new (locale?: string, options?: NumberFormatOptions): NumberFormat; - (locales?: string[], options?: NumberFormatOptions): NumberFormat; - (locale?: string, options?: NumberFormatOptions): NumberFormat; - supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; - supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; } interface DateTimeFormatOptions { @@ -4035,88 +4076,49 @@ declare module Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; - new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; - (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; - (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; - supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; - supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; } } interface String { /** - * Determines whether two strings are equivalent in the current locale. + * Determines whether two strings are equivalent in the current or specified locale. * @param that String to compare to target string - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. */ - localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. - * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. - */ - localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number; + localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; } interface Number { /** * Converts a number to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; - - /** - * Converts a number to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; + toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; } interface Date { /** * Converts a date and time to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a date to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a date and time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a date to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string; + toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; } diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 8e9de3f4ec9..f6c7766ea9f 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -529,8 +529,8 @@ interface NumberConstructor { /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ declare const Number: NumberConstructor; -interface TemplateStringsArray extends Array { - readonly raw: string[]; +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: ReadonlyArray } interface Math { @@ -1022,7 +1022,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: T[]): T[]; + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1071,6 +1076,12 @@ interface ReadonlyArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. @@ -1124,6 +1135,11 @@ interface Array { * Removes the last element from an array and returns it. */ pop(): T | undefined; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. @@ -1271,13 +1287,44 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * 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(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * 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( + onfulfilled?: ((value: T) => T | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): PromiseLike; + + /** + * 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( + onfulfilled: ((value: T) => T | PromiseLike) | undefined | null, + onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * 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( + onfulfilled: (value: T) => TResult | PromiseLike, + onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseLike; + + /** + * 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( + onfulfilled: (value: T) => TResult1 | PromiseLike, + onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; } interface ArrayLike { @@ -1537,7 +1584,7 @@ interface Int8Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -1545,7 +1592,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1810,7 +1857,7 @@ interface Uint8Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -1818,7 +1865,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2084,7 +2131,7 @@ interface Uint8ClampedArray { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2092,7 +2139,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2357,7 +2404,7 @@ interface Int16Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2365,7 +2412,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2631,7 +2678,7 @@ interface Uint16Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2639,7 +2686,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2904,7 +2951,7 @@ interface Int32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -2912,7 +2959,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3177,7 +3224,7 @@ interface Uint32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3185,7 +3232,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3450,7 +3497,7 @@ interface Float32Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3458,7 +3505,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3724,7 +3771,7 @@ interface Float64Array { find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, @@ -3732,7 +3779,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3949,12 +3996,9 @@ declare module Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new (locales?: string[], options?: CollatorOptions): Collator; - new (locale?: string, options?: CollatorOptions): Collator; - (locales?: string[], options?: CollatorOptions): Collator; - (locale?: string, options?: CollatorOptions): Collator; - supportedLocalesOf(locales: string[], options?: CollatorOptions): string[]; - supportedLocalesOf(locale: string, options?: CollatorOptions): string[]; + new (locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; } interface NumberFormatOptions { @@ -3989,12 +4033,9 @@ declare module Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string[], options?: NumberFormatOptions): NumberFormat; - new (locale?: string, options?: NumberFormatOptions): NumberFormat; - (locales?: string[], options?: NumberFormatOptions): NumberFormat; - (locale?: string, options?: NumberFormatOptions): NumberFormat; - supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; - supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; } interface DateTimeFormatOptions { @@ -4035,90 +4076,51 @@ declare module Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; - new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; - (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; - (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; - supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; - supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; } } interface String { /** - * Determines whether two strings are equivalent in the current locale. + * Determines whether two strings are equivalent in the current or specified locale. * @param that String to compare to target string - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. */ - localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. - * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. - */ - localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number; + localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; } interface Number { /** * Converts a number to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; - - /** - * Converts a number to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; + toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; } interface Date { /** * Converts a date and time to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a date to a string by using the current or specified locale. - * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ - toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a date and time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a date to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a time to a string by using the current or specified locale. - * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string; + toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; } declare type PropertyKey = string | number | symbol; @@ -4135,15 +4137,15 @@ interface Array { find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; /** - * Returns the index of the first element in the array where predicate is true, and undefined + * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value @@ -4190,6 +4192,10 @@ interface ArrayConstructor { of(...items: T[]): Array; } +interface DateConstructor { + new (value: Date): Date; +} + interface Function { /** * Returns the name of the function. Function names are read-only and can not be changed. @@ -4348,7 +4354,7 @@ interface NumberConstructor { /** * The value of the largest integer n such that n and n + 1 are both exactly representable as * a Number value. - * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. */ readonly MAX_SAFE_INTEGER: number; @@ -4465,6 +4471,30 @@ interface ObjectConstructor { defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; } +interface ReadonlyArray { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; +} + interface RegExp { /** * Returns a string indicating the flags of the regular expression in question. This field is read-only. @@ -4619,7 +4649,7 @@ interface StringConstructor { interface Map { clear(): void; delete(key: K): boolean; - forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; get(key: K): V | undefined; has(key: K): boolean; set(key: K, value?: V): this; @@ -4633,8 +4663,14 @@ interface MapConstructor { } declare var Map: MapConstructor; +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V|undefined; + has(key: K): boolean; + readonly size: number; +} + interface WeakMap { - clear(): void; delete(key: K): boolean; get(key: K): V | undefined; has(key: K): boolean; @@ -4652,7 +4688,7 @@ interface Set { add(value: T): this; clear(): void; delete(value: T): boolean; - forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; has(value: T): boolean; readonly size: number; } @@ -4664,9 +4700,14 @@ interface SetConstructor { } declare var Set: SetConstructor; +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + interface WeakSet { add(value: T): this; - clear(): void; delete(value: T): boolean; has(value: T): boolean; } @@ -4754,6 +4795,26 @@ interface ArrayConstructor { from(iterable: Iterable): Array; } +interface ReadonlyArray { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + interface IArguments { /** Iterator */ [Symbol.iterator](): IterableIterator; @@ -5123,7 +5184,7 @@ interface Promise { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + then(onfulfilled?: ((value: T) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): Promise; /** * Attaches callbacks for the resolution and/or rejection of the Promise. @@ -5131,20 +5192,30 @@ interface Promise { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled: ((value: T) => T | PromiseLike) | undefined | null, onrejected: (reason: any) => TResult | PromiseLike): Promise; /** * 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(onfulfilled: (value: T) => TResult | PromiseLike): Promise; + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; /** - * Creates a new Promise with the same internal state of this Promise. - * @returns A Promise. + * 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(): Promise; + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + + /** + * 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 | PromiseLike) | undefined | null): Promise; /** * Attaches a callback for only the rejection of the Promise. @@ -5152,13 +5223,6 @@ interface Promise { * @returns A Promise for the completion of the callback. */ catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; - - /** - * 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 | PromiseLike): Promise; } interface PromiseConstructor { @@ -5255,6 +5319,86 @@ interface PromiseConstructor { */ all(values: (T | PromiseLike)[]): Promise; + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | PromiseLike)[]): Promise; + /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. @@ -5312,8 +5456,7 @@ declare var Proxy: ProxyConstructor;declare namespace Reflect { function get(target: any, propertyKey: PropertyKey, receiver?: any): any; function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: string): boolean; - function has(target: any, propertyKey: symbol): boolean; + function has(target: any, propertyKey: PropertyKey): boolean; function isExtensible(target: any): boolean; function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; @@ -5808,6 +5951,7 @@ interface KeyAlgorithm { } interface KeyboardEventInit extends EventModifierInit { + code?: string; key?: string; location?: number; repeat?: boolean; @@ -7970,7 +8114,7 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode { /** * Sets or gets the URL for the current document. */ @@ -9033,7 +9177,7 @@ declare var Document: { new(): Document; } -interface DocumentFragment extends Node, NodeSelector { +interface DocumentFragment extends Node, NodeSelector, ParentNode { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9102,7 +9246,7 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; } -interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode { +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { readonly classList: DOMTokenList; className: string; readonly clientHeight: number; @@ -9357,6 +9501,16 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; closest(selector: string): Element | null; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + insertAdjacentElement(position: string, insertedElement: Element): Element | null; + insertAdjacentHTML(where: string, html: string): void; + insertAdjacentText(where: string, text: string): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -10128,7 +10282,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -10303,11 +10457,7 @@ interface HTMLElement extends Element { click(): void; dragDrop(): boolean; focus(): void; - insertAdjacentElement(position: string, insertedElement: Element): Element; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; msGetInputContext(): MSInputMethodContext; - scrollIntoView(top?: boolean): void; setActive(): void; addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -11572,6 +11722,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { */ type: string; import?: Document; + integrity: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11860,7 +12011,7 @@ interface HTMLMediaElement extends HTMLElement { */ canPlayType(type: string): string; /** - * Fires immediately after the client loads the object. + * Resets the audio or video object and loads a new media resource. */ load(): void; /** @@ -12433,6 +12584,7 @@ interface HTMLScriptElement extends HTMLElement { * Sets or retrieves the MIME type for the associated scripting engine. */ type: string; + integrity: string; } declare var HTMLScriptElement: { @@ -13438,6 +13590,7 @@ interface KeyboardEvent extends UIEvent { readonly repeat: boolean; readonly shiftKey: boolean; readonly which: number; + readonly code: string; getModifierState(keyArg: string): boolean; initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; readonly DOM_KEY_LOCATION_JOYSTICK: number; @@ -14810,6 +14963,7 @@ interface PerformanceTiming { readonly responseStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly secureConnectionStart: number; toJSON(): any; } @@ -17087,8 +17241,8 @@ declare var StereoPannerNode: { interface Storage { readonly length: number; clear(): void; - getItem(key: string): string; - key(index: number): string; + getItem(key: string): string | null; + key(index: number): string | null; removeItem(key: string): void; setItem(key: string, data: string): void; [key: string]: any; @@ -18629,7 +18783,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window onunload: (this: this, ev: Event) => any; onvolumechange: (this: this, ev: Event) => any; onwaiting: (this: this, ev: Event) => any; - readonly opener: Window; + opener: any; orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; @@ -18684,6 +18838,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + scroll(options?: ScrollToOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollBy(options?: ScrollToOptions): void; addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -19711,6 +19868,20 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + interface ClipboardEventInit extends EventInit { data?: string; dataType?: string; @@ -19754,7 +19925,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { @@ -19890,6 +20061,13 @@ interface JsonWebKey { k?: string; } +interface ParentNode { + readonly children: HTMLCollection; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly childElementCount: number; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -19960,7 +20138,7 @@ declare var location: Location; declare var locationbar: BarProp; declare var menubar: BarProp; declare var msCredentials: MSCredentials; -declare var name: string; +declare const name: never; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; declare var onabort: (this: Window, ev: UIEvent) => any; @@ -20054,7 +20232,7 @@ declare var ontouchstart: (ev: TouchEvent) => any; declare var onunload: (this: Window, ev: Event) => any; declare var onvolumechange: (this: Window, ev: Event) => any; declare var onwaiting: (this: Window, ev: Event) => any; -declare var opener: Window; +declare var opener: any; declare var orientation: string | number; declare var outerHeight: number; declare var outerWidth: number; @@ -20107,6 +20285,9 @@ declare function webkitCancelAnimationFrame(handle: number): void; declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function scroll(options?: ScrollToOptions): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; @@ -20262,6 +20443,8 @@ type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; @@ -20561,7 +20744,7 @@ interface DateConstructor { interface Date { getVarDate: () => VarDate; } -/// +/// interface DOMTokenList { [Symbol.iterator](): IterableIterator; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index be707d274f1..5b35d820dfe 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -1016,7 +1016,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { diff --git a/lib/tsc.js b/lib/tsc.js index 0e3d7285ac3..aef54c957e6 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -30,14 +30,15 @@ var ts; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidType"] = 2] = "VoidType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 8] = "TypeWithCallSignature"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 9] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; (function (DiagnosticCategory) { @@ -64,8 +65,80 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var performance; + (function (performance) { + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true + ? onProfilerEvent + : function (markName) { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function mark(markName) { + if (enabled) { + marks[markName] = ts.timestamp(); + counts[markName] = (counts[markName] || 0) + 1; + profilerEvent(markName); + } + } + performance.mark = mark; + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks[endMarkName] || ts.timestamp(); + var start = startMarkName && marks[startMarkName] || profilerStart; + measures[measureName] = (measures[measureName] || 0) + (end - start); + } + } + performance.measure = measure; + function getCount(markName) { + return counts && counts[markName] || 0; + } + performance.getCount = getCount; + function getDuration(measureName) { + return measures && measures[measureName] || 0; + } + performance.getDuration = getDuration; + function forEachMeasure(cb) { + for (var key in measures) { + cb(key, measures[key]); + } + } + performance.forEachMeasure = forEachMeasure; + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var createObject = Object.create; + function createMap(template) { + var map = createObject(null); + map["__"] = undefined; + delete map["__"]; + for (var key in template) + if (hasOwnProperty.call(template, key)) { + map[key] = template[key]; + } + return map; + } + ts.createMap = createMap; function createFileMap(keyMapper) { - var files = {}; + var files = createMap(); return { get: get, set: set, @@ -86,14 +159,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return hasProperty(files, toKey(path)); + return toKey(path) in files; } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = {}; + files = createMap(); } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -119,11 +192,42 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + function every(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0, len = array.length; i < len; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findMap(array, callback) { + for (var i = 0, len = array.length; i < len; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (areEqual ? areEqual(v, value) : v === value) { + if (v === value) { return true; } } @@ -154,9 +258,9 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var v = array_2[_i]; - if (predicate(v)) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { count++; } } @@ -165,23 +269,47 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { - var result; if (array) { - result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - result.push(item); + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; } + return result; } } - return result; + return array; } ts.filter = filter; + function removeWhere(array, f) { + var outIndex = 0; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var item = array_2[_i]; + if (!f(item)) { + array[outIndex] = item; + outIndex++; + } + } + if (outIndex !== array.length) { + array.length = outIndex; + return true; + } + return false; + } + ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var item = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { array[outIndex] = item; outIndex++; @@ -194,14 +322,114 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; - result.push(f(v)); + for (var i = 0; i < array.length; i++) { + var v = array[i]; + result.push(f(v, i)); } } return result; } ts.map = map; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + function flatMap(array, mapfn) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMap = flatMap; + function span(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!f(array[i], i)) { + return [array.slice(0, i), array.slice(i)]; + } + } + return [array.slice(0), []]; + } + return undefined; + } + ts.span = span; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapObject(object, f) { + var result; + if (object) { + result = {}; + for (var _i = 0, _a = getOwnKeys(object); _i < _a.length; _i++) { + var v = _a[_i]; + var _b = f(v, object[v]) || [undefined, undefined], key = _b[0], value = _b[1]; + if (key !== undefined) { + result[key] = value; + } + } + } + return result; + } + ts.mapObject = mapObject; function concatenate(array1, array2) { if (!array2 || !array2.length) return array1; @@ -214,20 +442,42 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; - if (!contains(result, item, areEqual)) { - result.push(item); + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; + for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { + var res = result_1[_a]; + if (areEqual ? areEqual(res, item) : res === item) { + continue loop; + } } + result.push(item); } } return result; } ts.deduplicate = deduplicate; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -237,7 +487,9 @@ var ts; if (to && from) { for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { var v = from_1[_i]; - to.push(v); + if (v !== undefined) { + to.push(v); + } } } } @@ -252,11 +504,28 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function firstOrUndefined(array) { + return array && array.length > 0 + ? array[0] + : undefined; + } + ts.firstOrUndefined = firstOrUndefined; + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; function lastOrUndefined(array) { - if (array.length === 0) { - return undefined; - } - return array[array.length - 1]; + return array && array.length > 0 + ? array[array.length - 1] + : undefined; } ts.lastOrUndefined = lastOrUndefined; function binarySearch(array, value) { @@ -278,11 +547,12 @@ var ts; return ~low; } ts.binarySearch = binarySearch; - function reduceLeft(array, f, initial) { - if (array) { - var count = array.length; - if (count > 0) { - var pos = 0; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -291,8 +561,8 @@ var ts; else { result = initial; } - while (pos < count) { - result = f(result, array[pos]); + while (pos <= end) { + result = f(result, array[pos], pos); pos++; } return result; @@ -301,10 +571,12 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial) { + function reduceRight(array, f, initial, start, count) { if (array) { - var pos = array.length - 1; - if (pos >= 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start > size - 1 ? size - 1 : start; + var end = count === undefined || pos - count < 0 ? 0 : pos - count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -313,8 +585,8 @@ var ts; else { result = initial; } - while (pos >= 0) { - result = f(result, array[pos]); + while (pos >= end) { + result = f(result, array[pos], pos); pos--; } return result; @@ -328,18 +600,103 @@ var ts; return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; - function getKeys(map) { - var keys = []; - for (var key in map) { - keys.push(key); - } - return keys; - } - ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; + function getOwnKeys(map) { + var keys = []; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function forEachProperty(map, callback) { + var result; + for (var key in map) { + if (result = callback(map[key], key)) + break; + } + return result; + } + ts.forEachProperty = forEachProperty; + function someProperties(map, predicate) { + for (var key in map) { + if (!predicate || predicate(map[key], key)) + return true; + } + return false; + } + ts.someProperties = someProperties; + function copyProperties(source, target) { + for (var key in source) { + target[key] = source[key]; + } + } + ts.copyProperties = copyProperties; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var _b = 0, _c = getOwnKeys(arg); _b < _c.length; _b++) { + var p = _c[_b]; + t[p] = arg[p]; + } + } + return t; + } + ts.assign = assign; + function reduceProperties(map, callback, initial) { + var result = initial; + for (var key in map) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceProperties = reduceProperties; + function reduceOwnProperties(map, callback, initial) { + var result = initial; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceOwnProperties = reduceOwnProperties; + function equalOwnProperties(left, right, equalityComparer) { + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key) === undefined) + return false; + if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + return false; + } + for (var key in right) + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; function isEmpty(map) { for (var id in map) { if (hasProperty(map, id)) { @@ -349,75 +706,56 @@ var ts; return true; } ts.isEmpty = isEmpty; + function cloneMap(map) { + var clone = createMap(); + copyProperties(map, clone); + return clone; + } + ts.cloneMap = cloneMap; function clone(object) { var result = {}; for (var id in object) { - result[id] = object[id]; + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in first) { - result[id] = first[id]; - } - for (var id in second) { - if (!hasProperty(result, id)) { + for (var id in second) + if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - } + for (var id in first) + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } return result; } ts.extend = extend; - function forEachValue(map, callback) { - var result; - for (var id in map) { - if (result = callback(map[id])) - break; + function multiMapAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + return values; } - return result; - } - ts.forEachValue = forEachValue; - function forEachKey(map, callback) { - var result; - for (var id in map) { - if (result = callback(id)) - break; - } - return result; - } - ts.forEachKey = forEachKey; - function lookUp(map, key) { - return hasProperty(map, key) ? map[key] : undefined; - } - ts.lookUp = lookUp; - function copyMap(source, target) { - for (var p in source) { - target[p] = source[p]; + else { + return map[key] = [value]; } } - ts.copyMap = copyMap; - function arrayToMap(array, makeKey) { - var result = {}; - forEach(array, function (value) { - result[makeKey(value)] = value; - }); - return result; - } - ts.arrayToMap = arrayToMap; - function reduceProperties(map, callback, initial) { - var result = initial; - if (map) { - for (var key in map) { - if (hasProperty(map, key)) { - result = callback(result, map[key], String(key)); - } + ts.multiMapAdd = multiMapAdd; + function multiMapRemove(map, key, value) { + var values = map[key]; + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + delete map[key]; } } - return result; } - ts.reduceProperties = reduceProperties; + ts.multiMapRemove = multiMapRemove; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -439,9 +777,7 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] - ? ts.localizedDiagnosticMessages[message.key] - : message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -626,6 +962,7 @@ var ts; } ts.getRootLength = getRootLength; ts.directorySeparator = "/"; + var directorySeparatorCharCode = 47; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; @@ -647,10 +984,21 @@ var ts; function normalizePath(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); + var root = path.substr(0, rootLength); var normalized = getNormalizedParts(path, rootLength); - return path.substr(0, rootLength) + normalized.join(ts.directorySeparator); + if (normalized.length) { + var joinedParts = root + normalized.join(ts.directorySeparator); + return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + } + else { + return root; + } } ts.normalizePath = normalizePath; + function pathEndsWithDirectorySeparator(path) { + return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; + } + ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; function getDirectoryPath(path) { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); } @@ -825,10 +1173,17 @@ var ts; return true; } ts.containsPath = containsPath; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - var pathLen = path.length; - var extLen = extension.length; - return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; + return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -843,10 +1198,15 @@ var ts; ts.fileExtensionIsAny = fileExtensionIsAny; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; + var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; + var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } + var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; + var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; + var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -869,7 +1229,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -881,6 +1241,16 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } + if (usage !== "exclude") { + if (component.charCodeAt(0) === 42) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + subpattern += "[^./]"; + component = component.substr(1); + } + } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -901,8 +1271,14 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildcardCharacter(match) { - return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + function replaceWildCardCharacterFiles(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); + } + function replaceWildCardCharacterOther(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1001,6 +1377,7 @@ var ts; } ts.getScriptKindFromFileName = getScriptKindFromFileName; ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { @@ -1063,9 +1440,13 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; + return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -1085,14 +1466,21 @@ var ts; function Signature(checker) { } function Node(kind, pos, end) { + this.id = 0; this.kind = kind; this.pos = pos; this.end = end; this.flags = 0; + this.modifierFlagsCache = 0; + this.transformFlags = 0; this.parent = undefined; + this.original = undefined; + this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -1100,9 +1488,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel = 0; + var currentAssertionLevel; function shouldAssert(level) { - return currentAssertionLevel >= level; + return getCurrentAssertionLevel() >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1120,20 +1508,56 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; + function getCurrentAssertionLevel() { + if (currentAssertionLevel !== undefined) { + return currentAssertionLevel; + } + if (ts.sys === undefined) { + return 0; + } + var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); + currentAssertionLevel = developmentMode + ? 1 + : 0; + return currentAssertionLevel; + } })(Debug = ts.Debug || (ts.Debug = {})); - function copyListRemovingItem(item, list) { - var copiedList = []; - for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { - var e = list_1[_i]; - if (e !== item) { - copiedList.push(e); + function getEnvironmentVariable(name, host) { + if (host && host.getEnvironmentVariable) { + return host.getEnvironmentVariable(name); + } + if (ts.sys && ts.sys.getEnvironmentVariable) { + return ts.sys.getEnvironmentVariable(name); + } + return ""; + } + ts.getEnvironmentVariable = getEnvironmentVariable; + function orderedRemoveItemAt(array, index) { + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + function unorderedRemoveItem(array, item) { + unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + break; } } - return copiedList; } - ts.copyListRemovingItem = copyListRemovingItem; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? (function (fileName) { return fileName; }) : (function (fileName) { return fileName.toLowerCase(); }); } @@ -1224,7 +1648,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - return { + var wscriptSystem = { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -1243,7 +1667,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!wscriptSystem.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -1254,6 +1678,9 @@ var ts; return shell.CurrentDirectory; }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%" + name + "%"); + }, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -1263,6 +1690,7 @@ var ts; } } }; + return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -1271,13 +1699,13 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = {}; - var fileWatcherCallbacks = {}; + var dirWatchers = ts.createMap(); + var fileWatcherCallbacks = ts.createMap(); return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - if (ts.hasProperty(dirWatchers, dirName)) { - var watcher = dirWatchers[dirName]; + var watcher = dirWatchers[dirName]; + if (watcher) { watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -1286,23 +1714,18 @@ var ts; } } function addDirWatcher(dirPath) { - if (ts.hasProperty(dirWatchers, dirPath)) { - var watcher_1 = dirWatchers[dirPath]; - watcher_1.referenceCount += 1; + var watcher = dirWatchers[dirPath]; + if (watcher) { + watcher.referenceCount += 1; return; } - var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - fileWatcherCallbacks[filePath].push(callback); - } - else { - fileWatcherCallbacks[filePath] = [callback]; - } + ts.multiMapAdd(fileWatcherCallbacks, filePath, callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1314,21 +1737,13 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); - if (newCallbacks.length === 0) { - delete fileWatcherCallbacks[filePath]; - } - else { - fileWatcherCallbacks[filePath] = newCallbacks; - } - } + ts.multiMapRemove(fileWatcherCallbacks, filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { var fileName = typeof relativeFileName !== "string" ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -1433,9 +1848,9 @@ var ts; return fileSystemEntryExists(path, 1); } function getDirectories(path) { - return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - return { + var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -1485,7 +1900,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!nodeSystem.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -1496,6 +1911,9 @@ var ts; return process.cwd(); }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -1531,8 +1949,16 @@ var ts; }, realpath: function (path) { return _fs.realpathSync(path); + }, + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (e) { + } } }; + return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -1557,6 +1983,7 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), readDirectory: function (path, extensions, excludes, includes) { var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); @@ -1787,9 +2214,9 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher_1311", message: "Async functions are only available when targeting ECMAScript 2015 or higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, @@ -1844,12 +2271,11 @@ var ts; Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, - Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_2349", message: "Cannot invoke an expression whose type lacks a call signature." }, + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, @@ -1991,7 +2417,6 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_yield_expressions_2504", message: "No best common type exists among yield expressions." }, A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, @@ -2008,7 +2433,7 @@ var ts; A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, @@ -2021,6 +2446,7 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, + Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2068,6 +2494,13 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, + A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, + Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2138,7 +2571,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -2166,6 +2599,7 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2196,6 +2630,7 @@ var ts; VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, + STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, @@ -2282,10 +2717,12 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, - Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, + Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, + Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, + Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2294,7 +2731,6 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -2309,6 +2745,8 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2336,7 +2774,9 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." } + Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } }; })(ts || (ts = {})); var ts; @@ -2345,7 +2785,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115, "any": 117, "as": 116, @@ -2469,7 +2909,7 @@ var ts; "|=": 67, "^=": 68, "@": 55 - }; + }); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -2510,9 +2950,7 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - if (source.hasOwnProperty(name_4)) { - result[source[name_4]] = name_4; - } + result[source[name_4]] = name_4; } return result; } @@ -2639,7 +3077,7 @@ var ts; ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { if (stopAtComments === void 0) { stopAtComments = false; } - if (!(pos >= 0)) { + if (ts.positionIsSynthesized(pos)) { return pos; } while (true) { @@ -2762,10 +3200,15 @@ var ts; pos = pos + shebang.length; return pos; } - function getCommentRanges(text, pos, trailing) { - var result; + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; var collecting = trailing || pos === 0; - while (pos < text.length) { + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13: @@ -2775,11 +3218,11 @@ var ts; case 10: pos++; if (trailing) { - return result; + break scan; } collecting = true; - if (result && result.length) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; } continue; case 9: @@ -2814,34 +3257,67 @@ var ts; } } if (collecting) { - if (!result) { - result = []; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + return accumulator; + } + hasPendingCommentRange = false; } - result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; } continue; } - break; + break scan; default: if (ch > 127 && (isWhiteSpace(ch))) { - if (result && result.length && isLineBreak(ch)) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; } pos++; continue; } - break; + break scan; } - return result; } - return result; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + if (!comments) { + comments = []; + } + comments.push({ pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + return comments; } function getLeadingCommentRanges(text, pos) { - return getCommentRanges(text, pos, false); + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getLeadingCommentRanges = getLeadingCommentRanges; function getTrailingCommentRanges(text, pos) { - return getCommentRanges(text, pos, true); + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { @@ -2862,7 +3338,7 @@ var ts; ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; - function isIdentifier(name, languageVersion) { + function isIdentifierText(name, languageVersion) { if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { return false; } @@ -2873,7 +3349,7 @@ var ts; } return true; } - ts.isIdentifier = isIdentifier; + ts.isIdentifierText = isIdentifierText; function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } var pos; @@ -2902,6 +3378,7 @@ var ts; reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, scanJSDocToken: scanJSDocToken, @@ -2985,7 +3462,8 @@ var ts; } return value; } - function scanString() { + function scanString(allowEscapes) { + if (allowEscapes === void 0) { allowEscapes = true; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -3003,7 +3481,7 @@ var ts; pos++; break; } - if (ch === 92) { + if (ch === 92 && allowEscapes) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; @@ -3704,42 +4182,61 @@ var ts; } return token; } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34: + case 39: + tokenValue = scanString(false); + return token = 9; + default: + return scan(); + } + } function scanJSDocToken() { if (pos >= end) { return token = 1; } startPos = pos; - var ch = text.charCodeAt(pos); - while (pos < end) { - ch = text.charCodeAt(pos); - if (isWhiteSpaceSingleLine(ch)) { - pos++; - } - else { - break; - } - } tokenPos = pos; + var ch = text.charCodeAt(pos); switch (ch) { + case 9: + case 11: + case 12: + case 32: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5; case 64: - return pos += 1, token = 55; + pos++; + return token = 55; case 10: case 13: - return pos += 1, token = 4; + pos++; + return token = 4; case 42: - return pos += 1, token = 37; + pos++; + return token = 37; case 123: - return pos += 1, token = 15; + pos++; + return token = 15; case 125: - return pos += 1, token = 16; + pos++; + return token = 16; case 91: - return pos += 1, token = 19; + pos++; + return token = 19; case 93: - return pos += 1, token = 20; + pos++; + return token = 20; case 61: - return pos += 1, token = 56; + pos++; + return token = 56; case 44: - return pos += 1, token = 24; + pos++; + return token = 24; } if (isIdentifierStart(ch, 2)) { pos++; @@ -3832,6 +4329,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -3879,24 +4377,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function mapIsEqualTo(map1, map2) { - if (!map1 || !map2) { - return map1 === map2; - } - return containsAll(map1, map2) && containsAll(map2, map1); - } - ts.mapIsEqualTo = mapIsEqualTo; - function containsAll(map, other) { - for (var key in map) { - if (!ts.hasProperty(map, key)) { - continue; - } - if (!ts.hasProperty(other, key) || map[key] !== other[key]) { - return false; - } - } - return true; - } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -3914,7 +4394,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -3923,14 +4403,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = {}; + sourceFile.resolvedModules = ts.createMap(); } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = {}; + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -3949,7 +4429,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; + var oldResolution = oldResolutions && oldResolutions[names[i]]; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -3962,17 +4442,17 @@ var ts; ts.hasChangesInResolutions = hasChangesInResolutions; function containsParseError(node) { aggregateChildData(node); - return (node.flags & 268435456) !== 0; + return (node.flags & 2097152) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 536870912)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864) !== 0) || + if (!(node.flags & 4194304)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 524288) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.flags |= 268435456; + node.flags |= 2097152; } - node.flags |= 536870912; + node.flags |= 4194304; } } function getSourceFileOfNode(node) { @@ -4009,6 +4489,10 @@ var ts; return node.pos; } ts.getStartPosOfNode = getStartPosOfNode; + function isDefined(value) { + return value !== undefined; + } + ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -4029,7 +4513,7 @@ var ts; } ts.getEndLinePosition = getEndLinePosition; function nodeIsMissing(node) { - if (!node) { + if (node === undefined) { return true; } return node.pos === node.end && node.pos >= 0 && node.kind !== 1; @@ -4049,16 +4533,20 @@ var ts; if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { return getTokenPosOfNode(node.jsDocComments[0]); } - if (node.kind === 282 && node._children.length > 0) { + if (node.kind === 286 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 281; + return node.kind >= 257 && node.kind <= 282; } ts.isJSDocNode = isJSDocNode; + function isJSDocTag(node) { + return node.kind >= 273 && node.kind <= 285; + } + ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -4087,6 +4575,50 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getLiteralText(node, sourceFile, languageVersion) { + if (languageVersion < 2 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + return getQuotedEscapedLiteralText('"', node.text, '"'); + } + if (!nodeIsSynthesized(node) && node.parent) { + var text = getSourceTextOfNodeFromSourceFile(sourceFile, node); + if (languageVersion < 2 && isBinaryOrOctalIntegerLiteral(node, text)) { + return node.text; + } + return text; + } + switch (node.kind) { + case 9: + return getQuotedEscapedLiteralText('"', node.text, '"'); + case 11: + return getQuotedEscapedLiteralText("`", node.text, "`"); + case 12: + return getQuotedEscapedLiteralText("`", node.text, "${"); + case 13: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 14: + return getQuotedEscapedLiteralText("}", node.text, "`"); + case 8: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function isBinaryOrOctalIntegerLiteral(node, text) { + if (node.kind === 8 && text.length > 1) { + switch (text.charCodeAt(1)) { + case 98: + case 66: + case 111: + case 79: + return true; + } + } + return false; + } + ts.isBinaryOrOctalIntegerLiteral = isBinaryOrOctalIntegerLiteral; + function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { + return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + } function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -4100,7 +4632,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 3072) !== 0 || + return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -4109,19 +4641,21 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { return node.kind === 225 && (!node.body); } - ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || - isFunctionLike(node) || - isFunctionBlock(node); + isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { - return !!(module.flags & 131072); + return !!(module.flags & 512); } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { @@ -4137,26 +4671,35 @@ var ts; return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 256: + case 227: + case 252: + case 225: + case 206: + case 207: + case 208: + case 148: + case 147: + case 149: + case 150: + case 220: + case 179: + case 180: + return true; + case 199: + return parentNode && !isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { - if (isFunctionLike(current)) { + if (isBlockScope(current, current.parent)) { return current; } - switch (current.kind) { - case 256: - case 227: - case 252: - case 225: - case 206: - case 207: - case 208: - return current; - case 199: - if (!isFunctionLike(current.parent)) { - return current; - } - } current = current.parent; } } @@ -4258,34 +4801,13 @@ var ts; return node.kind === 224 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 || isBindingPattern(node))) { - node = node.parent; - } - return node; - } - function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 218) { - node = node.parent; - } - if (node && node.kind === 219) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 200) { - flags |= node.flags; - } - return flags; - } - ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 2048); + return !!(ts.getCombinedNodeFlags(node) & 2) + || !!(ts.getCombinedModifierFlags(node) & 2048); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 1024); + return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; function isSuperCallExpression(n) { @@ -4326,7 +4848,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; - function isTypeNode(node) { + function isPartOfTypeNode(node) { if (154 <= node.kind && node.kind <= 166) { return true; } @@ -4350,7 +4872,7 @@ var ts; else if (node.parent.kind === 172 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 139: case 172: case 97: @@ -4395,7 +4917,7 @@ var ts; } return false; } - ts.isTypeNode = isTypeNode; + ts.isPartOfTypeNode = isPartOfTypeNode; function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { @@ -4447,7 +4969,7 @@ var ts; return; } } - else if (!isTypeNode(node)) { + else if (!isPartOfTypeNode(node)) { ts.forEachChild(node, traverse); } } @@ -4660,18 +5182,19 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; - function isSuperPropertyOrElementAccess(node) { - return (node.kind === 172 - || node.kind === 173) + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 172 || kind === 173) && node.expression.kind === 95; } - ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; + ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { case 155: return node.typeName; case 194: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -4681,6 +5204,18 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function isCallLikeExpression(node) { + switch (node.kind) { + case 174: + case 175: + case 176: + case 143: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { if (node.kind === 176) { return node.tag; @@ -4714,14 +5249,20 @@ var ts; && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function isPropertyAccessExpression(node) { - return node.kind === 172; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isElementAccessExpression(node) { - return node.kind === 173; + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 221: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 147: + case 150: + return ts.forEach(node.parameters, nodeIsDecorated); + } } - ts.isElementAccessExpression = isElementAccessExpression; + ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; if (parent.kind === 243 || @@ -4732,7 +5273,7 @@ var ts; return false; } ts.isJSXTagName = isJSXTagName; - function isExpression(node) { + function isPartOfExpression(node) { switch (node.kind) { case 97: case 95: @@ -4827,16 +5368,16 @@ var ts; case 194: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: - if (isExpression(parent_3)) { + if (isPartOfExpression(parent_3)) { return true; } } } return false; } - ts.isExpression = isExpression; + ts.isPartOfExpression = isPartOfExpression; function isExternalModuleNameRelative(moduleName) { - return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + return /^\.\.?($|[\\/])/.test(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { @@ -4863,7 +5404,7 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 134217728); + return node && !!(node.flags & 1048576); } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression, checkArgumentIsStringLiteral) { @@ -4943,6 +5484,22 @@ var ts; } } ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + if (node.kind === 229) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { + return importClause.namedBindings; + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 230 + && node.importClause + && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { @@ -4969,31 +5526,62 @@ var ts; if (!node) { return undefined; } - var jsDocComments = getJSDocComments(node, checkParentVariableStatement); - if (!jsDocComments) { + var jsDocTags = getJSDocTags(node, checkParentVariableStatement); + if (!jsDocTags) { return undefined; } - for (var _i = 0, jsDocComments_1 = jsDocComments; _i < jsDocComments_1.length; _i++) { - var jsDocComment = jsDocComments_1[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === kind) { - return tag; - } + for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { + var tag = jsDocTags_1[_i]; + if (tag.kind === kind) { + return tag; } } } - function getJSDocComments(node, checkParentVariableStatement) { - if (node.jsDocComments) { - return node.jsDocComments; + function append(previous, additional) { + if (additional) { + if (!previous) { + previous = []; + } + for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { + var x = additional_1[_i]; + previous.push(x); + } } + return previous; + } + function getJSDocComments(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); + } + ts.getJSDocComments = getJSDocComments; + function getJSDocTags(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { + var result = []; + for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { + var doc = docs_1[_i]; + if (doc.tags) { + result.push.apply(result, doc.tags); + } + } + return result; + }, function (tags) { return tags; }); + } + function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { + var result = undefined; if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 218 && - node.parent.initializer === node && + var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && + (node.parent).initializer === node && node.parent.parent.parent.kind === 200; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + var isVariableOfVariableDeclarationStatement = isVariableLike(node) && + node.parent.parent.kind === 200; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : + isVariableOfVariableDeclarationStatement ? node.parent.parent : + undefined; if (variableStatementNode) { - return variableStatementNode.jsDocComments; + result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 225 && + node.parent && node.parent.kind === 225) { + result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } var parent_4 = node.parent; var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && @@ -5001,14 +5589,52 @@ var ts; parent_4.operatorToken.kind === 56 && parent_4.parent.kind === 202; if (isSourceOfAssignmentExpressionStatement) { - return parent_4.parent.jsDocComments; + result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); } var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; if (isPropertyAssignmentExpression) { - return parent_4.jsDocComments; + result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 142) { + var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); + if (paramTags) { + result = append(result, getTags(paramTags)); + } } } - return undefined; + if (isVariableLike(node) && node.initializer) { + result = append(result, getJSDocs(node.initializer, false, getDocs, getTags)); + } + if (node.jsDocComments) { + if (result) { + result = append(result, getDocs(node.jsDocComments)); + } + else { + return getDocs(node.jsDocComments); + } + } + return result; + } + function getJSDocParameterTag(param, checkParentVariableStatement) { + var func = param.parent; + var tags = getJSDocTags(func, checkParentVariableStatement); + if (!param.name) { + var i = func.parameters.indexOf(param); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275; }); + if (paramTags && 0 <= i && i < paramTags.length) { + return [paramTags[i]]; + } + } + else if (param.name.kind === 69) { + var name_6 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_6; }); + if (paramTags) { + return paramTags; + } + } + else { + return undefined; + } } function getJSDocTypeTag(node) { return getJSDocTag(node, 277, false); @@ -5025,19 +5651,16 @@ var ts; function getCorrespondingJSDocParameterTag(parameter) { if (parameter.name && parameter.name.kind === 69) { var parameterName = parameter.name.text; - var jsDocComments = getJSDocComments(parameter.parent, true); - if (jsDocComments) { - for (var _i = 0, jsDocComments_2 = jsDocComments; _i < jsDocComments_2.length; _i++) { - var jsDocComment = jsDocComments_2[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === 275) { - var parameterTag = tag; - var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_6.text === parameterName) { - return parameterTag; - } - } + var jsDocTags = getJSDocTags(parameter.parent, true); + if (!jsDocTags) { + return undefined; + } + for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { + var tag = jsDocTags_2[_i]; + if (tag.kind === 275) { + var parameterTag = tag; + if (parameterTag.parameterName.text === parameterName) { + return parameterTag; } } } @@ -5054,7 +5677,7 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 134217728)) { + if (node && (node.flags & 1048576)) { if (node.type && node.type.kind === 270) { return true; } @@ -5070,22 +5693,6 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isLiteralKind(kind) { - return 8 <= kind && kind <= 11; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 || kind === 11; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isTemplateLiteralKind(kind) { - return 11 <= kind && kind <= 14; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isBindingPattern(node) { - return !!node && (node.kind === 168 || node.kind === 167); - } - ts.isBindingPattern = isBindingPattern; function isAssignmentTarget(node) { while (node.parent.kind === 178) { node = node.parent; @@ -5101,14 +5708,14 @@ var ts; continue; } return parent_5.kind === 187 && - parent_5.operatorToken.kind === 56 && + isAssignmentOperator(parent_5.operatorToken.kind) && parent_5.left === node || (parent_5.kind === 207 || parent_5.kind === 208) && parent_5.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; - function isNodeDescendentOf(node, ancestor) { + function isNodeDescendantOf(node, ancestor) { while (node) { if (node === ancestor) return true; @@ -5116,10 +5723,10 @@ var ts; } return false; } - ts.isNodeDescendentOf = isNodeDescendentOf; + ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (node.flags & 2 || (node.kind === 256 && node.isDeclarationFile)) { + if (hasModifier(node, 2) || (node.kind === 256 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -5127,84 +5734,6 @@ var ts; return false; } ts.isInAmbientContext = isInAmbientContext; - function isDeclaration(node) { - switch (node.kind) { - case 180: - case 169: - case 221: - case 192: - case 148: - case 224: - case 255: - case 238: - case 220: - case 179: - case 149: - case 231: - case 229: - case 234: - case 222: - case 147: - case 146: - case 225: - case 232: - case 142: - case 253: - case 145: - case 144: - case 150: - case 254: - case 223: - case 141: - case 218: - case 279: - return true; - } - return false; - } - ts.isDeclaration = isDeclaration; - function isStatement(n) { - switch (n.kind) { - case 210: - case 209: - case 217: - case 204: - case 202: - case 201: - case 207: - case 208: - case 206: - case 203: - case 214: - case 211: - case 213: - case 215: - case 216: - case 200: - case 205: - case 212: - case 235: - return true; - default: - return false; - } - } - ts.isStatement = isStatement; - function isClassElement(n) { - switch (n.kind) { - case 148: - case 145: - case 147: - case 149: - case 150: - case 146: - case 153: - return true; - default: - return false; - } - } - ts.isClassElement = isClassElement; function isDeclarationName(name) { if (name.kind !== 69 && name.kind !== 9 && name.kind !== 8) { return false; @@ -5264,9 +5793,13 @@ var ts; node.kind === 232 || node.kind === 234 || node.kind === 238 || - node.kind === 235 && node.expression.kind === 69; + node.kind === 235 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + return isEntityNameExpression(node.expression); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -5354,7 +5887,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node); + return isFunctionLike(node) && hasModifier(node, 256) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; function isStringOrNumericLiteral(kind) { @@ -5430,63 +5963,238 @@ var ts; return node; } ts.getRootDeclaration = getRootDeclaration; - function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 225 || n.kind === 256; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 148 + || kind === 179 + || kind === 220 + || kind === 180 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 225 + || kind === 256; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneNode(node, location, flags, parent) { - var clone = location !== undefined - ? ts.createNode(node.kind, location.pos, location.end) - : createSynthesizedNode(node.kind); - for (var key in node) { - if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { - continue; - } - clone[key] = node[key]; - } - if (flags !== undefined) { - clone.flags = flags; - } - if (parent !== undefined) { - clone.parent = parent; - } - return clone; - } - ts.cloneNode = cloneNode; - function cloneEntityName(node, parent) { - var clone = cloneNode(node, node, node.flags, parent); - if (isQualifiedName(clone)) { - var left = clone.left, right = clone.right; - clone.left = cloneEntityName(left, clone); - clone.right = cloneNode(right, right, right.flags, parent); - } - return clone; - } - ts.cloneEntityName = cloneEntityName; - function isQualifiedName(node) { - return node.kind === 139; - } - ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { - return node.pos === -1; + return positionIsSynthesized(node.pos) + || positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function createSynthesizedNode(kind, startsOnNewLine) { - var node = ts.createNode(kind, -1, -1); - node.startsOnNewLine = startsOnNewLine; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function getOriginalNode(node) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } return node; } - ts.createSynthesizedNode = createSynthesizedNode; - function createSynthesizedNodeArray() { - var array = []; - array.pos = -1; - array.end = -1; - return array; + ts.getOriginalNode = getOriginalNode; + function isParseTreeNode(node) { + return (node.flags & 8) === 0; } - ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function getOriginalSourceFiles(sourceFiles) { + var originalSourceFiles = []; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + var originalSourceFile = getParseTreeNode(sourceFile, isSourceFile); + if (originalSourceFile) { + originalSourceFiles.push(originalSourceFile); + } + } + return originalSourceFiles; + } + ts.getOriginalSourceFiles = getOriginalSourceFiles; + function getOriginalNodeId(node) { + node = getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 175: + return hasArguments ? 0 : 1; + case 185: + case 182: + case 183: + case 181: + case 184: + case 188: + case 190: + return 1; + case 187: + switch (operator) { + case 38: + case 56: + case 57: + case 58: + case 60: + case 59: + case 61: + case 62: + case 63: + case 64: + case 65: + case 66: + case 68: + case 67: + return 1; + } + } + return 0; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 187) { + return expression.operatorToken.kind; + } + else if (expression.kind === 185 || expression.kind === 186) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 97: + case 95: + case 69: + case 93: + case 99: + case 84: + case 8: + case 9: + case 170: + case 171: + case 179: + case 180: + case 192: + case 241: + case 242: + case 10: + case 11: + case 189: + case 178: + case 193: + return 19; + case 176: + case 172: + case 173: + return 18; + case 175: + return hasArguments ? 18 : 17; + case 174: + return 17; + case 186: + return 16; + case 185: + case 182: + case 183: + case 181: + case 184: + return 15; + case 187: + switch (operatorKind) { + case 49: + case 50: + return 15; + case 38: + case 37: + case 39: + case 40: + return 14; + case 35: + case 36: + return 13; + case 43: + case 44: + case 45: + return 12; + case 25: + case 28: + case 27: + case 29: + case 90: + case 91: + return 11; + case 30: + case 32: + case 31: + case 33: + return 10; + case 46: + return 9; + case 48: + return 8; + case 47: + return 7; + case 51: + return 6; + case 52: + return 5; + case 56: + case 57: + case 58: + case 60: + case 59: + case 61: + case 62: + case 63: + case 64: + case 65: + case 66: + case 68: + case 67: + return 3; + case 24: + return 0; + default: + return -1; + } + case 188: + return 4; + case 190: + return 2; + case 191: + return 1; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -5539,9 +6247,7 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); - } + ts.forEach(fileDiagnostics[key], pushDiagnostic); } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -5552,15 +6258,13 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); - } + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } } } ts.createDiagnosticCollection = createDiagnosticCollection; var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { + var escapedCharsMap = ts.createMap({ "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -5573,7 +6277,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }; + }); function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -5676,10 +6380,23 @@ var ts; getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, reset: reset }; } ts.createTextWriter = createTextWriter; + function getResolvedExternalModuleName(host, file) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; function getExternalModuleNameFromPath(host, fileName) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); @@ -5721,6 +6438,69 @@ var ts; getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; } ts.getEmitModuleKind = getEmitModuleKind; + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + var moduleKind = getEmitModuleKind(options); + var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var sourceFiles = host.getSourceFiles(); + return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, isNonDeclarationFile); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function isNonDeclarationFile(sourceFile) { + return !isDeclarationFile(sourceFile); + } + function isBundleEmitNonExternalModule(sourceFile) { + return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + function forEachTransformedEmitFile(host, sourceFiles, action) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + onBundledEmit(host, sourceFiles); + } + else { + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var extension = ".js"; + if (options.jsx === 1) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); + } + function onBundledEmit(host, sourceFiles) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, true); + } + } + } + ts.forEachTransformedEmitFile = forEachTransformedEmitFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -5728,8 +6508,8 @@ var ts; } else { var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { onSingleFileEmit(host, sourceFile); } @@ -5770,9 +6550,6 @@ var ts; action(emitFileNames, bundledSources, true); } } - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } } ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { @@ -5834,7 +6611,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 149 || member.kind === 150) - && (member.flags & 32) === (accessor.flags & 32)) { + && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -5863,30 +6640,47 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { - if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } - ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { - var emitLeadingSpace = !trailingSeparator; - ts.forEach(comments, function (comment) { - if (emitLeadingSpace) { - writer.write(" "); - emitLeadingSpace = false; - } - writeComment(text, lineMap, writer, comment, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - else if (trailingSeparator) { + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { writer.write(" "); } - else { - emitLeadingSpace = true; + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.write(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } } - }); + if (emitInterveningSeparator && trailingSeparator) { + writer.write(" "); + } + } } ts.emitComments = emitComments; function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { @@ -5920,7 +6714,7 @@ var ts; var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments(text, lineMap, writer, detachedComments, true, newLine, writeComment); + emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } @@ -5932,18 +6726,18 @@ var ts; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(text, lineMap, writer, comment, newLine) { - if (text.charCodeAt(comment.pos + 1) === 42) { - var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); var lineCount = lineMap.length; var firstCommentLineIndent = void 0; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount ? text.length + 1 : lineMap[currentLine + 1]; - if (pos !== comment.pos) { + if (pos !== commentPos) { if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); } var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); @@ -5960,21 +6754,21 @@ var ts; writer.rawWrite(""); } } - writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { - writer.write(text.substring(comment.pos, comment.end)); + writer.write(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; - function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { writer.write(currentLineText); - if (end !== comment.end) { + if (end !== commentEnd) { writer.writeLine(); } } @@ -5994,6 +6788,32 @@ var ts; } return currentLineIndent; } + function hasModifiers(node) { + return getModifierFlags(node) !== 0; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return (getModifierFlags(node) & flags) !== 0; + } + ts.hasModifier = hasModifier; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912) { + return node.modifierFlagsCache & ~536870912; + } + var flags = 0; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4) { + flags |= 1; + } + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { case 113: return 32; @@ -6011,49 +6831,35 @@ var ts; return 0; } ts.modifierToFlag = modifierToFlag; - function isLeftHandSideExpression(expr) { - if (expr) { - switch (expr.kind) { - case 172: - case 173: - case 175: - case 174: - case 196: - case 241: - case 242: - case 176: - case 170: - case 178: - case 171: - case 192: - case 179: - case 69: - case 10: - case 8: - case 9: - case 11: - case 189: - case 84: - case 93: - case 97: - case 99: - case 95: - return true; - } - } - return false; + function isLogicalOperator(token) { + return token === 52 + || token === 51 + || token === 49; } - ts.isLeftHandSideExpression = isLeftHandSideExpression; + ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { return token >= 56 && token <= 68; } ts.isAssignmentOperator = isAssignmentOperator; - function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 194 && + function tryGetClassExtendingExpressionWithTypeArguments(node) { + if (node.kind === 194 && node.parent.token === 83 && - isClassLike(node.parent.parent); + isClassLike(node.parent.parent)) { + return node.parent.parent; + } } - ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isDestructuringAssignment(node) { + if (isBinaryExpression(node)) { + if (node.operatorToken.kind === 56) { + var kind = node.left.kind; + return kind === 171 + || kind === 170; + } + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; function isSupportedExpressionWithTypeArguments(node) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } @@ -6069,6 +6875,15 @@ var ts; return false; } } + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 69 || + node.kind === 172 && isEntityNameExpression(node.expression); + } + ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 && node.parent.right === node) || (node.parent.kind === 172 && node.parent.name === node); @@ -6086,7 +6901,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { @@ -6097,6 +6912,10 @@ var ts; return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function tryExtractTypeScriptExtension(fileName) { + return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6153,7 +6972,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -6204,6 +7023,738 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; + function isSimpleExpression(node) { + return isSimpleExpressionWorker(node, 0); + } + ts.isSimpleExpression = isSimpleExpression; + function isSimpleExpressionWorker(node, depth) { + if (depth <= 5) { + var kind = node.kind; + if (kind === 9 + || kind === 8 + || kind === 10 + || kind === 11 + || kind === 69 + || kind === 97 + || kind === 95 + || kind === 99 + || kind === 84 + || kind === 93) { + return true; + } + else if (kind === 172) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 173) { + return isSimpleExpressionWorker(node.expression, depth + 1) + && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + } + else if (kind === 185 + || kind === 186) { + return isSimpleExpressionWorker(node.operand, depth + 1); + } + else if (kind === 187) { + return node.operatorToken.kind !== 38 + && isSimpleExpressionWorker(node.left, depth + 1) + && isSimpleExpressionWorker(node.right, depth + 1); + } + else if (kind === 188) { + return isSimpleExpressionWorker(node.condition, depth + 1) + && isSimpleExpressionWorker(node.whenTrue, depth + 1) + && isSimpleExpressionWorker(node.whenFalse, depth + 1); + } + else if (kind === 183 + || kind === 182 + || kind === 181) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 170) { + return node.elements.length === 0; + } + else if (kind === 171) { + return node.properties.length === 0; + } + else if (kind === 174) { + if (!isSimpleExpressionWorker(node.expression, depth + 1)) { + return false; + } + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (!isSimpleExpressionWorker(argument, depth + 1)) { + return false; + } + } + return true; + } + } + return false; + } + var syntaxKindCache = ts.createMap(); + function formatSyntaxKind(kind) { + var syntaxKindEnum = ts.SyntaxKind; + if (syntaxKindEnum) { + if (syntaxKindCache[kind]) { + return syntaxKindCache[kind]; + } + for (var name_7 in syntaxKindEnum) { + if (syntaxKindEnum[name_7] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_7 + ")"; + } + } + } + else { + return kind.toString(); + } + } + ts.formatSyntaxKind = formatSyntaxKind; + function movePos(pos, value) { + return positionIsSynthesized(pos) ? -1 : pos + value; + } + ts.movePos = movePos; + function createRange(pos, end) { + return { pos: pos, end: end }; + } + ts.createRange = createRange; + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + function collapseRangeToStart(range) { + return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); + } + ts.collapseRangeToStart = collapseRangeToStart; + function collapseRangeToEnd(range) { + return isCollapsedRange(range) ? range : moveRangePos(range, range.end); + } + ts.collapseRangeToEnd = collapseRangeToEnd; + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function collectExternalModuleInfo(sourceFile, resolver) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 230: + if (!node.importClause || + resolver.isReferencedAliasDeclaration(node.importClause, true)) { + externalImports.push(node); + } + break; + case 229: + if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { + externalImports.push(node); + } + break; + case 236: + if (node.moduleSpecifier) { + if (!node.exportClause) { + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + } + else if (resolver.isValueAliasDeclaration(node)) { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + var name_8 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_8] || (exportSpecifiers[name_8] = [])).push(specifier); + } + } + break; + case 235: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isMergedWithClass(node) { + if (node.symbol) { + for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 221 && declaration !== node) { + return true; + } + } + } + return false; + } + ts.isMergedWithClass = isMergedWithClass; + function isFirstDeclarationOfKind(node, kind) { + return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; + } + ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 11; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 11; + } + ts.isLiteralKind = isLiteralKind; + function isTextualLiteralKind(kind) { + return kind === 9 || kind === 11; + } + ts.isTextualLiteralKind = isTextualLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 11 <= kind && kind <= 14; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralFragmentKind(kind) { + return kind === 12 + || kind === 13 + || kind === 14; + } + function isTemplateLiteralFragment(node) { + return isTemplateLiteralFragmentKind(node.kind); + } + ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + function isIdentifier(node) { + return node.kind === 69; + } + ts.isIdentifier = isIdentifier; + function isGeneratedIdentifier(node) { + return isIdentifier(node) && node.autoGenerateKind > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isQualifiedName(node) { + return node.kind === 139; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 140; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isEntityName(node) { + var kind = node.kind; + return kind === 139 + || kind === 69; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 69 + || kind === 9 + || kind === 8 + || kind === 140; + } + ts.isPropertyName = isPropertyName; + function isModuleName(node) { + var kind = node.kind; + return kind === 69 + || kind === 9; + } + ts.isModuleName = isModuleName; + function isBindingName(node) { + var kind = node.kind; + return kind === 69 + || kind === 167 + || kind === 168; + } + ts.isBindingName = isBindingName; + function isTypeParameter(node) { + return node.kind === 141; + } + ts.isTypeParameter = isTypeParameter; + function isParameter(node) { + return node.kind === 142; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 143; + } + ts.isDecorator = isDecorator; + function isMethodDeclaration(node) { + return node.kind === 147; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isClassElement(node) { + var kind = node.kind; + return kind === 148 + || kind === 145 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 153 + || kind === 198; + } + ts.isClassElement = isClassElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 253 + || kind === 254 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 239; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNodeKind(kind) { + return (kind >= 154 && kind <= 166) + || kind === 117 + || kind === 130 + || kind === 120 + || kind === 132 + || kind === 133 + || kind === 103 + || kind === 127 + || kind === 194; + } + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 168 + || kind === 167; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isBindingElement(node) { + return node.kind === 169; + } + ts.isBindingElement = isBindingElement; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 169 + || kind === 193; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isPropertyAccessExpression(node) { + return node.kind === 172; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 173; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isBinaryExpression(node) { + return node.kind === 187; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 188; + } + ts.isConditionalExpression = isConditionalExpression; + function isCallExpression(node) { + return node.kind === 174; + } + ts.isCallExpression = isCallExpression; + function isTemplate(node) { + var kind = node.kind; + return kind === 189 + || kind === 11; + } + ts.isTemplate = isTemplate; + function isSpreadElementExpression(node) { + return node.kind === 191; + } + ts.isSpreadElementExpression = isSpreadElementExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 194; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isLeftHandSideExpressionKind(kind) { + return kind === 172 + || kind === 173 + || kind === 175 + || kind === 174 + || kind === 241 + || kind === 242 + || kind === 176 + || kind === 170 + || kind === 178 + || kind === 171 + || kind === 192 + || kind === 179 + || kind === 69 + || kind === 10 + || kind === 8 + || kind === 9 + || kind === 11 + || kind === 189 + || kind === 84 + || kind === 93 + || kind === 97 + || kind === 99 + || kind === 95 + || kind === 196; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 185 + || kind === 186 + || kind === 181 + || kind === 182 + || kind === 183 + || kind === 184 + || kind === 177 + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 188 + || kind === 190 + || kind === 180 + || kind === 187 + || kind === 191 + || kind === 195 + || kind === 193 + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 177 + || kind === 195; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isOmittedExpression(node) { + return node.kind === 193; + } + ts.isOmittedExpression = isOmittedExpression; + function isTemplateSpan(node) { + return node.kind === 197; + } + ts.isTemplateSpan = isTemplateSpan; + function isBlock(node) { + return node.kind === 199; + } + ts.isBlock = isBlock; + function isConciseBody(node) { + return isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isVariableDeclaration(node) { + return node.kind === 218; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 219; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isCaseBlock(node) { + return node.kind === 227; + } + ts.isCaseBlock = isCaseBlock; + function isModuleBody(node) { + var kind = node.kind; + return kind === 226 + || kind === 225; + } + ts.isModuleBody = isModuleBody; + function isImportEqualsDeclaration(node) { + return node.kind === 229; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportClause(node) { + return node.kind === 231; + } + ts.isImportClause = isImportClause; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 233 + || kind === 232; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isImportSpecifier(node) { + return node.kind === 234; + } + ts.isImportSpecifier = isImportSpecifier; + function isNamedExports(node) { + return node.kind === 237; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 238; + } + ts.isExportSpecifier = isExportSpecifier; + function isModuleOrEnumDeclaration(node) { + return node.kind === 225 || node.kind === 224; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 180 + || kind === 169 + || kind === 221 + || kind === 192 + || kind === 148 + || kind === 224 + || kind === 255 + || kind === 238 + || kind === 220 + || kind === 179 + || kind === 149 + || kind === 231 + || kind === 229 + || kind === 234 + || kind === 222 + || kind === 147 + || kind === 146 + || kind === 225 + || kind === 228 + || kind === 232 + || kind === 142 + || kind === 253 + || kind === 145 + || kind === 144 + || kind === 150 + || kind === 254 + || kind === 223 + || kind === 141 + || kind === 218 + || kind === 279; + } + function isDeclarationStatementKind(kind) { + return kind === 220 + || kind === 239 + || kind === 221 + || kind === 222 + || kind === 223 + || kind === 224 + || kind === 225 + || kind === 230 + || kind === 229 + || kind === 236 + || kind === 235 + || kind === 228; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 210 + || kind === 209 + || kind === 217 + || kind === 204 + || kind === 202 + || kind === 201 + || kind === 207 + || kind === 208 + || kind === 206 + || kind === 203 + || kind === 214 + || kind === 211 + || kind === 213 + || kind === 215 + || kind === 216 + || kind === 200 + || kind === 205 + || kind === 212 + || kind === 287; + } + function isDeclaration(node) { + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 199; + } + ts.isStatement = isStatement; + function isModuleReference(node) { + var kind = node.kind; + return kind === 240 + || kind === 139 + || kind === 69; + } + ts.isModuleReference = isModuleReference; + function isJsxOpeningElement(node) { + return node.kind === 243; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 245; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 97 + || kind === 69 + || kind === 172; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 241 + || kind === 248 + || kind === 242 + || kind === 244; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 246 + || kind === 247; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isJsxSpreadAttribute(node) { + return node.kind === 247; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxAttribute(node) { + return node.kind === 246; + } + ts.isJsxAttribute = isJsxAttribute; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 + || kind === 248; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 249 + || kind === 250; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isHeritageClause(node) { + return node.kind === 251; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 252; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 253; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 254; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isEnumMember(node) { + return node.kind === 255; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 256; + } + ts.isSourceFile = isSourceFile; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } @@ -6341,28 +7892,2230 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 169 || ts.isBindingPattern(node))) { + node = node.parent; + } + return node; } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return str.indexOf(suffix, expectedPos) === expectedPos; + function getCombinedModifierFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = ts.getModifierFlags(node); + if (node.kind === 218) { + node = node.parent; + } + if (node && node.kind === 219) { + flags |= ts.getModifierFlags(node); + node = node.parent; + } + if (node && node.kind === 200) { + flags |= ts.getModifierFlags(node); + } + return flags; } - ts.endsWith = endsWith; + ts.getCombinedModifierFlags = getCombinedModifierFlags; + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 218) { + node = node.parent; + } + if (node && node.kind === 219) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 200) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; })(ts || (ts = {})); var ts; (function (ts) { - ts.parseTime = 0; var NodeConstructor; var SourceFileConstructor; + function createNode(kind, location, flags) { + var ConstructorForKind = kind === 256 + ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) + : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); + var node = location + ? new ConstructorForKind(kind, location.pos, location.end) + : new ConstructorForKind(kind, -1, -1); + node.flags = flags | 8; + return node; + } + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + if (original.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + function createNodeArray(elements, location, hasTrailingComma) { + if (elements) { + if (ts.isNodeArray(elements)) { + return elements; + } + } + else { + elements = []; + } + var array = elements; + if (location) { + array.pos = location.pos; + array.end = location.end; + } + else { + array.pos = -1; + array.end = -1; + } + if (hasTrailingComma) { + array.hasTrailingComma = true; + } + return array; + } + ts.createNodeArray = createNodeArray; + function createSynthesizedNode(kind, startsOnNewLine) { + var node = createNode(kind, undefined); + node.startsOnNewLine = startsOnNewLine; + return node; + } + ts.createSynthesizedNode = createSynthesizedNode; + function createSynthesizedNodeArray(elements) { + return createNodeArray(elements, undefined); + } + ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + function getSynthesizedClone(node) { + var clone = createNode(node.kind, undefined, node.flags); + clone.original = node; + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + function createLiteral(value, location) { + if (typeof value === "number") { + var node = createNode(8, location, undefined); + node.text = value.toString(); + return node; + } + else if (typeof value === "boolean") { + return createNode(value ? 99 : 84, location, undefined); + } + else if (typeof value === "string") { + var node = createNode(9, location, undefined); + node.text = value; + return node; + } + else { + var node = createNode(9, location, undefined); + node.textSourceNode = value; + node.text = value.text; + return node; + } + } + ts.createLiteral = createLiteral; + var nextAutoGenerateId = 0; + function createIdentifier(text, location) { + var node = createNode(69, location); + node.text = ts.escapeIdentifier(text); + node.originalKeywordKind = ts.stringToToken(text); + node.autoGenerateKind = 0; + node.autoGenerateId = 0; + return node; + } + ts.createIdentifier = createIdentifier; + function createTempVariable(recordTempVariable, location) { + var name = createNode(69, location); + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 1; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + return name; + } + ts.createTempVariable = createTempVariable; + function createLoopVariable(location) { + var name = createNode(69, location); + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 2; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + function createUniqueName(text, location) { + var name = createNode(69, location); + name.text = text; + name.originalKeywordKind = 0; + name.autoGenerateKind = 3; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function getGeneratedNameForNode(node, location) { + var name = createNode(69, location); + name.original = node; + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 4; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + function createToken(token) { + return createNode(token); + } + ts.createToken = createToken; + function createSuper() { + var node = createNode(95); + return node; + } + ts.createSuper = createSuper; + function createThis(location) { + var node = createNode(97, location); + return node; + } + ts.createThis = createThis; + function createNull() { + var node = createNode(93); + return node; + } + ts.createNull = createNull; + function createComputedPropertyName(expression, location) { + var node = createNode(140, location); + node.expression = expression; + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + if (node.expression !== expression) { + return updateNode(createComputedPropertyName(expression, node), node); + } + return node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + function createParameter(name, initializer, location) { + return createParameterDeclaration(undefined, undefined, undefined, name, undefined, undefined, initializer, location); + } + ts.createParameter = createParameter; + function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(142, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameterDeclaration = createParameterDeclaration; + function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); + } + return node; + } + ts.updateParameterDeclaration = updateParameterDeclaration; + function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { + var node = createNode(145, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer, node), node); + } + return node; + } + ts.updateProperty = updateProperty; + function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(147, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createMethod(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body, location, flags) { + var node = createNode(148, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body) { + return updateNode(createConstructor(decorators, modifiers, parameters, body, node, node.flags), node); + } + return node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { + var node = createNode(149, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { + var node = createNode(150, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body) { + return updateNode(createSetAccessor(decorators, modifiers, name, parameters, body, node, node.flags), node); + } + return node; + } + ts.updateSetAccessor = updateSetAccessor; + function createObjectBindingPattern(elements, location) { + var node = createNode(167, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createObjectBindingPattern(elements, node), node); + } + return node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements, location) { + var node = createNode(168, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayBindingPattern(elements, node), node); + } + return node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { + var node = createNode(169, location); + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + } + return node; + } + ts.updateBindingElement = updateBindingElement; + function createArrayLiteral(elements, location, multiLine) { + var node = createNode(170, location); + node.elements = parenthesizeListElements(createNodeArray(elements)); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayLiteral(elements, node, node.multiLine), node); + } + return node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, location, multiLine) { + var node = createNode(171, location); + node.properties = createNodeArray(properties); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + if (node.properties !== properties) { + return updateNode(createObjectLiteral(properties, node, node.multiLine), node); + } + return node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name, location, flags) { + var node = createNode(172, location, flags); + node.expression = parenthesizeForAccess(expression); + node.emitFlags = 1048576; + node.name = typeof name === "string" ? createIdentifier(name) : name; + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + if (node.expression !== expression || node.name !== name) { + var propertyAccess = createPropertyAccess(expression, name, node, node.flags); + propertyAccess.emitFlags = node.emitFlags; + return updateNode(propertyAccess, node); + } + return node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index, location) { + var node = createNode(173, location); + node.expression = parenthesizeForAccess(expression); + node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + if (node.expression !== expression || node.argumentExpression !== argumentExpression) { + return updateNode(createElementAccess(expression, argumentExpression, node), node); + } + return node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(174, location, flags); + node.expression = parenthesizeForAccess(expression); + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + node.arguments = parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + if (expression !== node.expression || typeArguments !== node.typeArguments || argumentsArray !== node.arguments) { + return updateNode(createCall(expression, typeArguments, argumentsArray, node, node.flags), node); + } + return node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(175, location, flags); + node.expression = parenthesizeForNew(expression); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + if (node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray) { + return updateNode(createNew(expression, typeArguments, argumentsArray, node, node.flags), node); + } + return node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, template, location) { + var node = createNode(176, location); + node.tag = parenthesizeForAccess(tag); + node.template = template; + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, template) { + if (node.tag !== tag || node.template !== template) { + return updateNode(createTaggedTemplate(tag, template, node), node); + } + return node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createParen(expression, location) { + var node = createNode(178, location); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + if (node.expression !== expression) { + return updateNode(createParen(expression, node), node); + } + return node; + } + ts.updateParen = updateParen; + function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(179, location, flags); + node.modifiers = undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { + var node = createNode(180, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.body = parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + if (node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body, node, node.flags), node); + } + return node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression, location) { + var node = createNode(181, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + if (node.expression !== expression) { + return updateNode(createDelete(expression, node), expression); + } + return node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression, location) { + var node = createNode(182, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + if (node.expression !== expression) { + return updateNode(createTypeOf(expression, node), expression); + } + return node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression, location) { + var node = createNode(183, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + if (node.expression !== expression) { + return updateNode(createVoid(expression, node), node); + } + return node; + } + ts.updateVoid = updateVoid; + function createAwait(expression, location) { + var node = createNode(184, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + if (node.expression !== expression) { + return updateNode(createAwait(expression, node), node); + } + return node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand, location) { + var node = createNode(185, location); + node.operator = operator; + node.operand = parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPrefix(node.operator, operand, node), node); + } + return node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator, location) { + var node = createNode(186, location); + node.operand = parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPostfix(operand, node.operator, node), node); + } + return node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right, location) { + var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorKind = operatorToken.kind; + var node = createNode(187, location); + node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); + node.operatorToken = operatorToken; + node.right = parenthesizeBinaryOperand(operatorKind, right, false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right) { + if (node.left !== left || node.right !== right) { + return updateNode(createBinary(left, node.operatorToken, right, node), node); + } + return node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { + var node = createNode(188, location); + node.condition = condition; + node.questionToken = questionToken; + node.whenTrue = whenTrue; + node.colonToken = colonToken; + node.whenFalse = whenFalse; + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, whenTrue, whenFalse) { + if (node.condition !== condition || node.whenTrue !== whenTrue || node.whenFalse !== whenFalse) { + return updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse, node), node); + } + return node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans, location) { + var node = createNode(189, location); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + if (node.head !== head || node.templateSpans !== templateSpans) { + return updateNode(createTemplateExpression(head, templateSpans, node), node); + } + return node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createYield(asteriskToken, expression, location) { + var node = createNode(190, location); + node.asteriskToken = asteriskToken; + node.expression = expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, expression) { + if (node.expression !== expression) { + return updateNode(createYield(node.asteriskToken, expression, node), node); + } + return node; + } + ts.updateYield = updateYield; + function createSpread(expression, location) { + var node = createNode(191, location); + node.expression = parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpread(expression, node), node); + } + return node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(192, location); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + if (node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression(location) { + var node = createNode(193, location); + return node; + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression, location) { + var node = createNode(194, location); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.expression = parenthesizeForAccess(expression); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + if (node.typeArguments !== typeArguments || node.expression !== expression) { + return updateNode(createExpressionWithTypeArguments(typeArguments, expression, node), node); + } + return node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createTemplateSpan(expression, literal, location) { + var node = createNode(197, location); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + if (node.expression !== expression || node.literal !== literal) { + return updateNode(createTemplateSpan(expression, literal, node), node); + } + return node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createBlock(statements, location, multiLine, flags) { + var block = createNode(199, location, flags); + block.statements = createNodeArray(statements); + if (multiLine) { + block.multiLine = true; + } + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + if (statements !== node.statements) { + return updateNode(createBlock(statements, node, node.multiLine, node.flags), node); + } + return node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList, location, flags) { + var node = createNode(200, location, flags); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + if (node.modifiers !== modifiers || node.declarationList !== declarationList) { + return updateNode(createVariableStatement(modifiers, declarationList, node, node.flags), node); + } + return node; + } + ts.updateVariableStatement = updateVariableStatement; + function createVariableDeclarationList(declarations, location, flags) { + var node = createNode(219, location, flags); + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + if (node.declarations !== declarations) { + return updateNode(createVariableDeclarationList(declarations, node, node.flags), node); + } + return node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createVariableDeclaration(name, type, initializer, location, flags) { + var node = createNode(218, location, flags); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.type = type; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + if (node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createVariableDeclaration(name, type, initializer, node, node.flags), node); + } + return node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createEmptyStatement(location) { + return createNode(201, location); + } + ts.createEmptyStatement = createEmptyStatement; + function createStatement(expression, location, flags) { + var node = createNode(202, location, flags); + node.expression = parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createStatement = createStatement; + function updateStatement(node, expression) { + if (node.expression !== expression) { + return updateNode(createStatement(expression, node, node.flags), node); + } + return node; + } + ts.updateStatement = updateStatement; + function createIf(expression, thenStatement, elseStatement, location) { + var node = createNode(203, location); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + if (node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement) { + return updateNode(createIf(expression, thenStatement, elseStatement, node), node); + } + return node; + } + ts.updateIf = updateIf; + function createDo(statement, expression, location) { + var node = createNode(204, location); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + if (node.statement !== statement || node.expression !== expression) { + return updateNode(createDo(statement, expression, node), node); + } + return node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement, location) { + var node = createNode(205, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWhile(expression, statement, node), node); + } + return node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement, location) { + var node = createNode(206, location, undefined); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + if (node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement) { + return updateNode(createFor(initializer, condition, incrementor, statement, node), node); + } + return node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement, location) { + var node = createNode(207, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForIn(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForIn = updateForIn; + function createForOf(initializer, expression, statement, location) { + var node = createNode(208, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForOf(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForOf = updateForOf; + function createContinue(label, location) { + var node = createNode(209, location); + if (label) { + node.label = label; + } + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + if (node.label !== label) { + return updateNode(createContinue(label, node), node); + } + return node; + } + ts.updateContinue = updateContinue; + function createBreak(label, location) { + var node = createNode(210, location); + if (label) { + node.label = label; + } + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + if (node.label !== label) { + return updateNode(createBreak(label, node), node); + } + return node; + } + ts.updateBreak = updateBreak; + function createReturn(expression, location) { + var node = createNode(211, location); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + if (node.expression !== expression) { + return updateNode(createReturn(expression, node), node); + } + return node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement, location) { + var node = createNode(212, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWith(expression, statement, node), node); + } + return node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock, location) { + var node = createNode(213, location); + node.expression = parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + if (node.expression !== expression || node.caseBlock !== caseBlock) { + return updateNode(createSwitch(expression, caseBlock, node), node); + } + return node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement, location) { + var node = createNode(214, location); + node.label = typeof label === "string" ? createIdentifier(label) : label; + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + if (node.label !== label || node.statement !== statement) { + return updateNode(createLabel(label, statement, node), node); + } + return node; + } + ts.updateLabel = updateLabel; + function createThrow(expression, location) { + var node = createNode(215, location); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + if (node.expression !== expression) { + return updateNode(createThrow(expression, node), node); + } + return node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock, location) { + var node = createNode(216, location); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + if (node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock) { + return updateNode(createTry(tryBlock, catchClause, finallyBlock, node), node); + } + return node; + } + ts.updateTry = updateTry; + function createCaseBlock(clauses, location) { + var node = createNode(227, location); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + if (node.clauses !== clauses) { + return updateNode(createCaseBlock(clauses, node), node); + } + return node; + } + ts.updateCaseBlock = updateCaseBlock; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(220, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionDeclaration(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(221, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { + var node = createNode(230, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings, location) { + var node = createNode(231, location); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + if (node.name !== name || node.namedBindings !== namedBindings) { + return updateNode(createImportClause(name, namedBindings, node), node); + } + return node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name, location) { + var node = createNode(232, location); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + if (node.name !== name) { + return updateNode(createNamespaceImport(name, node), node); + } + return node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements, location) { + var node = createNode(233, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedImports(elements, node), node); + } + return node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name, location) { + var node = createNode(234, location); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + if (node.propertyName !== propertyName || node.name !== name) { + return updateNode(createImportSpecifier(propertyName, name, node), node); + } + return node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { + var node = createNode(235, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.isExportEquals = isExportEquals; + node.expression = expression; + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.expression !== expression) { + return updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression, node), node); + } + return node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { + var node = createNode(236, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements, location) { + var node = createNode(237, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedExports(elements, node), node); + } + return node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(name, propertyName, location) { + var node = createNode(238, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, name, propertyName) { + if (node.name !== name || node.propertyName !== propertyName) { + return updateNode(createExportSpecifier(name, propertyName, node), node); + } + return node; + } + ts.updateExportSpecifier = updateExportSpecifier; + function createJsxElement(openingElement, children, closingElement, location) { + var node = createNode(241, location); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + if (node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement) { + return updateNode(createJsxElement(openingElement, children, closingElement, node), node); + } + return node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, attributes, location) { + var node = createNode(242, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxSelfClosingElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, attributes, location) { + var node = createNode(243, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxOpeningElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName, location) { + var node = createNode(245, location); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + if (node.tagName !== tagName) { + return updateNode(createJsxClosingElement(tagName, node), node); + } + return node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxAttribute(name, initializer, location) { + var node = createNode(246, location); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createJsxAttribute(name, initializer, node), node); + } + return node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxSpreadAttribute(expression, location) { + var node = createNode(247, location); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxSpreadAttribute(expression, node), node); + } + return node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(expression, location) { + var node = createNode(248, location); + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxExpression(expression, node), node); + } + return node; + } + ts.updateJsxExpression = updateJsxExpression; + function createHeritageClause(token, types, location) { + var node = createNode(251, location); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + if (node.types !== types) { + return updateNode(createHeritageClause(node.token, types, node), node); + } + return node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCaseClause(expression, statements, location) { + var node = createNode(249, location); + node.expression = parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + if (node.expression !== expression || node.statements !== statements) { + return updateNode(createCaseClause(expression, statements, node), node); + } + return node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements, location) { + var node = createNode(250, location); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + if (node.statements !== statements) { + return updateNode(createDefaultClause(statements, node), node); + } + return node; + } + ts.updateDefaultClause = updateDefaultClause; + function createCatchClause(variableDeclaration, block, location) { + var node = createNode(252, location); + node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + if (node.variableDeclaration !== variableDeclaration || node.block !== block) { + return updateNode(createCatchClause(variableDeclaration, block, node), node); + } + return node; + } + ts.updateCatchClause = updateCatchClause; + function createPropertyAssignment(name, initializer, location) { + var node = createNode(253, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = undefined; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createPropertyAssignment(name, initializer, node), node); + } + return node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { + var node = createNode(254, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { + return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); + } + return node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSourceFileNode(node, statements) { + if (node.statements !== statements) { + var updated = createNode(256, node, node.flags); + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.referencedFiles !== undefined) + updated.referencedFiles = node.referencedFiles; + if (node.typeReferenceDirectives !== undefined) + updated.typeReferenceDirectives = node.typeReferenceDirectives; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.isDeclarationFile !== undefined) + updated.isDeclarationFile = node.isDeclarationFile; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.hasNoDefaultLib !== undefined) + updated.hasNoDefaultLib = node.hasNoDefaultLib; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.externalHelpersModuleName !== undefined) + updated.externalHelpersModuleName = node.externalHelpersModuleName; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + function createNotEmittedStatement(original) { + var node = createNode(287, original); + node.original = original; + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + function createPartiallyEmittedExpression(expression, original, location) { + var node = createNode(288, location || original); + node.expression = expression; + node.original = original; + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original, node), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function createComma(left, right) { + return createBinary(left, 24, right); + } + ts.createComma = createComma; + function createLessThan(left, right, location) { + return createBinary(left, 25, right, location); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right, location) { + return createBinary(left, 56, right, location); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 32, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 33, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 35, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 36, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand, location) { + return createPostfix(operand, 41, location); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 51, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 52, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(49, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return createElementAccess(target, memberName.expression, location); + } + else { + var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); + expression.emitFlags |= 2048; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createRestParameter(name) { + return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + } + ts.createRestParameter = createRestParameter; + function createFunctionCall(func, thisArg, argumentsList, location) { + return createCall(createPropertyAccess(func, "call"), undefined, [ + thisArg + ].concat(argumentsList), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return createCall(createPropertyAccess(func, "apply"), undefined, [ + thisArg, + argumentsExpression + ], location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? createLiteral(start) : start); + } + return createCall(createPropertyAccess(array, "slice"), undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return createCall(createPropertyAccess(array, "concat"), undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return createCall(createPropertyAccess(createIdentifier("Math"), "pow"), undefined, [left, right], location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + var react = createIdentifier(reactNamespace || "React"); + react.flags &= ~8; + react.parent = parent; + return react; + } + function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + child.startsOnNewLine = true; + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), undefined, argumentsList, location); + } + ts.createReactCreateElement = createReactCreateElement; + function createLetDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 1); + } + ts.createLetDeclarationList = createLetDeclarationList; + function createConstDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 2); + } + ts.createConstDeclarationList = createConstDeclarationList; + function createHelperName(externalHelpersModuleName, name) { + return externalHelpersModuleName + ? createPropertyAccess(externalHelpersModuleName, name) + : createIdentifier(name); + } + ts.createHelperName = createHelperName; + function createExtendsHelper(externalHelpersModuleName, name) { + return createCall(createHelperName(externalHelpersModuleName, "__extends"), undefined, [ + name, + createIdentifier("_super") + ]); + } + ts.createExtendsHelper = createExtendsHelper; + function createAssignHelper(externalHelpersModuleName, attributesSegments) { + return createCall(createHelperName(externalHelpersModuleName, "__assign"), undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { + return createCall(createHelperName(externalHelpersModuleName, "__param"), undefined, [ + createLiteral(parameterOffset), + expression + ], location); + } + ts.createParamHelper = createParamHelper; + function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { + return createCall(createHelperName(externalHelpersModuleName, "__metadata"), undefined, [ + createLiteral(metadataKey), + metadataValue + ]); + } + ts.createMetadataHelper = createMetadataHelper; + function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(createArrayLiteral(decoratorExpressions, undefined, true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return createCall(createHelperName(externalHelpersModuleName, "__decorate"), undefined, argumentsArray, location); + } + ts.createDecorateHelper = createDecorateHelper; + function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { + var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); + generatorFunc.emitFlags |= 2097152; + return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ + createThis(), + hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), + promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), + generatorFunc + ]); + } + ts.createAwaiterHelper = createAwaiterHelper; + function createHasOwnProperty(target, propertyName) { + return createCall(createPropertyAccess(target, "hasOwnProperty"), undefined, [propertyName]); + } + ts.createHasOwnProperty = createHasOwnProperty; + function createObjectCreate(prototype) { + return createCall(createPropertyAccess(createIdentifier("Object"), "create"), undefined, [prototype]); + } + function createGeti(target) { + return createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createElementAccess(target, createIdentifier("name"))); + } + function createSeti(target) { + return createArrowFunction(undefined, undefined, [ + createParameter("name"), + createParameter("value") + ], undefined, undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); + } + function createAdvancedAsyncSuperHelper() { + var createCache = createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("cache", undefined, createObjectCreate(createNull())) + ])); + var getter = createGetAccessor(undefined, undefined, "value", [], undefined, createBlock([ + createReturn(createCall(createIdentifier("geti"), undefined, [createIdentifier("name")])) + ])); + var setter = createSetAccessor(undefined, undefined, "value", [createParameter("v")], createBlock([ + createStatement(createCall(createIdentifier("seti"), undefined, [ + createIdentifier("name"), + createIdentifier("v") + ])) + ])); + var getOrCreateAccessorsForName = createReturn(createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ + getter, + setter + ])))))); + return createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("_super", undefined, createCall(createParen(createFunctionExpression(undefined, undefined, undefined, [ + createParameter("geti"), + createParameter("seti") + ], undefined, createBlock([ + createCache, + getOrCreateAccessorsForName + ]))), undefined, [ + createGeti(createSuper()), + createSeti(createSuper()) + ])) + ])); + } + ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; + function createSimpleAsyncSuperHelper() { + return createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("_super", undefined, createGeti(createSuper())) + ])); + } + ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = skipParentheses(node); + switch (target.kind) { + case 69: + return cacheIdentifiers; + case 97: + case 8: + case 9: + return false; + case 170: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 171: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + var callee = skipOuterExpressions(expression, 7); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = createThis(); + target = callee; + } + else if (callee.kind === 95) { + thisArg = createThis(); + target = languageVersion < 2 ? createIdentifier("_super", callee) : callee; + } + else { + switch (callee.kind) { + case 172: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createPropertyAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.name, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 173: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createElementAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.argumentExpression, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + thisArg = createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + return ts.reduceLeft(expressions, createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = getMutableClone(node.right); + return createPropertyAccess(left, right, node); + } + else { + return getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return createLiteral(memberName, undefined); + } + else if (ts.isComputedPropertyName(memberName)) { + return getMutableClone(memberName.expression); + } + else { + return getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 149: + case 150: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + case 253: + return createExpressionForPropertyAssignment(property, receiver); + case 254: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 147: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_1 = []; + if (getAccessor) { + var getterFunction = createFunctionExpression(undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); + setOriginalNode(getterFunction, getAccessor); + var getter = createPropertyAssignment("get", getterFunction); + properties_1.push(getter); + } + if (setAccessor) { + var setterFunction = createFunctionExpression(undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); + setOriginalNode(setterFunction, setAccessor); + var setter = createPropertyAssignment("set", setterFunction); + properties_1.push(setter); + } + properties_1.push(createPropertyAssignment("enumerable", createLiteral(true))); + properties_1.push(createPropertyAssignment("configurable", createLiteral(true))); + var expression = createCall(createPropertyAccess(createIdentifier("Object"), "defineProperty"), undefined, [ + receiver, + createExpressionForPropertyName(property.name), + createObjectLiteral(properties_1, undefined, multiLine) + ], firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), property.initializer, property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), getSynthesizedClone(property.name), property), property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); + } + function isUseStrictPrologue(node) { + return node.expression.text === "use strict"; + } + function addPrologueDirectives(target, source, ensureUseStrict, visitor) { + ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + foundUseStrict = true; + } + if (statement.emitFlags & 8388608) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + } + statementOffset++; + } + return statementOffset; + } + ts.addPrologueDirectives = addPrologueDirectives; + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = skipPartiallyEmittedExpressions(operand); + if (skipped.kind === 178) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var binaryOperatorPrecedence = ts.getOperatorPrecedence(187, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(187, binaryOperator); + var emittedOperand = skipPartiallyEmittedExpressions(operand); + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1: + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 + && operand.kind === 190) { + return false; + } + return true; + case 1: + return false; + case 0: + if (isLeftSideOfBinary) { + return binaryOperatorAssociativity === 1; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + if (binaryOperator === 35) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0; + } + } + } + function operatorHasAssociativeProperty(binaryOperator) { + return binaryOperator === 37 + || binaryOperator === 47 + || binaryOperator === 46 + || binaryOperator === 48; + } + function getLiteralKindOfBinaryPlusOperand(node) { + node = skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 187 && node.operatorToken.kind === 35) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0; + } + function parenthesizeForNew(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + switch (emittedExpression.kind) { + case 174: + return createParen(expression); + case 175: + return emittedExpression.arguments + ? expression + : createParen(expression); + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + function parenthesizeForAccess(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 175 || emittedExpression.arguments) + && emittedExpression.kind !== 8) { + return expression; + } + return createParen(expression, expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : createParen(operand, operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : createParen(operand, operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return createNodeArray(result, elements, elements.hasTrailingComma); + } + return elements; + } + function parenthesizeExpressionForList(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(187, 24); + return expressionPrecedence > commaPrecedence + ? expression + : createParen(expression, expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = skipPartiallyEmittedExpressions(callee).kind; + if (kind === 179 || kind === 180) { + var mutableCall = getMutableClone(emittedExpression); + mutableCall.expression = createParen(callee, callee); + return recreatePartiallyEmittedExpressions(expression, mutableCall); + } + } + else { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 171 || leftmostExpressionKind === 179) { + return createParen(expression, expression); + } + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { + if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { + var clone_1 = getMutableClone(originalOuterExpression); + clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); + return clone_1; + } + return newInnerExpression; + } + function getLeftmostExpression(node) { + while (true) { + switch (node.kind) { + case 186: + node = node.operand; + continue; + case 187: + node = node.left; + continue; + case 188: + node = node.condition; + continue; + case 174: + case 173: + case 172: + node = node.expression; + continue; + case 288: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + var emittedBody = skipPartiallyEmittedExpressions(body); + if (emittedBody.kind === 171) { + return createParen(body, body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7; } + var previousNode; + do { + previousNode = node; + if (kinds & 1) { + node = skipParentheses(node); + } + if (kinds & 2) { + node = skipAssertions(node); + } + if (kinds & 4) { + node = skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipParentheses(node) { + while (node.kind === 178) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipAssertions(node) { + while (ts.isAssertionExpression(node)) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function startOnNewLine(node) { + node.startsOnNewLine = true; + return node; + } + ts.startOnNewLine = startOnNewLine; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; + if (emitFlags) + node.emitFlags = emitFlags; + if (commentRange) + node.commentRange = commentRange; + if (sourceMapRange) + node.sourceMapRange = sourceMapRange; + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function setTextRange(node, location) { + if (location) { + node.pos = location.pos; + node.end = location.end; + } + return node; + } + ts.setTextRange = setTextRange; + function setNodeFlags(node, flags) { + node.flags = flags; + return node; + } + ts.setNodeFlags = setNodeFlags; + function setMultiLine(node, multiLine) { + node.multiLine = multiLine; + return node; + } + ts.setMultiLine = setMultiLine; + function setHasTrailingComma(nodes, hasTrailingComma) { + nodes.hasTrailingComma = hasTrailingComma; + return nodes; + } + ts.setHasTrailingComma = setHasTrailingComma; + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name_9 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_9) ? name_9 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + } + if (node.kind === 230 && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 236 && node.moduleSpecifier) { + return getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); + if (moduleName.kind === 9) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + function tryRenameExternalModule(moduleName, sourceFile) { + if (sourceFile.renamedDependencies && ts.hasProperty(sourceFile.renamedDependencies, moduleName.text)) { + return createLiteral(sourceFile.renamedDependencies[moduleName.text]); + } + return undefined; + } + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return createLiteral(file.moduleName); + } + if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + return createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } + else if (kind === 69) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (kind < 139) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -6471,6 +10224,8 @@ var ts; return visitNodes(cbNodes, node.types); case 164: return visitNode(cbNode, node.type); + case 166: + return visitNode(cbNode, node.literal); case 167: case 168: return visitNodes(cbNodes, node.elements); @@ -6710,7 +10465,7 @@ var ts; case 263: return visitNode(cbNode, node.type); case 265: - return visitNodes(cbNodes, node.members); + return visitNode(cbNode, node.literal); case 267: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); @@ -6749,14 +10504,19 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + case 288: + return visitNode(cbNode, node.expression); + case 282: + return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - var start = new Date().getTime(); + ts.performance.mark("beforeParse"); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.parseTime += new Date().getTime() - start; + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; } ts.createSourceFile = createSourceFile; @@ -6770,8 +10530,8 @@ var ts; ts.updateSourceFile = updateSourceFile; function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDocComment) { - Parser.fixupParentReferences(result.jsDocComment); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); } return result; } @@ -6783,13 +10543,15 @@ var ts; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 4194304 | 16777216; + var disallowInAndDecoratorContext = 32768 | 131072; var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -6810,15 +10572,17 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 1048576 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -6837,10 +10601,10 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; - token = nextToken(); + nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token === 1); + ts.Debug.assert(token() === 1); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -6853,20 +10617,18 @@ var ts; return sourceFile; } function addJSDocComment(node) { - if (contextFlags & 134217728) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDocComment) { - continue; - } - if (!node.jsDocComments) { - node.jsDocComments = []; - } - node.jsDocComments.push(jsDocComment); + var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; } + if (!node.jsDocComments) { + node.jsDocComments = []; + } + node.jsDocComments.push(jsDoc); } } return node; @@ -6915,16 +10677,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 4194304); + setContextFlag(val, 32768); } function setYieldContext(val) { - setContextFlag(val, 8388608); + setContextFlag(val, 65536); } function setDecoratorContext(val) { - setContextFlag(val, 16777216); + setContextFlag(val, 131072); } function setAwaitContext(val) { - setContextFlag(val, 33554432); + setContextFlag(val, 262144); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -6947,40 +10709,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(4194304, func); + return doOutsideOfContext(32768, func); } function disallowInAnd(func) { - return doInsideOfContext(4194304, func); + return doInsideOfContext(32768, func); } function doInYieldContext(func) { - return doInsideOfContext(8388608, func); + return doInsideOfContext(65536, func); } function doInDecoratorContext(func) { - return doInsideOfContext(16777216, func); + return doInsideOfContext(131072, func); } function doInAwaitContext(func) { - return doInsideOfContext(33554432, func); + return doInsideOfContext(262144, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(33554432, func); + return doOutsideOfContext(262144, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(8388608 | 33554432, func); + return doInsideOfContext(65536 | 262144, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(8388608); + return inContext(65536); } function inDisallowInContext() { - return inContext(4194304); + return inContext(32768); } function inDecoratorContext() { - return inContext(16777216); + return inContext(131072); } function inAwaitContext() { - return inContext(33554432); + return inContext(262144); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -7004,26 +10766,32 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } + function token() { + return currentToken; + } function nextToken() { - return token = scanner.scan(); + return currentToken = scanner.scan(); } function reScanGreaterToken() { - return token = scanner.reScanGreaterToken(); + return currentToken = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return token = scanner.reScanSlashToken(); + return currentToken = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return token = scanner.reScanTemplateToken(); + return currentToken = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return token = scanner.scanJsxIdentifier(); + return currentToken = scanner.scanJsxIdentifier(); } function scanJsxText() { - return token = scanner.scanJsxToken(); + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); } function speculationHelper(callback, isLookAhead) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -7032,7 +10800,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -7045,20 +10813,20 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token === 69) { + if (token() === 69) { return true; } - if (token === 114 && inYieldContext()) { + if (token() === 114 && inYieldContext()) { return false; } - if (token === 119 && inAwaitContext()) { + if (token() === 119 && inAwaitContext()) { return false; } - return token > 105; + return token() > 105; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token === kind) { + if (token() === kind) { if (shouldAdvance) { nextToken(); } @@ -7073,14 +10841,14 @@ var ts; return false; } function parseOptional(t) { - if (token === t) { + if (token() === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token === t) { + if (token() === t) { return parseTokenNode(); } return undefined; @@ -7090,19 +10858,19 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token); + var node = createNode(token()); nextToken(); return finishNode(node); } function canParseSemicolon() { - if (token === 23) { + if (token() === 23) { return true; } - return token === 16 || token === 1 || scanner.hasPrecedingLineBreak(); + return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token === 23) { + if (token() === 23) { nextToken(); } return true; @@ -7116,7 +10884,18 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new NodeConstructor(kind, pos, pos); + return kind >= 139 ? new NodeConstructor(kind, pos, pos) : + kind === 69 ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -7125,7 +10904,7 @@ var ts; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 67108864; + node.flags |= 524288; } return node; } @@ -7142,14 +10921,14 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); + return identifiers[text] || (identifiers[text] = text); } function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { var node = createNode(69); - if (token !== 69) { - node.originalKeywordKind = token; + if (token() !== 69) { + node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -7161,18 +10940,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token) || - token === 9 || - token === 8; + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token === 9 || token === 8) { + if (token() === 9 || token() === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token === 19) { + if (allowComputedPropertyNames && token() === 19) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -7184,7 +10963,7 @@ var ts; return parsePropertyNameWorker(false); } function isSimplePropertyName() { - return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { var node = createNode(140); @@ -7194,7 +10973,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -7204,39 +10983,39 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token === 74) { + if (token() === 74) { return nextToken() === 81; } - if (token === 82) { + if (token() === 82) { nextToken(); - if (token === 77) { + if (token() === 77) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token !== 37 && token !== 116 && token !== 15 && canFollowModifier(); + return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); } - if (token === 77) { + if (token() === 77) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token === 113) { + if (token() === 113) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token === 19 - || token === 15 - || token === 37 - || token === 22 + return token() === 19 + || token() === 15 + || token() === 37 + || token() === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token === 73 || token === 87 || - (token === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 73 || token() === 87 || + (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -7247,21 +11026,21 @@ var ts; case 0: case 1: case 3: - return !(token === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); case 2: - return token === 71 || token === 77; + return token() === 71 || token() === 77; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); case 6: - return token === 19 || isLiteralPropertyName(); + return token() === 19 || isLiteralPropertyName(); case 12: - return token === 19 || token === 37 || isLiteralPropertyName(); + return token() === 19 || token() === 37 || isLiteralPropertyName(); case 9: - return token === 19 || isLiteralPropertyName(); + return token() === 19 || isLiteralPropertyName(); case 7: - if (token === 15) { + if (token() === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -7273,23 +11052,23 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token === 24 || token === 22 || isIdentifierOrPattern(); + return token() === 24 || token() === 22 || isIdentifierOrPattern(); case 17: return isIdentifier(); case 11: case 15: - return token === 24 || token === 22 || isStartOfExpression(); + return token() === 24 || token() === 22 || isStartOfExpression(); case 16: return isStartOfParameter(); case 18: case 19: - return token === 24 || isStartOfType(); + return token() === 24 || isStartOfType(); case 20: return isHeritageClause(); case 21: - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); case 13: - return ts.tokenIsIdentifierOrKeyword(token) || token === 15; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; case 14: return true; case 22: @@ -7302,7 +11081,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token === 15); + ts.Debug.assert(token() === 15); if (nextToken() === 16) { var next = nextToken(); return next === 24 || next === 15 || next === 83 || next === 106; @@ -7315,11 +11094,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token === 106 || - token === 83) { + if (token() === 106 || + token() === 83) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -7329,7 +11108,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token === 1) { + if (token() === 1) { return true; } switch (kind) { @@ -7341,49 +11120,49 @@ var ts; case 12: case 9: case 21: - return token === 16; + return token() === 16; case 3: - return token === 16 || token === 71 || token === 77; + return token() === 16 || token() === 71 || token() === 77; case 7: - return token === 15 || token === 83 || token === 106; + return token() === 15 || token() === 83 || token() === 106; case 8: return isVariableDeclaratorListTerminator(); case 17: - return token === 27 || token === 17 || token === 15 || token === 83 || token === 106; + return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; case 11: - return token === 18 || token === 23; + return token() === 18 || token() === 23; case 15: case 19: case 10: - return token === 20; + return token() === 20; case 16: - return token === 18 || token === 20; + return token() === 18 || token() === 20; case 18: - return token === 27 || token === 17; + return token() === 27 || token() === 17; case 20: - return token === 15 || token === 16; + return token() === 15 || token() === 16; case 13: - return token === 27 || token === 39; + return token() === 27 || token() === 39; case 14: - return token === 25 && lookAhead(nextTokenIsSlash); + return token() === 25 && lookAhead(nextTokenIsSlash); case 22: - return token === 18 || token === 54 || token === 16; + return token() === 18 || token() === 54 || token() === 16; case 23: - return token === 27 || token === 16; + return token() === 27 || token() === 16; case 25: - return token === 20 || token === 16; + return token() === 20 || token() === 16; case 24: - return token === 16; + return token() === 16; } } function isVariableDeclaratorListTerminator() { if (canParseSemicolon()) { return true; } - if (isInOrOfKeyword(token)) { + if (isInOrOfKeyword(token())) { return true; } - if (token === 34) { + if (token() === 34) { return true; } return false; @@ -7401,8 +11180,7 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); @@ -7441,7 +11219,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 197132288; + var nodeContextFlags = node.flags & 1540096; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -7623,8 +11401,7 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); var commaStart = -1; while (true) { if (isListElement(kind, false)) { @@ -7638,7 +11415,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -7658,11 +11435,7 @@ var ts; return result; } function createMissingList() { - var pos = getNodePos(); - var result = []; - result.pos = pos; - result.end = pos; - return result; + return createNodeArray(); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -7683,7 +11456,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); @@ -7695,8 +11468,7 @@ var ts; var template = createNode(189); template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); - var templateSpans = []; - templateSpans.pos = getNodePos(); + var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); } while (ts.lastOrUndefined(templateSpans).literal.kind === 13); @@ -7708,7 +11480,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16) { + if (token() === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -7718,14 +11490,11 @@ var ts; span.literal = literal; return finishNode(span); } - function parseStringLiteralTypeNode() { - return parseLiteralLikeNode(166, true); - } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token, internName); + return parseLiteralLikeNode(token(), internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token, false); + return parseLiteralLikeNode(token(), false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -7751,7 +11520,7 @@ var ts; var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); var node = createNode(155, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token === 25) { + if (!scanner.hasPrecedingLineBreak() && token() === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); @@ -7788,7 +11557,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25) { + if (token() === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -7799,26 +11568,20 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; - } - function setModifiers(node, modifiers) { - if (modifiers) { - node.flags |= modifiers.flags; - node.modifiers = modifiers; - } + return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; } function parseParameter() { var node = createNode(142); - if (token === 97) { + if (token() === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -7873,20 +11636,20 @@ var ts; } fillSignature(54, false, false, false, node); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token !== 19) { + if (token() !== 19) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token === 22 || token === 20) { + if (token() === 22 || token() === 20) { return true; } - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { nextToken(); if (isIdentifier()) { return true; @@ -7898,19 +11661,19 @@ var ts; else { nextToken(); } - if (token === 54 || token === 24) { + if (token() === 54 || token() === 24) { return true; } - if (token !== 53) { + if (token() !== 53) { return false; } nextToken(); - return token === 54 || token === 24 || token === 20; + return token() === 54 || token() === 24 || token() === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.parameters = parseBracketedList(16, parseParameter, 19, 20); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); @@ -7919,58 +11682,59 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { var method = createNode(146, fullStart); - setModifiers(method, modifiers); + method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; fillSignature(54, false, false, false, method); parseTypeMemberSemicolon(); - return finishNode(method); + return addJSDocComment(finishNode(method)); } else { var property = createNode(144, fullStart); - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56) { + if (token() === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } } function isTypeMemberStart() { var idToken; - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { return true; } - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); nextToken(); } - if (token === 19) { + if (token() === 19) { return true; } if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } if (idToken) { - return token === 17 || - token === 25 || - token === 53 || - token === 54 || + return token() === 17 || + token() === 25 || + token() === 53 || + token() === 54 || + token() === 24 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { return parseSignatureMember(151); } - if (token === 92 && lookAhead(isStartOfConstructSignature)) { + if (token() === 92 && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152); } var fullStart = getNodePos(); @@ -7982,7 +11746,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 || token === 25; + return token() === 17 || token() === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -8022,10 +11786,19 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token === 21 ? undefined : node; + return token() === 21 ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(166); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8; } function parseNonArrayType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -8036,13 +11809,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: - return parseStringLiteralTypeNode(); + case 8: + case 99: + case 84: + return parseLiteralTypeNode(); + case 36: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); case 103: case 93: return parseTokenNode(); case 97: { var thisKeyword = parseThisTypeNode(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -8062,7 +11840,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -8079,7 +11857,12 @@ var ts; case 25: case 92: case 9: + case 8: + case 99: + case 84: return true; + case 36: + return lookAhead(nextTokenIsNumericLiteral); case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); default: @@ -8088,7 +11871,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 || isStartOfParameter() || isStartOfType(); + return token() === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -8102,9 +11885,8 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { - var types = [type]; - types.pos = type.pos; + if (token() === operator) { + var types = createNodeArray([type], type.pos); while (parseOptional(operator)) { types.push(parseConstituentType()); } @@ -8122,20 +11904,20 @@ var ts; return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { - if (token === 25) { + if (token() === 25) { return true; } - return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { parseModifiers(); } - if (isIdentifier() || token === 97) { + if (isIdentifier() || token() === 97) { nextToken(); return true; } - if (token === 19 || token === 15) { + if (token() === 19 || token() === 15) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -8144,17 +11926,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token === 18 || token === 22) { + if (token() === 18 || token() === 22) { return true; } if (skipParameterStart()) { - if (token === 54 || token === 24 || - token === 53 || token === 56) { + if (token() === 54 || token() === 24 || + token() === 53 || token() === 56) { return true; } - if (token === 18) { + if (token() === 18) { nextToken(); - if (token === 34) { + if (token() === 34) { return true; } } @@ -8176,19 +11958,19 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseType() { - return doOutsideOfContext(41943040, parseTypeWorker); + return doOutsideOfContext(327680, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token === 92) { + if (token() === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -8197,7 +11979,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97: case 95: case 93: @@ -8225,7 +12007,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -8247,10 +12029,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token !== 15 && - token !== 87 && - token !== 73 && - token !== 55 && + return token() !== 15 && + token() !== 87 && + token() !== 73 && + token() !== 55 && isStartOfExpression(); } function parseExpression() { @@ -8269,8 +12051,8 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15) || !isStartOfExpression()) { + if (token() !== 56) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { return undefined; } } @@ -8286,7 +12068,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token === 34) { + if (expr.kind === 69 && token() === 34) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -8295,7 +12077,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114) { + if (token() === 114) { if (inYieldContext()) { return true; } @@ -8311,7 +12093,7 @@ var ts; var node = createNode(190); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token === 37 || isStartOfExpression())) { + (token() === 37 || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -8321,11 +12103,11 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180, asyncModifier.pos); - setModifiers(node, asyncModifier); + node.modifiers = asyncModifier; } else { node = createNode(180, identifier.pos); @@ -8333,12 +12115,11 @@ var ts; var parameter = createNode(142, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = [parameter]; - node.parameters.pos = parameter.pos; + node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; node.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function tryParseParenthesizedArrowFunctionExpression() { var triState = isParenthesizedArrowFunctionExpression(); @@ -8351,34 +12132,34 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token; + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return finishNode(arrowFunction); + return addJSDocComment(finishNode(arrowFunction)); } function isParenthesizedArrowFunctionExpression() { - if (token === 17 || token === 25 || token === 118) { + if (token() === 17 || token() === 25 || token() === 118) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token === 34) { + if (token() === 34) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token === 118) { + if (token() === 118) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token !== 17 && token !== 25) { + if (token() !== 17 && token() !== 25) { return 0; } } - var first = token; + var first = token(); var second = nextToken(); if (first === 17) { if (second === 18) { @@ -8441,7 +12222,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token === 118) { + if (token() === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -8452,13 +12233,13 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token === 118) { + if (token() === 118) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token === 34) { + if (scanner.hasPrecedingLineBreak() || token() === 34) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { return 1; } } @@ -8466,24 +12247,24 @@ var ts; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(180); - setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 256); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = !!(ts.getModifierFlags(node) & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token !== 34 && token !== 15) { + if (!allowAmbiguity && token() !== 34 && token() !== 15) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token === 15) { + if (token() === 15) { return parseFunctionBlock(false, isAsync, false); } - if (token !== 23 && - token !== 87 && - token !== 73 && + if (token() !== 23 && + token() !== 87 && + token() !== 73 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -8516,16 +12297,16 @@ var ts; while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token === 38 ? + var consumeCurrentOperator = token() === 38 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token === 90 && inDisallowInContext()) { + if (token() === 90 && inDisallowInContext()) { break; } - if (token === 116) { + if (token() === 116) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -8541,13 +12322,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token === 90) { + if (inDisallowInContext() && token() === 90) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token) { + switch (token()) { case 52: return 1; case 51: @@ -8602,7 +12383,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -8626,7 +12407,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119) { + if (token() === 119) { if (inAwaitContext()) { return true; } @@ -8641,18 +12422,15 @@ var ts; return finishNode(node); } function parseUnaryExpressionOrHigher() { - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - if (isIncrementExpression()) { + if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token === 38 ? + return token() === 38 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token; + var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token === 38) { + if (token() === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -8664,7 +12442,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -8678,12 +12456,16 @@ var ts; return parseVoidExpression(); case 25: return parseTypeAssertion(); + case 119: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } } - function isIncrementExpression() { - switch (token) { + function isUpdateExpression() { + switch (token()) { case 35: case 36: case 50: @@ -8691,6 +12473,7 @@ var ts; case 78: case 101: case 103: + case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -8701,29 +12484,29 @@ var ts; } } function parseIncrementExpression() { - if (token === 41 || token === 42) { + if (token() === 41 || token() === 42) { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { + if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186, expression.pos); node.operand = expression; - node.operator = token; + node.operator = token(); nextToken(); return finishNode(node); } return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token === 95 + var expression = token() === 95 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -8734,7 +12517,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token === 17 || token === 21 || token === 19) { + if (token() === 17 || token() === 21 || token() === 19) { return expression; } var node = createNode(172, expression.pos); @@ -8773,7 +12556,7 @@ var ts; ts.Debug.assert(opening.kind === 242); result = opening; } - if (inExpressionContext && token === 25) { + if (inExpressionContext && token() === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -8790,11 +12573,11 @@ var ts; } function parseJsxText() { var node = createNode(244, scanner.getStartPos()); - token = scanner.scanJsxToken(); + currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token) { + switch (token()) { case 244: return parseJsxText(); case 15: @@ -8802,19 +12585,18 @@ var ts; case 25: return parseJsxElementOrSelfClosingElement(false); } - ts.Debug.fail("Unknown JSX child kind " + token); + ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = []; - result.pos = scanner.getStartPos(); + var result = createNodeArray(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - token = scanner.reScanJsxToken(); - if (token === 26) { + currentToken = scanner.reScanJsxToken(); + if (token() === 26) { break; } - else if (token === 1) { + else if (token() === 1) { parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } @@ -8830,7 +12612,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token === 27) { + if (token() === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -8851,7 +12633,7 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token === 97 ? + var expression = token() === 97 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21)) { var propertyAccess = createNode(172, expression.pos); @@ -8864,7 +12646,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token !== 16) { + if (token() !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -8877,14 +12659,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token === 15) { + if (token() === 15) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246); node.name = parseIdentifierName(); - if (parseOptional(56)) { - switch (token) { + if (token() === 56) { + switch (scanJsxAttributeValue()) { case 9: node.initializer = parseLiteralNode(); break; @@ -8934,7 +12716,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token === 49 && !scanner.hasPrecedingLineBreak()) { + if (token() === 49 && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196, expression.pos); nonNullExpression.expression = expression; @@ -8944,7 +12726,7 @@ var ts; if (!inDecoratorContext() && parseOptional(19)) { var indexedAccess = createNode(173, expression.pos); indexedAccess.expression = expression; - if (token !== 20) { + if (token() !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; @@ -8955,10 +12737,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token === 11 || token === 12) { + if (token() === 11 || token() === 12) { var tagExpression = createNode(176, expression.pos); tagExpression.tag = expression; - tagExpression.template = token === 11 + tagExpression.template = token() === 11 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -8970,7 +12752,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token === 25) { + if (token() === 25) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; @@ -8982,7 +12764,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token === 17) { + else if (token() === 17) { var callExpr = createNode(174, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -9011,7 +12793,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17: case 21: case 18: @@ -9038,7 +12820,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8: case 9: case 11: @@ -9091,8 +12873,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token === 22 ? parseSpreadElement() : - token === 24 ? createNode(193) : + return token() === 22 ? parseSpreadElement() : + token() === 24 ? createNode(193) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -9110,7 +12892,7 @@ var ts; } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123)) { - return addJSDocComment(parseAccessorDeclaration(149, fullStart, decorators, modifiers)); + return parseAccessorDeclaration(149, fullStart, decorators, modifiers); } else if (parseContextualModifier(131)) { return parseAccessorDeclaration(150, fullStart, decorators, modifiers); @@ -9129,10 +12911,10 @@ var ts; var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token === 17 || token === 25) { + if (asteriskToken || token() === 17 || token() === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254, fullStart); shorthandDeclaration.name = propertyName; @@ -9170,11 +12952,11 @@ var ts; setDecoratorContext(false); } var node = createNode(179); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); parseExpected(87); node.asteriskToken = parseOptionalToken(37); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256); + var isAsync = !!(ts.getModifierFlags(node) & 256); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -9195,7 +12977,7 @@ var ts; parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token === 17) { + if (node.typeArguments || token() === 17) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -9203,6 +12985,9 @@ var ts; function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var node = createNode(199); if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.statements = parseList(1, parseStatement); parseExpected(16); } @@ -9268,8 +13053,8 @@ var ts; parseExpected(86); parseExpected(17); var initializer = undefined; - if (token !== 23) { - if (token === 102 || token === 108 || token === 74) { + if (token() !== 23) { + if (token() === 102 || token() === 108 || token() === 74) { initializer = parseVariableDeclarationList(true); } else { @@ -9295,11 +13080,11 @@ var ts; var forStatement = createNode(206, pos); forStatement.initializer = initializer; parseExpected(23); - if (token !== 23 && token !== 18) { + if (token() !== 23 && token() !== 18) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23); - if (token !== 18) { + if (token() !== 18) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18); @@ -9351,7 +13136,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -9377,8 +13162,8 @@ var ts; var node = createNode(216); parseExpected(100); node.tryBlock = parseBlock(false); - node.catchClause = token === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token === 85) { + node.catchClause = token() === 72 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 85) { parseExpected(85); node.finallyBlock = parseBlock(false); } @@ -9418,19 +13203,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token === 87 && !scanner.hasPrecedingLineBreak(); + return token() === 87 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token) || token === 8) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -9458,16 +13243,16 @@ var ts; continue; case 137: nextToken(); - return token === 15 || token === 69 || token === 82; + return token() === 15 || token() === 69 || token() === 82; case 89: nextToken(); - return token === 9 || token === 37 || - token === 15 || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 || token() === 37 || + token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); case 82: nextToken(); - if (token === 56 || token === 37 || - token === 15 || token === 77 || - token === 116) { + if (token() === 56 || token() === 37 || + token() === 15 || token() === 77 || + token() === 116) { return true; } continue; @@ -9483,7 +13268,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55: case 23: case 15: @@ -9531,13 +13316,13 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token === 15 || token === 19; + return isIdentifier() || token() === 15 || token() === 19; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token) { + switch (token()) { case 23: return parseEmptyStatement(); case 15: @@ -9609,7 +13394,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -9632,7 +13417,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token) { + switch (token()) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -9646,24 +13431,24 @@ var ts; var node = createMissingNode(239, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; return finishNode(node); } } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token !== 15 && canParseSemicolon()) { + if (token() !== 15 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token === 24) { + if (token() === 24) { return createNode(193); } var node = createNode(169); @@ -9676,7 +13461,7 @@ var ts; var node = createNode(169); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token !== 54) { + if (tokenIsIdentifier && token() !== 54) { node.name = propertyName; } else { @@ -9702,13 +13487,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token === 15 || token === 19 || isIdentifier(); + return token() === 15 || token() === 19 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token === 19) { + if (token() === 19) { return parseArrayBindingPattern(); } - if (token === 15) { + if (token() === 15) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -9717,27 +13502,27 @@ var ts; var node = createNode(218); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token)) { + if (!isInOrOfKeyword(token())) { node.initializer = parseInitializer(false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219); - switch (token) { + switch (token()) { case 102: break; case 108: - node.flags |= 1024; + node.flags |= 1; break; case 74: - node.flags |= 2048; + node.flags |= 2; break; default: ts.Debug.fail(); } nextToken(); - if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -9754,7 +13539,7 @@ var ts; function parseVariableStatement(fullStart, decorators, modifiers) { var node = createNode(200, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); return addJSDocComment(finishNode(node)); @@ -9762,12 +13547,12 @@ var ts; function parseFunctionDeclaration(fullStart, decorators, modifiers) { var node = createNode(220, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(87); node.asteriskToken = parseOptionalToken(37); - node.name = node.flags & 512 ? parseOptionalIdentifier() : parseIdentifier(); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256); + var isAsync = ts.hasModifier(node, 256); fillSignature(54, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); @@ -9775,7 +13560,7 @@ var ts; function parseConstructorDeclaration(pos, decorators, modifiers) { var node = createNode(148, pos); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(121); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); @@ -9784,12 +13569,12 @@ var ts; function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { var method = createNode(147, fullStart); method.decorators = decorators; - setModifiers(method, modifiers); + method.modifiers = modifiers; method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 256); + var isAsync = ts.hasModifier(method, 256); fillSignature(54, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); @@ -9797,21 +13582,21 @@ var ts; function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { var property = createNode(145, fullStart); property.decorators = decorators; - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = modifiers && modifiers.flags & 32 + property.initializer = ts.hasModifier(property, 32) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(8388608 | 4194304, parseNonParameterInitializer); + : doOutsideOfContext(65536 | 32768, parseNonParameterInitializer); parseSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { var asteriskToken = parseOptionalToken(37); var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token === 17 || token === 25) { + if (asteriskToken || token() === 17 || token() === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -9824,11 +13609,11 @@ var ts; function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.name = parsePropertyName(); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -9844,31 +13629,31 @@ var ts; } function isClassMemberStart() { var idToken; - if (token === 55) { + if (token() === 55) { return true; } - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); if (isClassMemberModifier(idToken)) { return true; } nextToken(); } - if (token === 37) { + if (token() === 37) { return true; } if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } - if (token === 19) { + if (token() === 19) { return true; } if (idToken !== undefined) { if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { return true; } - switch (token) { + switch (token()) { case 17: case 25: case 54: @@ -9888,13 +13673,15 @@ var ts; if (!parseOptional(55)) { break; } - if (!decorators) { - decorators = []; - decorators.pos = decoratorStart; - } var decorator = createNode(143, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - decorators.push(finishNode(decorator)); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } } if (decorators) { decorators.end = getNodeEnd(); @@ -9902,12 +13689,11 @@ var ts; return decorators; } function parseModifiers(permitInvalidConstAsModifier) { - var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; - if (token === 74 && permitInvalidConstAsModifier) { + var modifierKind = token(); + if (token() === 74 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -9917,37 +13703,33 @@ var ts; break; } } + var modifier = finishNode(createNode(modifierKind, modifierStart)); if (!modifiers) { - modifiers = []; - modifiers.pos = modifierStart; + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); } - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); } if (modifiers) { - modifiers.flags = flags; modifiers.end = scanner.getStartPos(); } return modifiers; } function parseModifiersForArrowFunction() { - var flags = 0; var modifiers; - if (token === 118) { + if (token() === 118) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; + var modifierKind = token(); nextToken(); - modifiers = []; - modifiers.pos = modifierStart; - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); - modifiers.flags = flags; + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); modifiers.end = scanner.getStartPos(); } return modifiers; } function parseClassElement() { - if (token === 23) { + if (token() === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -9959,22 +13741,22 @@ var ts; if (accessor) { return accessor; } - if (token === 121) { + if (token() === 121) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); } - if (ts.tokenIsIdentifierOrKeyword(token) || - token === 9 || - token === 8 || - token === 37 || - token === 19) { + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8 || + token() === 37 || + token() === 19) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_7 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); + var name_10 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -9987,7 +13769,7 @@ var ts; function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(73); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -9999,7 +13781,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseNameOfClassDeclarationOrExpression() { return isIdentifier() && !isImplementsClause() @@ -10007,7 +13789,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -10016,9 +13798,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token === 83 || token === 106) { + if (token() === 83 || token() === 106) { var node = createNode(251); - node.token = token; + node.token = token(); nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); @@ -10028,13 +13810,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token === 25) { + if (token() === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } function isHeritageClause() { - return token === 83 || token === 106; + return token() === 83 || token() === 106; } function parseClassMembers() { return parseList(5, parseClassElement); @@ -10042,18 +13824,18 @@ var ts; function parseInterfaceDeclaration(fullStart, decorators, modifiers) { var node = createNode(222, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(107); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(false); node.members = parseObjectTypeMembers(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { var node = createNode(223, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(134); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -10066,12 +13848,12 @@ var ts; var node = createNode(255, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { var node = createNode(224, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(81); node.name = parseIdentifier(); if (parseExpected(15)) { @@ -10081,7 +13863,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseModuleBlock() { var node = createNode(226, scanner.getStartPos()); @@ -10096,28 +13878,28 @@ var ts; } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { var node = createNode(225, fullStart); - var namespaceFlag = flags & 4096; + var namespaceFlag = flags & 16; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 1 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) : parseModuleBlock(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { var node = createNode(225, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); - if (token === 137) { + node.modifiers = modifiers; + if (token() === 137) { node.name = parseIdentifier(); - node.flags |= 131072; + node.flags |= 512; } else { node.name = parseLiteralNode(true); } - if (token === 15) { + if (token() === 15) { node.body = parseModuleBlock(); } else { @@ -10126,23 +13908,23 @@ var ts; return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = modifiers ? modifiers.flags : 0; - if (token === 137) { + var flags = 0; + if (token() === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { - flags |= 4096; + flags |= 16; } else { parseExpected(125); - if (token === 9) { + if (token() === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 129 && + return token() === 129 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -10167,23 +13949,23 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 && token !== 136) { + if (token() !== 24 && token() !== 136) { var importEqualsDeclaration = createNode(229, fullStart); importEqualsDeclaration.decorators = decorators; - setModifiers(importEqualsDeclaration, modifiers); + importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; parseExpected(56); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); - return finishNode(importEqualsDeclaration); + return addJSDocComment(finishNode(importEqualsDeclaration)); } } var importDeclaration = createNode(230, fullStart); importDeclaration.decorators = decorators; - setModifiers(importDeclaration, modifiers); + importDeclaration.modifiers = modifiers; if (identifier || - token === 37 || - token === 15) { + token() === 37 || + token() === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -10198,7 +13980,7 @@ var ts; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); } return finishNode(importClause); } @@ -10216,7 +13998,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9) { + if (token() === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -10245,14 +14027,14 @@ var ts; } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token === 116) { + if (token() === 116) { node.propertyName = identifierName; parseExpected(116); - checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -10268,14 +14050,14 @@ var ts; function parseExportDeclaration(fullStart, decorators, modifiers) { var node = createNode(236, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(37)) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } else { node.exportClause = parseNamedImportsOrExports(237); - if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -10286,7 +14068,7 @@ var ts; function parseExportAssignment(fullStart, decorators, modifiers) { var node = createNode(235, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(56)) { node.isExportEquals = true; } @@ -10362,7 +14144,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 + return ts.hasModifier(node, 1) || node.kind === 229 && node.moduleReference.kind === 240 || node.kind === 230 || node.kind === 235 @@ -10374,7 +14156,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37: case 53: case 17: @@ -10387,13 +14169,14 @@ var ts; case 97: return true; } - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2, undefined, 1); + sourceFile = createSourceFile("file.js", 2, 1); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -10411,12 +14194,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token === 47) { + if (token() === 47) { var unionType = createNode(261, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token === 56) { + if (token() === 56) { var optionalType = createNode(268, type.pos); nextToken(); optionalType.type = type; @@ -10427,20 +14210,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token === 19) { + if (token() === 19) { var arrayType = createNode(260, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } - else if (token === 53) { + else if (token() === 53) { var nullableType = createNode(263, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token === 49) { + else if (token() === 49) { var nonNullableType = createNode(264, type.pos); nonNullableType.type = type; nextToken(); @@ -10453,7 +14236,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37: return parseJSDocAllType(); case 53: @@ -10480,7 +14263,15 @@ var ts; case 120: case 133: case 103: + case 93: + case 135: + case 127: return parseTokenNode(); + case 9: + case 8: + case 99: + case 84: + return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } @@ -10511,7 +14302,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -10528,12 +14319,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267); result.name = parseSimplePropertyName(); - if (token === 25) { + if (token() === 25) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21)) { - if (token === 25) { + if (token() === 25) { result.typeArguments = parseTypeArguments(); break; } @@ -10567,19 +14358,7 @@ var ts; } function parseJSDocRecordType() { var result = createNode(265); - nextToken(); - result.members = parseDelimitedList(24, parseJSDocRecordMember); - checkForTrailingComma(result.members); - parseExpected(16); - return finishNode(result); - } - function parseJSDocRecordMember() { - var result = createNode(266); - result.name = parseSimplePropertyName(); - if (token === 54) { - nextToken(); - result.type = parseJSDocType(); - } + result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { @@ -10611,9 +14390,7 @@ var ts; } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); - var types = []; - types.pos = firstType.pos; - types.push(firstType); + var types = createNodeArray([firstType], firstType.pos); while (parseOptional(47)) { types.push(parseJSDocType()); } @@ -10625,15 +14402,20 @@ var ts; nextToken(); return finishNode(result); } + function parseJSDocLiteralType() { + var result = createNode(282); + result.literal = parseLiteralTypeNode(); + return finishNode(result); + } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token === 24 || - token === 16 || - token === 18 || - token === 27 || - token === 56 || - token === 47) { + if (token() === 24 || + token() === 16 || + token() === 18 || + token() === 27 || + token() === 56 || + token() === 47) { var result = createNode(259, pos); return finishNode(result); } @@ -10646,21 +14428,21 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { initializeState("file.js", content, 2, undefined, 1); sourceFile = { languageVariant: 0, text: content }; - var jsDocComment = parseJSDocCommentWorker(start, length); + var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); - return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -10675,125 +14457,254 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var comments = []; var result; - if (content.charCodeAt(start) === 47 && - content.charCodeAt(start + 1) === 42 && - content.charCodeAt(start + 2) === 42 && - content.charCodeAt(start + 3) !== 42) { - scanner.scanRange(start + 3, length - 5, function () { - var canParseTag = true; - var seenAsterisk = true; + if (!isJsDocStart(content, start)) { + return result; + } + scanner.scanRange(start + 3, length - 5, function () { + var advanceToken = true; + var state = 1; + var margin = undefined; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5) { nextJSDocToken(); - while (token !== 1) { - switch (token) { - case 55: - if (canParseTag) { - parseTag(); - } - seenAsterisk = false; - break; - case 4: - canParseTag = true; - seenAsterisk = false; - break; - case 37: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 69: - canParseTag = false; - break; - case 1: - break; - } + } + if (token() === 4) { + state = 0; + nextJSDocToken(); + } + while (token() !== 1) { + switch (token()) { + case 55: + if (state === 0 || state === 1) { + removeTrailingNewlines(comments); + parseTag(indent); + state = 0; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 37: + var asterisk = scanner.getTokenText(); + if (state === 1) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 69: + pushComment(scanner.getTokenText()); + state = 2; + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break; + default: + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { nextJSDocToken(); } - result = createJSDocComment(); - }); - } - return result; - function createJSDocComment() { - if (!tags) { - return undefined; + else { + advanceToken = true; + } } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42; + } + function createJSDocComment() { var result = createNode(273, start); result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 || token === 4) { + while (token() === 5 || token() === 4) { nextJSDocToken(); } } - function parseTag() { - ts.Debug.assert(token === 55); + function parseTag(indent) { + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return; } - var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); - addTag(tag); - } - function handleTag(atToken, tagName) { + var tag; if (tagName) { switch (tagName.text) { case "param": - return handleParamTag(atToken, tagName); + tag = parseParamTag(atToken, tagName); + break; case "return": case "returns": - return handleReturnTag(atToken, tagName); + tag = parseReturnTag(atToken, tagName); + break; case "template": - return handleTemplateTag(atToken, tagName); + tag = parseTemplateTag(atToken, tagName); + break; case "type": - return handleTypeTag(atToken, tagName); + tag = parseTypeTag(atToken, tagName); + break; case "typedef": - return handleTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; } } - return undefined; + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); } - function handleUnknownTag(atToken, tagName) { + function parseTagComments(indent) { + var comments = []; + var state = 1; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 55 && token() !== 1) { + switch (token()) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 55: + break; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 37: + if (state === 0) { + state = 1; + indent += scanner.getTokenText().length; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (token() === 55) { + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { var result = createNode(274, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } - function addTag(tag) { - if (tag) { - if (!tags) { - tags = []; - tags.pos = tag.pos; - } - tags.push(tag); - tags.end = tag.end; + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); } + else { + tags.push(tag); + } + tags.end = tag.end; } function tryParseTypeExpression() { - if (token !== 15) { - return undefined; - } - var typeExpression = parseJSDocTypeExpression(); - return typeExpression; + return tryParse(function () { + skipWhitespace(); + if (token() !== 15) { + return undefined; + } + return parseJSDocTypeExpression(); + }); } - function handleParamTag(atToken, tagName) { + function parseParamTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name; var isBracketed; if (parseOptionalToken(19)) { name = parseJSDocIdentifierName(); + skipWhitespace(); isBracketed = true; if (parseOptionalToken(56)) { parseExpression(); } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -10816,10 +14727,11 @@ var ts; result.preParameterName = preName; result.typeExpression = typeExpression; result.postParameterName = postName; + result.parameterName = postName || preName; result.isBracketed = isBracketed; return finishNode(result); } - function handleReturnTag(atToken, tagName) { + function parseReturnTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 276; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -10829,7 +14741,7 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handleTypeTag(atToken, tagName) { + function parseTypeTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 277; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -10839,10 +14751,11 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handlePropertyTag(atToken, tagName) { + function parsePropertyTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name = parseJSDocIdentifierName(); + skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; @@ -10854,7 +14767,7 @@ var ts; result.typeExpression = typeExpression; return finishNode(result); } - function handleTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var typedefTag = createNode(279, atToken.pos); @@ -10862,12 +14775,13 @@ var ts; typedefTag.tagName = tagName; typedefTag.name = parseJSDocIdentifierName(); typedefTag.typeExpression = typeExpression; + skipWhitespace(); if (typeExpression) { if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_8 = jsDocTypeReference.name; - if (name_8.text === "Object") { + var name_11 = jsDocTypeReference.name; + if (name_11.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -10886,12 +14800,15 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token !== 1 && !parentTagTerminated) { + while (token() !== 1 && !parentTagTerminated) { nextJSDocToken(); - switch (token) { + switch (token()) { case 55: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); + if (!parentTagTerminated) { + resumePos = scanner.getStartPos(); + } } seenAsterisk = false; break; @@ -10917,11 +14834,12 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token === 55); + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return false; } @@ -10930,37 +14848,38 @@ var ts; if (parentTag.jsDocTypeTag) { return false; } - parentTag.jsDocTypeTag = handleTypeTag(atToken, tagName); + parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); return true; case "prop": case "property": if (!parentTag.jsDocPropertyTags) { parentTag.jsDocPropertyTags = []; } - var propertyTag = handlePropertyTag(atToken, tagName); + var propertyTag = parsePropertyTag(atToken, tagName); parentTag.jsDocPropertyTags.push(propertyTag); return true; } return false; } - function handleTemplateTag(atToken, tagName) { + function parseTemplateTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 278; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var typeParameters = []; - typeParameters.pos = scanner.getStartPos(); + var typeParameters = createNodeArray(); while (true) { - var name_9 = parseJSDocIdentifierName(); - if (!name_9) { + var name_12 = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name_12) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(141, name_12.pos); + typeParameter.name = name_12; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24) { + if (token() === 24) { nextJSDocToken(); + skipWhitespace(); } else { break; @@ -10975,10 +14894,10 @@ var ts; return result; } function nextJSDocToken() { - return token = scanner.scanJSDocToken(); + return currentToken = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -11284,7 +15203,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -11292,7 +15210,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 230 || node.kind === 229) && !(node.flags & 1)) { + else if ((node.kind === 230 || node.kind === 229) && !(ts.hasModifier(node, 1))) { return 0; } else if (node.kind === 226) { @@ -11322,9 +15240,10 @@ var ts; ts.getModuleInstanceState = getModuleInstanceState; var binder = createBinder(); function bindSourceFile(file, options) { - var start = new Date().getTime(); + ts.performance.mark("beforeBind"); binder(file, options); - ts.bindTime += new Date().getTime() - start; + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -11352,13 +15271,16 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 }; var reportedUnreachableFlow = { flags: 1 }; + var subtreeTransformFlags = 0; + var skipTransformFlagAggregation; function bindSourceFile(f, opts) { file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; + skipTransformFlagAggregation = ts.isDeclarationFile(file); Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -11382,6 +15304,7 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0; + subtreeTransformFlags = 0; } return bindSourceFile; function createSymbol(flags, name) { @@ -11396,10 +15319,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = {}; + symbol.exports = ts.createMap(); } if (symbolFlags & 6240 && !symbol.members) { - symbol.members = {}; + symbol.members = ts.createMap(); } if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; @@ -11453,14 +15376,14 @@ var ts; break; case 220: case 221: - return node.flags & 512 ? "default" : undefined; + return ts.hasModifier(node, 512) ? "default" : undefined; case 269: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; case 142: ts.Debug.assert(node.parent.kind === 269); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); - return "p" + index; + return "arg" + index; case 279: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; @@ -11480,44 +15403,47 @@ var ts; } function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512; + var isDefaultExport = ts.hasModifier(node, 512); var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name !== undefined) { - symbol = ts.hasProperty(symbolTable, name) - ? symbolTable[name] - : (symbolTable[name] = createSymbol(0, name)); + if (name === undefined) { + symbol = createSymbol(0, "__missing"); + } + else { + symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0, name)); if (name && (includes & 788448)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (node.name) { - node.name.parent = node; + if (symbol.isReplaceableByMethod) { + symbol = symbolTable[name] = createSymbol(0, name); } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + else { + if (node.name) { + node.name.parent = node; } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (ts.hasModifier(declaration, 512)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); + } } } - else { - symbol = createSymbol(0, "__missing"); - } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 8388608) { if (node.kind === 238 || (node.kind === 229 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -11527,10 +15453,10 @@ var ts; } } else { - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793056 ? 2097152 : 0) | - (symbolFlags & 1536 ? 4194304 : 0); + (symbolFlags & 793064 ? 2097152 : 0) | + (symbolFlags & 1920 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -11547,7 +15473,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -11578,11 +15504,11 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); - node.flags &= ~4030464; + node.flags &= ~32128; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { - node.flags |= 32768; + node.flags |= 128; if (hasExplicitReturn) - node.flags |= 65536; + node.flags |= 256; } if (node.kind === 256) { node.flags |= emitFlags; @@ -11603,7 +15529,7 @@ var ts; else if (containerFlags & 64) { seenThisKeyword = false; bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 16384 : node.flags & ~16384; + node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; } else { bindChildren(node); @@ -11612,11 +15538,24 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindChildrenWorker(node) { if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - bind(jsDocComment); - } + ts.forEach(node.jsDocComments, bind); } if (checkUnreachable(node)) { ts.forEachChild(node, bind); @@ -11665,6 +15604,9 @@ var ts; case 185: bindPrefixUnaryExpressionFlow(node); break; + case 186: + bindPostfixUnaryExpressionFlow(node); + break; case 187: bindBinaryExpressionFlow(node); break; @@ -11722,15 +15664,9 @@ var ts; } return false; } - function isNarrowingNullCheckOperands(expr1, expr2) { - return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); - } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } - function isNarrowingDiscriminant(expr) { - return expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -11739,9 +15675,8 @@ var ts; case 31: case 32: case 33: - return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || - isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 91: return isNarrowableOperand(expr.left); case 24: @@ -11763,10 +15698,6 @@ var ts; } return isNarrowableReference(expr); } - function isNarrowingSwitchStatement(switchStatement) { - var expr = switchStatement.expression; - return expr.kind === 172 && isNarrowableReference(expr.expression); - } function createBranchLabel() { return { flags: 4, @@ -11810,7 +15741,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -12151,6 +16082,15 @@ var ts; } else { ts.forEachChild(node, bind); + if (node.operator === 57 || node.operator === 42) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + ts.forEachChild(node, bind); + if (node.operator === 41 || node.operator === 42) { + bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { @@ -12192,7 +16132,7 @@ var ts; currentFlow = finishFlowLabel(postExpressionLabel); } function bindInitializedVariableFlow(node) { - var name = node.name; + var name = !ts.isOmittedExpression(node) ? node.name : undefined; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var child = _a[_i]; @@ -12316,7 +16256,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 32 + return ts.hasModifier(node, 32) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -12339,16 +16279,16 @@ var ts; } function setExportContextFlag(node) { if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 8192; + node.flags |= 32; } else { - node.flags &= ~8192; + node.flags &= ~32; } } function bindModuleDeclaration(node) { setExportContextFlag(node); if (ts.isAmbientModule(node)) { - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (ts.isExternalModuleAugmentation(node)) { @@ -12398,12 +16338,12 @@ var ts; addDeclarationToSymbol(symbol, node, 131072); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; + typeLiteralSymbol.members = ts.createMap(); + typeLiteralSymbol.members[symbol.name] = symbol; } function bindObjectLiteralExpression(node) { if (inStrictMode) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69) { @@ -12419,8 +16359,8 @@ var ts; continue; } if (currentKind === 1 && existingKind === 1) { - var span = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -12442,7 +16382,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -12483,8 +16423,8 @@ var ts; } function checkStrictModeDeleteExpression(node) { if (inStrictMode && node.expression.kind === 69) { - var span = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -12495,8 +16435,8 @@ var ts; if (name && name.kind === 69) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { - var span = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } } } @@ -12581,6 +16521,9 @@ var ts; } parent = saveParent; } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } inStrictMode = saveInStrictMode; } function updateStrictModeStatementList(statements) { @@ -12655,7 +16598,7 @@ var ts; case 154: return checkTypePredicate(node); case 141: - return declareSymbolAndAddToSymbolTable(node, 262144, 530912); + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); case 142: return bindParameter(node); case 218: @@ -12671,9 +16614,9 @@ var ts; case 254: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 107455); + return bindPropertyOrMethodOrAccessor(node, 8, 900095); case 247: - emitFlags |= 1073741824; + emitFlags |= 16384; return; case 151: case 152: @@ -12713,10 +16656,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222: - return bindBlockScopedDeclaration(node, 64, 792960); + return bindBlockScopedDeclaration(node, 64, 792968); case 279: case 223: - return bindBlockScopedDeclaration(node, 524288, 793056); + return bindBlockScopedDeclaration(node, 524288, 793064); case 224: return bindEnumDeclaration(node); case 225: @@ -12765,15 +16708,14 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 235 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } - else if (boundExpression.kind === 69 && node.kind === 235) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); - } else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); + var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) + ? 8388608 + : 4; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); } } function bindNamespaceExportDeclaration(node) { @@ -12795,7 +16737,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || {}; + file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); } function bindExportDeclaration(node) { @@ -12826,18 +16768,20 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); } function bindThisPropertyAssignment(node) { - var assignee; - if (container.kind === 220 || container.kind === 220) { - assignee = container; + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (container.kind === 220 || container.kind === 179) { + container.symbol.members = container.symbol.members || ts.createMap(); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } else if (container.kind === 148) { - assignee = container.parent; + var saveContainer = container; + container = container.parent; + var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); + if (symbol) { + symbol.isReplaceableByMethod = true; + } + container = saveContainer; } - else { - return; - } - assignee.symbol.members = assignee.symbol.members || {}; - declareSymbol(assignee.symbol.members, assignee.symbol, node, 4, 0 & ~4); } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; @@ -12851,7 +16795,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -12863,10 +16807,10 @@ var ts; function bindClassLikeDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 262144; + emitFlags |= 1024; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288; + emitFlags |= 2048; } } if (node.kind === 221) { @@ -12881,7 +16825,7 @@ var ts; } var symbol = node.symbol; var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (symbol.exports[prototypeSymbol.name]) { if (node.name) { node.name.parent = node; } @@ -12915,7 +16859,7 @@ var ts; if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node) && ts.nodeIsDecorated(node)) { - emitFlags |= (524288 | 1048576); + emitFlags |= (2048 | 4096); } if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); @@ -12934,7 +16878,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } } checkStrictModeFunctionName(node); @@ -12949,7 +16893,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } } if (currentFlow) { @@ -12962,10 +16906,10 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288; + emitFlags |= 2048; } } return ts.hasDynamicName(node) @@ -12984,7 +16928,7 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatement(node) && node.kind !== 201) || + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 201) || node.kind === 221 || (node.kind === 225 && shouldReportErrorOnModuleDeclaration(node)) || (node.kind === 224 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); @@ -12993,7 +16937,7 @@ var ts; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && (node.kind !== 200 || - ts.getCombinedNodeFlags(node.declarationList) & 3072 || + ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); @@ -13003,9 +16947,517 @@ var ts; return true; } } + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 174: + return computeCallExpression(node, subtreeFlags); + case 225: + return computeModuleDeclaration(node, subtreeFlags); + case 178: + return computeParenthesizedExpression(node, subtreeFlags); + case 187: + return computeBinaryExpression(node, subtreeFlags); + case 202: + return computeExpressionStatement(node, subtreeFlags); + case 142: + return computeParameter(node, subtreeFlags); + case 180: + return computeArrowFunction(node, subtreeFlags); + case 179: + return computeFunctionExpression(node, subtreeFlags); + case 220: + return computeFunctionDeclaration(node, subtreeFlags); + case 218: + return computeVariableDeclaration(node, subtreeFlags); + case 219: + return computeVariableDeclarationList(node, subtreeFlags); + case 200: + return computeVariableStatement(node, subtreeFlags); + case 214: + return computeLabeledStatement(node, subtreeFlags); + case 221: + return computeClassDeclaration(node, subtreeFlags); + case 192: + return computeClassExpression(node, subtreeFlags); + case 251: + return computeHeritageClause(node, subtreeFlags); + case 194: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 148: + return computeConstructor(node, subtreeFlags); + case 145: + return computePropertyDeclaration(node, subtreeFlags); + case 147: + return computeMethod(node, subtreeFlags); + case 149: + case 150: + return computeAccessor(node, subtreeFlags); + case 229: + return computeImportEquals(node, subtreeFlags); + case 172: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (subtreeFlags & 262144 + || isSuperOrSuperProperty(expression, expressionKind)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537133909; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 95: + return true; + case 172: + case 173: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 95; + } + return false; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 56 + && (leftKind === 171 + || leftKind === 170)) { + transformFlags |= 192 | 256; + } + else if (operatorTokenKind === 38 + || operatorTokenKind === 60) { + transformFlags |= 48; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + if (node.questionToken) { + transformFlags |= 3; + } + if (subtreeFlags & 2048 + || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + transformFlags |= 3; + } + if (modifierFlags & 92) { + transformFlags |= 3 | 131072; + } + if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { + transformFlags |= 192 | 65536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~538968917; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + if (expressionKind === 195 + || expressionKind === 177) { + transformFlags |= 3; + } + if (expressionTransformFlags & 256) { + transformFlags |= 256; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 192; + if ((subtreeFlags & 137216) + || (modifierFlags & 1)) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537590613; + } + function computeClassExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (subtreeFlags & 137216) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537590613; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 83: + transformFlags |= 192; + break; + case 106: + transformFlags |= 3; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.typeArguments) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var body = node.body; + if (body === undefined) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computeMethod(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var typeParameters = node.typeParameters; + var asteriskToken = node.asteriskToken; + if (!body + || typeParameters + || (modifierFlags & (256 | 128)) + || (subtreeFlags & 2048)) { + transformFlags |= 3; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body + || (modifierFlags & (256 | 128)) + || (subtreeFlags & 2048)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computePropertyDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags | 3; + if (node.initializer) { + transformFlags |= 4096; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var asteriskToken = node.asteriskToken; + if (!body || (modifierFlags & 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 8388608; + if (modifierFlags & 1) { + transformFlags |= 3 | 192; + } + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550726485; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var asteriskToken = node.asteriskToken; + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550726485; + } + function computeArrowFunction(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 8192) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550710101; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (expressionKind === 95) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var nameKind = node.name.kind; + if (nameKind === 167 || nameKind === 168) { + transformFlags |= 192 | 2097152; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags; + if (modifierFlags & 1) { + transformFlags |= 192 | 3; + } + if (declarationListTransformFlags & 2097152) { + transformFlags |= 192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (subtreeFlags & 1048576 + && ts.isIterationStatement(node, true)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.expression.transformFlags & 256) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~546335573; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (node.flags & 3) { + transformFlags |= 192 | 1048576; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~538968917; + } + function computeOther(node, kind, subtreeFlags) { + var transformFlags = subtreeFlags; + var excludeFlags = 536871765; + switch (kind) { + case 112: + case 110: + case 111: + case 115: + case 122: + case 118: + case 74: + case 184: + case 224: + case 255: + case 177: + case 195: + case 196: + case 128: + transformFlags |= 3; + break; + case 241: + case 242: + case 243: + case 244: + case 245: + case 246: + case 247: + case 248: + transformFlags |= 12; + break; + case 82: + transformFlags |= 192 | 3; + break; + case 77: + case 11: + case 12: + case 13: + case 14: + case 189: + case 176: + case 254: + case 208: + transformFlags |= 192; + break; + case 190: + transformFlags |= 192 | 4194304; + break; + case 117: + case 130: + case 127: + case 132: + case 120: + case 133: + case 103: + case 141: + case 144: + case 146: + case 151: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 161: + case 162: + case 163: + case 164: + case 222: + case 223: + case 165: + case 166: + transformFlags = 3; + excludeFlags = -3; + break; + case 140: + transformFlags |= 524288; + if (subtreeFlags & 8192) { + transformFlags |= 32768; + } + break; + case 191: + transformFlags |= 262144; + break; + case 95: + transformFlags |= 192; + break; + case 97: + transformFlags |= 8192; + break; + case 167: + case 168: + transformFlags |= 192 | 2097152; + break; + case 143: + transformFlags |= 3 | 2048; + break; + case 171: + excludeFlags = 537430869; + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + break; + case 170: + case 175: + excludeFlags = 537133909; + if (subtreeFlags & 262144) { + transformFlags |= 192; + } + break; + case 204: + case 205: + case 206: + case 207: + if (subtreeFlags & 1048576) { + transformFlags |= 192; + } + break; + case 256: + if (subtreeFlags & 16384) { + transformFlags |= 192; + } + break; + case 211: + case 209: + case 210: + transformFlags |= 8388608; + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~excludeFlags; + } })(ts || (ts = {})); var ts; (function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -13018,7 +17470,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -13035,7 +17486,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = {}; + var emptySymbols = ts.createMap(); var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -13087,37 +17538,49 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, + getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var stringLiteralTypes = ts.createMap(); + var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var unknownType = createIntrinsicType(1, "unknown"); + var undefinedType = createIntrinsicType(2048, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); + var nullType = createIntrinsicType(4096, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); - var booleanType = createIntrinsicType(8, "boolean"); - var esSymbolType = createIntrinsicType(16777216, "symbol"); - var voidType = createIntrinsicType(16, "void"); - var undefinedType = createIntrinsicType(32, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 | 2097152, "undefined"); - var nullType = createIntrinsicType(64, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 | 2097152, "null"); - var unknownType = createIntrinsicType(1, "unknown"); - var neverType = createIntrinsicType(134217728, "never"); + var trueType = createIntrinsicType(128, "true"); + var falseType = createIntrinsicType(128, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512, "symbol"); + var voidType = createIntrinsicType(1024, "void"); + var neverType = createIntrinsicType(8192, "never"); + var silentNeverType = createIntrinsicType(8192, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = {}; + emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; + anyFunctionType.flags |= 134217728; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, undefined, 0, false, false); var enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = {}; + var globals = ts.createMap(); var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; + var tryGetGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; @@ -13150,10 +17613,8 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var tupleTypes = {}; - var unionTypes = {}; - var intersectionTypes = {}; - var stringLiteralTypes = {}; + var emptyStringType = getLiteralTypeForText(32, ""); + var zeroType = getLiteralTypeForText(64, "0"); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -13169,7 +17630,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1, "number": 2, "boolean": 4, @@ -13177,8 +17638,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128, "number": 256, "boolean": 512, @@ -13186,16 +17647,16 @@ var ts; "undefined": 131072, "object": 2048, "function": 4096 - }; - var typeofTypesByName = { + }); + var typeofTypesByName = ts.createMap({ "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }; + }); var jsxElementType; - var jsxTypes = {}; + var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -13205,15 +17666,14 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = {}; - var assignableRelation = {}; - var comparableRelation = {}; - var identityRelation = {}; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); var _displayBuilder; - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -13239,13 +17699,13 @@ var ts; if (flags & 4) result |= 0; if (flags & 8) - result |= 107455; + result |= 900095; if (flags & 16) result |= 106927; if (flags & 32) result |= 899519; if (flags & 64) - result |= 792960; + result |= 792968; if (flags & 256) result |= 899327; if (flags & 128) @@ -13259,9 +17719,9 @@ var ts; if (flags & 65536) result |= 74687; if (flags & 262144) - result |= 530912; + result |= 530920; if (flags & 524288) - result |= 793056; + result |= 793064; if (flags & 8388608) result |= 8388608; return result; @@ -13282,9 +17742,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = cloneSymbolTable(symbol.members); + result.members = ts.cloneMap(symbol.members); if (symbol.exports) - result.exports = cloneSymbolTable(symbol.exports); + result.exports = ts.cloneMap(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -13304,12 +17764,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = {}; + target.members = ts.createMap(); mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = {}; + target.exports = ts.createMap(); mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -13325,28 +17785,17 @@ var ts; }); } } - function cloneSymbolTable(symbolTable) { - var result = {}; - for (var id in symbolTable) { - if (ts.hasProperty(symbolTable, id)) { - result[id] = symbolTable[id]; - } - } - return result; - } function mergeSymbolTable(target, source) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (!ts.hasProperty(target, id)) { - target[id] = source[id]; - } - else { - var symbol = target[id]; - if (!(symbol.flags & 33554432)) { - target[id] = symbol = cloneSymbol(symbol); - } - mergeSymbol(symbol, source[id]); + var targetSymbol = target[id]; + if (!targetSymbol) { + target[id] = source[id]; + } + else { + if (!(targetSymbol.flags & 33554432)) { + target[id] = targetSymbol = cloneSymbol(targetSymbol); } + mergeSymbol(targetSymbol, source[id]); } } } @@ -13368,7 +17817,7 @@ var ts; return; } mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1536) { + if (mainModule.flags & 1920) { mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } @@ -13379,13 +17828,11 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (ts.hasProperty(target, id)) { - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; - } + if (target[id]) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; } } function addDeclarationDiagnostic(id, message) { @@ -13400,23 +17847,25 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning && ts.hasProperty(symbols, name)) { + if (meaning) { var symbol = symbols[name]; - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { + if (symbol) { + ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { return symbol; } + if (symbol.flags & 8388608) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } } } } @@ -13478,7 +17927,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 145 && - (current.parent.flags & 32) === 0 && + (ts.getModifierFlags(current.parent) & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -13500,7 +17949,7 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793056 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 142 || @@ -13537,7 +17986,7 @@ var ts; } result = undefined; } - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -13554,7 +18003,7 @@ var ts; break; case 145: case 144: - if (ts.isClassLike(location.parent) && !(location.flags & 32)) { + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -13566,8 +18015,8 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { - if (lastLocation && lastLocation.flags & 32) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -13584,7 +18033,7 @@ var ts; case 140: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -13635,8 +18084,10 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -13654,7 +18105,7 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule) { + if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -13664,7 +18115,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -13680,7 +18131,7 @@ var ts; error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); return true; } - if (location === container && !(location.flags & 32)) { + if (location === container && !(ts.getModifierFlags(location) & 32)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); @@ -13693,25 +18144,32 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var parentClassExpression = errorLocation; - while (parentClassExpression) { - var kind = parentClassExpression.kind; - if (kind === 69 || kind === 172) { - parentClassExpression = parentClassExpression.parent; - continue; - } - if (kind === 194) { - break; - } - return false; - } - if (!parentClassExpression) { - return false; - } - var expression = parentClassExpression.expression; - if (resolveEntityName(expression, 64, true)) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64, true)); + if (isError) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - return true; + } + return isError; + } + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 69: + case 172: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 194: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (107455 & ~1024)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + if (symbol && !(symbol.flags & 1024)) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } } return false; } @@ -13719,7 +18177,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -13757,7 +18215,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -13776,7 +18234,7 @@ var ts; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793056 | 1536)) { + if (valueSymbol.flags & (793064 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -13792,9 +18250,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536) { - var exports = getExportsOfSymbol(symbol); - if (ts.hasProperty(exports, name)) { - return resolveSymbol(exports[name]); + var exportedSymbol = getExportsOfSymbol(symbol)[name]; + if (exportedSymbol) { + return resolveSymbol(exportedSymbol); } } } @@ -13810,25 +18268,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { - if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + var name_13 = specifier.propertyName || specifier.name; + if (name_13.text) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); } return symbol; } @@ -13843,10 +18304,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536); + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 | 793056 | 1536); + return resolveEntityName(node.expression, 107455 | 793064 | 1920); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -13867,7 +18328,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793056 | 1536)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); @@ -13875,6 +18336,7 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -13904,6 +18366,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -13920,24 +18383,24 @@ var ts; entityName = entityName.parent; } if (entityName.kind === 69 || entityName.parent.kind === 139) { - return resolveEntityName(entityName, 1536, false, dontResolveAlias); + return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { ts.Debug.assert(entityName.parent.kind === 229); - return resolveEntityName(entityName, 107455 | 793056 | 1536, false, dontResolveAlias); + return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); } - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias) { + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } var symbol; if (name.kind === 69) { - var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } @@ -13945,7 +18408,7 @@ var ts; else if (name.kind === 139 || name.kind === 172) { var left = name.kind === 139 ? name.left : name.expression; var right = name.kind === 139 ? name.right : name.name; - var namespace = resolveEntityName(left, 1536, ignoreErrors); + var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -13955,7 +18418,7 @@ var ts; symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); } return undefined; } @@ -13974,7 +18437,10 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; - var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } @@ -13985,14 +18451,14 @@ var ts; return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return getMergedSymbol(sourceFile.symbol); } if (moduleNotFoundError) { - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return undefined; } @@ -14003,7 +18469,14 @@ var ts; } } if (moduleNotFoundError) { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } return undefined; } @@ -14033,7 +18506,7 @@ var ts; } function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !ts.hasProperty(target, id)) { + if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -14041,7 +18514,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -14059,11 +18532,11 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = cloneSymbolTable(symbol.exports); + var symbols = ts.cloneMap(symbol.exports); var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = {}; - var lookupTable = {}; + var nestedSymbols = ts.createMap(); + var lookupTable = ts.createMap(); for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -14072,7 +18545,7 @@ var ts; } for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -14123,8 +18596,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount; typeCount++; + result.id = typeCount; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -14132,6 +18605,12 @@ var ts; type.intrinsicName = intrinsicName; return type; } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8; + type.intrinsicName = "boolean"; + return type; + } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -14146,14 +18625,12 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (ts.hasProperty(members, id)) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); } } } @@ -14171,7 +18648,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -14196,7 +18673,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1536; + return rightMeaning === 107455 ? 107455 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -14213,10 +18690,10 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(ts.lookUp(symbols, symbol.name))) { + if (isAccessible(symbols[symbol.name])) { return [symbol]; } - return ts.forEachValue(symbols, function (symbolFromSymbolTable) { + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { @@ -14243,10 +18720,10 @@ var ts; function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - if (!ts.hasProperty(symbolTable, symbol.name)) { + var symbolFromSymbolTable = symbolTable[symbol.name]; + if (!symbolFromSymbolTable) { return false; } - var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { return true; } @@ -14277,19 +18754,19 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined }; } return hasAccessibleDeclarations; @@ -14325,7 +18802,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -14335,16 +18812,18 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1) && + !(ts.getModifierFlags(anyImportSyntax) & 1) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -14360,14 +18839,14 @@ var ts; } else if (entityName.kind === 139 || entityName.kind === 172 || entityName.parent.kind === 229) { - meaning = 1536; + meaning = 1920; } else { - meaning = 793056; + meaning = 793064; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -14414,6 +18893,31 @@ var ts; ts.releaseStringWriter(writer); return result; } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144)) { + if (t.flags & (128 | 256)) { + var baseType = t.flags & 128 ? booleanType : t.baseType; + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } + } + result.push(t); + } + } + if (flags & 4096) + result.push(nullType); + if (flags & 2048) + result.push(undefinedType); + return result || types; + } function visibilityToString(flags) { if (flags === 8) { return "private"; @@ -14440,6 +18944,9 @@ var ts; node.parent.kind === 226 && ts.isExternalModuleAugmentation(node.parent.parent); } + function literalTypeToString(type) { + return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -14499,71 +19006,77 @@ var ts; parentSymbol = symbol; } writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning) { - if (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_7) { + walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else { - if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { - return; - } - if (symbol.flags & 2048 || symbol.flags & 4096) { - return; - } - appendParentTypeArgumentsAndSymbolName(symbol); + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } + else if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } } var isTypeParameter = symbol.flags & 262144; var typeFormatFlag = 128 & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning); - return; + walkSymbol(symbol, meaning, true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); } - return appendParentTypeArgumentsAndSymbolName(symbol); } function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - if (type.flags & 150995071) { + var nextFlags = flags & ~512; + if (type.flags & 16015) { writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 33554432) { + else if (type.flags & 268435456) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 4096) { - writeTypeReference(type, flags); - } - else if (type.flags & (1024 | 2048 | 128 | 512)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056, 0, flags); - } - else if (type.flags & 8192) { - writeTupleType(type); - } - else if (type.flags & 49152) { - writeUnionOrIntersectionType(type, flags); - } - else if (type.flags & 65536) { - writeAnonymousType(type, flags); + else if (type.flags & 131072) { + writeTypeReference(type, nextFlags); } else if (type.flags & 256) { - writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); + buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); + writePunctuation(writer, 21); + appendSymbolNameOnly(type.symbol, writer); + } + else if (type.flags & (32768 | 65536 | 16 | 16384)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); + } + else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); + } + else if (type.flags & 1572864) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (type.flags & 2097152) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96) { + writer.writeStringLiteral(literalTypeToString(type)); } else { writePunctuation(writer, 15); @@ -14587,7 +19100,7 @@ var ts; } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056, 0, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); } if (pos < end) { writePunctuation(writer, 25); @@ -14609,6 +19122,11 @@ var ts; writePunctuation(writer, 19); writePunctuation(writer, 20); } + else if (type.target.flags & 262144) { + writePunctuation(writer, 19); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); + writePunctuation(writer, 20); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -14616,12 +19134,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_7 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_7); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_7, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -14630,16 +19148,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } - function writeTupleType(type) { - writePunctuation(writer, 19); - writeTypeList(type.elementTypes, 24); - writePunctuation(writer, 20); - } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { writePunctuation(writer, 17); } - writeTypeList(type.types, type.flags & 16384 ? 47 : 46); + if (type.flags & 524288) { + writeTypeList(formatUnionTypes(type.types), 47); + } + else { + writeTypeList(type.types, 46); + } if (flags & 64) { writePunctuation(writer, 18); } @@ -14656,7 +19174,7 @@ var ts; else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); } else { writeKeyword(writer, 117); @@ -14676,7 +19194,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32; })); + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -14862,7 +19380,7 @@ var ts; } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingElement.kind === 193) { + if (ts.isOmittedExpression(bindingElement)) { return; } ts.Debug.assert(bindingElement.kind === 169); @@ -15010,19 +19528,19 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_8 = getDeclarationContainer(node); - if (!(ts.getCombinedNodeFlags(node) & 1) && - !(node.kind !== 229 && parent_8.kind !== 256 && ts.isInAmbientContext(parent_8))) { - return isGlobalSourceFile(parent_8); + var parent_9 = getDeclarationContainer(node); + if (!(ts.getCombinedModifierFlags(node) & 1) && + !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { + return isGlobalSourceFile(parent_9); } - return isDeclarationVisible(parent_8); + return isDeclarationVisible(parent_9); case 145: case 144: case 149: case 150: case 147: case 146: - if (node.flags & (8 | 16)) { + if (ts.getModifierFlags(node) & (8 | 16)) { return false; } case 148: @@ -15047,6 +19565,7 @@ var ts; return false; case 141: case 256: + case 228: return true; case 235: return false; @@ -15058,13 +19577,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793056 | 1536 | 8388608); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -15081,7 +19600,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -15122,7 +19641,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 1024)); + ts.Debug.assert(!!(target.flags & 32768)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -15164,7 +19683,7 @@ var ts; return type && (type.flags & 1) !== 0; } function isTypeNever(type) { - return type && (type.flags & 134217728) !== 0; + return type && (type.flags & 8192) !== 0; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); @@ -15195,25 +19714,25 @@ var ts; } if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { - return checkExpressionCached(declaration.initializer); + return checkDeclarationInitializer(declaration); } return parentType; } var type; if (pattern.kind === 167) { - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + var name_14 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_14)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_14); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); return unknownType; } } @@ -15226,7 +19745,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -15238,10 +19757,12 @@ var ts; type = createArrayType(elementType); } } - if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { type = getTypeWithFacts(type, 131072); } - return type; + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -15271,10 +19792,10 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? addTypeKind(type, 32) : type; + return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -15306,40 +19827,44 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - var type = declaration.symbol.name === "this" - ? getContextuallyTypedThisType(func) - : getContextuallyTypedParameterType(declaration); + var type = void 0; + if (declaration.symbol.name === "this") { + var thisParameter = getContextualThisParameter(func); + type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + } + else { + type = getContextuallyTypedParameterType(declaration); + } if (type) { return addOptionality(type, declaration.questionToken && includeOptionality); } } if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), declaration.questionToken && includeOptionality); + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, declaration.questionToken && includeOptionality); } if (declaration.kind === 254) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false); + return getTypeFromBindingPattern(declaration.name, false, true); } return undefined; } - function getTypeFromBindingElement(element, includePatternInType) { + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - var type = checkExpressionCached(element.initializer); - reportErrorsFromWidening(element, type); - return getWidenedType(type); + return checkDeclarationInitializer(element); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType); + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } - function getTypeFromObjectBindingPattern(pattern, includePatternInType) { - var members = {}; + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createMap(); var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -15350,7 +19875,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -15359,27 +19884,28 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 67108864; + result.flags |= 536870912; } return result; } - function getTypeFromArrayBindingPattern(pattern, includePatternInType) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; - if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); if (includePatternInType) { - var result = createNewTupleType(elementTypes); + result = cloneTypeReference(result); result.pattern = pattern; - return result; } - return createTupleType(elementTypes); + return result; } - function getTypeFromBindingPattern(pattern, includePatternInType) { + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { return pattern.kind === 167 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType) - : getTypeFromArrayBindingPattern(pattern, includePatternInType); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration, true); @@ -15418,19 +19944,27 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } + if (declaration.flags & 1048576 && declaration.kind === 280 && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = undefined; - if (declaration.kind === 187) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - else if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - type = checkExpressionCached(declaration.parent.right); + var type = void 0; + if (declaration.kind === 187 || + declaration.kind === 172 && declaration.parent.kind === 187) { + if (declaration.flags & 1048576) { + var typeTag = ts.getJSDocTypeTag(declaration.parent); + if (typeTag && typeTag.typeExpression) { + return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + } } + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + checkExpressionCached(decl.right) : + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -15473,7 +20007,7 @@ var ts; if (!links.type) { var getter = ts.getDeclarationOfKind(symbol, 149); var setter = ts.getDeclarationOfKind(symbol, 150); - if (getter && getter.flags & 134217728) { + if (getter && getter.flags & 1048576) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -15498,7 +20032,13 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } type = anyType; } @@ -15518,13 +20058,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(65536, symbol); + var type = createObjectType(2097152, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + includeFalsyTypes(type, 2048) : type; } } return links.type; @@ -15532,7 +20072,7 @@ var ts; function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.type = getDeclaredTypeOfEnumMember(symbol); } return links.type; } @@ -15575,7 +20115,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 4096 ? type.target : type; + return type.flags & 131072 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -15635,7 +20175,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 80896 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -15647,7 +20187,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -15662,7 +20202,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -15678,25 +20218,28 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { - var isClass = type.symbol.flags & 32; - var isInterface = type.symbol.flags & 64; if (!type.resolvedBaseTypes) { - if (!isClass && !isInterface) { + if (type.flags & 262144) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 | 64)) { + if (type.symbol.flags & 32) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64) { + resolveBaseTypesOfInterface(type); + } + } + else { ts.Debug.fail("type must be class or interface"); } - if (isClass) { - resolveBaseTypesOfClass(type); - } - if (isInterface) { - resolveBaseTypesOfInterface(type); - } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 80896)) { + if (!(baseConstructorType.flags & 2588672)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -15717,7 +20260,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (1024 | 2048))) { + if (!(getTargetType(baseType).flags & (32768 | 65536))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -15750,7 +20293,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (1024 | 2048)) { + if (getTargetType(baseType).flags & (32768 | 65536)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -15775,15 +20318,15 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 222) { - if (declaration.flags & 16384) { + if (declaration.flags & 64) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isSupportedExpressionWithTypeArguments(node)) { - var baseSymbol = resolveEntityName(node.expression, 793056, true); + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -15797,20 +20340,20 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 1024 : 2048; + var kind = symbol.flags & 32 ? 32768 : 65536; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1024 || !isIndependentInterface(symbol)) { - type.flags |= 4096; + if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { + type.flags |= 131072; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = {}; + type.instantiations = ts.createMap(); type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(512 | 33554432); + type.thisType = createType(16384 | 268435456); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -15823,8 +20366,9 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var type = void 0; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var declaration = ts.getDeclarationOfKind(symbol, 279); + var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -15835,12 +20379,12 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type); + type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); } if (popTypeResolution()) { - links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (links.typeParameters) { - links.instantiations = {}; + links.typeParameters = typeParameters; + if (typeParameters) { + links.instantiations = ts.createMap(); links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -15852,19 +20396,84 @@ var ts; } return links.declaredType; } + function isLiteralEnumMember(symbol, member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + return expr.kind === 8 || + expr.kind === 185 && expr.operator === 36 && + expr.operand.kind === 8 || + expr.kind === 69 && !!symbol.exports[expr.text]; + } + function enumHasLiteralMembers(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (!isLiteralEnumMember(symbol, member)) { + return false; + } + } + } + } + return true; + } + function createEnumLiteralType(symbol, baseType, text) { + var type = createType(256); + type.symbol = symbol; + type.baseType = baseType; + type.text = text; + return type; + } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(128); - type.symbol = symbol; - links.declaredType = type; + var enumType = links.declaredType = createType(16); + enumType.symbol = symbol; + if (enumHasLiteralMembers(symbol)) { + var memberTypeList = []; + var memberTypes = ts.createMap(); + for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224) { + computeEnumMemberValues(declaration); + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberSymbol = getSymbolOfNode(member); + var value = getEnumMemberValue(member); + if (!memberTypes[value]) { + var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); + memberTypeList.push(memberType); + } + } + } + } + enumType.memberTypes = memberTypes; + if (memberTypeList.length > 1) { + enumType.flags |= 524288; + enumType.types = memberTypeList; + unionTypes[getTypeListId(memberTypeList)] = enumType; + } + } + } + return links.declaredType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.declaredType = enumType.flags & 524288 ? + enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : + enumType; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(512); + var type = createType(16384); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141).constraint) { type.constraint = noConstraintType; @@ -15888,11 +20497,14 @@ var ts; if (symbol.flags & 524288) { return getDeclaredTypeOfTypeAlias(symbol); } + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); + } if (symbol.flags & 384) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); + if (symbol.flags & 8) { + return getDeclaredTypeOfEnumMember(symbol); } if (symbol.flags & 8388608) { return getDeclaredTypeOfAlias(symbol); @@ -15963,7 +20575,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -15971,7 +20583,7 @@ var ts; return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -15981,7 +20593,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!ts.hasProperty(symbols, s.name)) { + if (!symbols[s.name]) { symbols[s.name] = s; } } @@ -15998,19 +20610,27 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 4096) { + if (type.flags & 131072) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper = identityMapper; - var members = source.symbol.members; - var callSignatures = source.declaredCallSignatures; - var constructSignatures = source.declaredConstructSignatures; - var stringIndexInfo = source.declaredStringIndexInfo; - var numberIndexInfo = source.declaredNumberIndexInfo; - if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -16020,7 +20640,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (members === source.symbol.members) { + if (source.symbol && members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -16046,7 +20666,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -16056,11 +20676,11 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasStringLiterals = hasStringLiterals; + sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -16069,7 +20689,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -16084,22 +20704,6 @@ var ts; } return result; } - function createTupleTypeMemberSymbols(memberTypes) { - var members = {}; - for (var i = 0; i < memberTypes.length; i++) { - var symbol = createSymbol(4 | 67108864, "" + i); - symbol.type = memberTypes[i]; - members[i] = symbol; - } - return members; - } - function resolveTupleTypeMembers(type) { - var arrayElementType = getUnionType(type.elementTypes, true); - var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); - var members = createTupleTypeMemberSymbols(type.elementTypes); - addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); - } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -16145,7 +20749,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; @@ -16170,7 +20774,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -16230,7 +20834,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -16244,41 +20848,36 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 4096) { + if (type.flags & 131072) { resolveTypeReferenceMembers(type); } - else if (type.flags & (1024 | 2048)) { + else if (type.flags & (32768 | 65536)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 65536) { + else if (type.flags & 2097152) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 8192) { - resolveTupleTypeMembers(type); - } - else if (type.flags & 16384) { + else if (type.flags & 524288) { resolveUnionTypeMembers(type); } - else if (type.flags & 32768) { + else if (type.flags & 1048576) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } } } @@ -16289,7 +20888,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 16384) { + if (type.flags & 524288) { break; } } @@ -16297,12 +20896,12 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 512) { + while (constraintType && constraintType.flags & 16384) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -16310,19 +20909,19 @@ var ts; return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 512) { + if (type.flags & 16384) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 258) { + if (type.flags & 34) { type = globalStringType; } - else if (type.flags & 132) { + else if (type.flags & 340) { type = globalNumberType; } - else if (type.flags & 8) { + else if (type.flags & 136) { type = globalBooleanType; } - else if (type.flags & 16777216) { + else if (type.flags & 512) { type = getGlobalESSymbolType(); } return type; @@ -16330,14 +20929,14 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; + var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 | 16))) { + if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16))) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -16349,7 +20948,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384) { + else if (containingType.flags & 524288) { return undefined; } } @@ -16362,11 +20961,20 @@ var ts; } var propTypes = []; var declarations = []; + var commonType = undefined; + var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + hasCommonType = false; + } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 | @@ -16374,47 +20982,46 @@ var ts; 268435456 | commonFlags, name); result.containingType = containingType; + result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = {}); - if (ts.hasProperty(properties, name)) { - return properties[name]; - } - var property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; + var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); + var property = properties[name]; + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; + } } return property; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol = getPropertyOfObjectType(globalFunctionType, name); - if (symbol) { - return symbol; + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 49152) { + if (type.flags & 1572864) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 130048) { + if (type.flags & 4161536) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -16424,7 +21031,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 130048) { + if (type.flags & 4161536) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -16449,13 +21056,13 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, true); } } return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -16483,7 +21090,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 134217728) { + if (node.flags & 1048576) { if (node.type && node.type.kind === 268) { return true; } @@ -16532,7 +21139,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasStringLiterals = false; + var hasLiteralTypes = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -16552,7 +21159,7 @@ var ts; parameters.push(paramSymbol); } if (param.type && param.type.kind === 166) { - hasStringLiterals = true; + hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -16578,6 +21185,9 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } + if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { + thisParameter = getContextualThisParameter(declaration); + } var classType = declaration.kind === 148 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -16588,7 +21198,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } @@ -16602,7 +21212,7 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -16673,7 +21283,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); } else { type = getReturnTypeFromBody(signature.declaration); @@ -16697,7 +21307,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 4096 && type.target === globalArrayType) { + if (type.flags & 131072 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -16717,7 +21327,7 @@ var ts; function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(65536 | 262144); + var type = createObjectType(2097152); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -16752,7 +21362,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); } return undefined; } @@ -16761,7 +21371,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { + while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -16793,24 +21403,27 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); } function getTypeListId(types) { + var result = ""; if (types) { - switch (types.length) { - case 1: - return "" + types[0].id; - case 2: - return types[0].id + "," + types[1].id; - default: - var result = ""; - for (var i = 0; i < types.length; i++) { - if (i > 0) { - result += ","; - } - result += types[i].id; - } - return result; + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; } } - return ""; + return result; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; @@ -16820,20 +21433,29 @@ var ts; result |= type.flags; } } - return result & 14680064; + return result & 234881024; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 4096 | propagatedFlags; + var flags = 131072 | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } + function cloneTypeReference(source) { + var type = createObjectType(source.flags, source.symbol); + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return type.target.typeParameters ? type.target.typeParameters.length : 0; + } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; @@ -16842,7 +21464,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); return unknownType; } - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -16859,7 +21481,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); var id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } @@ -16883,8 +21505,9 @@ var ts; case 267: return node.name; case 194: - if (ts.isSupportedExpressionWithTypeArguments(node)) { - return node.expression; + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; } } return undefined; @@ -16893,7 +21516,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -16919,14 +21542,14 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); - links.resolvedSymbol = symbol; - links.resolvedType = type; } else { - var typeNameOrExpression = node.kind === 155 ? node.typeName : - ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : - undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 + ? node.typeName + : ts.isEntityNameExpression(node.expression) + ? node.expression + : undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : @@ -16961,7 +21584,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 80896)) { + if (!(type.flags & 2588672)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -16975,7 +21598,7 @@ var ts; return getGlobalSymbol(name, 107455, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793056, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793064, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -16985,8 +21608,8 @@ var ts; return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); + var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } function createTypedPropertyDescriptorType(propertyType) { @@ -17014,47 +21637,115 @@ var ts; } return links.resolvedType; } - function createTupleType(elementTypes) { - var id = getTypeListId(elementTypes); - return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); - } - function createNewTupleType(elementTypes) { - var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, 0); - var type = createObjectType(8192 | propagatedFlags); - type.elementTypes = elementTypes; + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384); + typeParameters.push(typeParameter); + var property = createSymbol(4 | 67108864, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(262144 | 131072); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 | 268435456); + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; return type; } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); } return links.resolvedType; } - function addTypeToSet(typeSet, type, typeSetKind) { - if (type.flags & typeSetKind) { - addTypesToSet(typeSet, type.types, typeSetKind); + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } } - else if (type.flags & (1 | 32 | 64)) { - if (type.flags & 1) - typeSet.containsAny = true; - if (type.flags & 32) + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 524288) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144) { + if (flags & 2048) typeSet.containsUndefined = true; - if (type.flags & 64) + if (flags & 4096) typeSet.containsNull = true; - if (!(type.flags & 2097152)) + if (!(flags & 33554432)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(flags & 8192)) { + if (flags & 2) + typeSet.containsString = true; + if (flags & 4) + typeSet.containsNumber = true; + if (flags & 96) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } } } - function addTypesToSet(typeSet, types, typeSetKind) { + function addTypesToUnion(typeSet, types) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToSet(typeSet, type, typeSetKind); + addTypeToUnion(typeSet, type); } } + function containsIdenticalType(types, type) { + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -17068,11 +21759,24 @@ var ts; while (i > 0) { i--; if (isSubtypeOfAny(types[i], types)) { - types.splice(i, 1); + ts.orderedRemoveItemAt(types, i); } } } - function getUnionType(types, noSubtypeReduction) { + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 && types.containsString || + t.flags & 64 && types.containsNumber || + t.flags & 96 && t.flags & 16777216 && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -17080,96 +21784,132 @@ var ts; return types[0]; } var typeSet = []; - addTypesToSet(typeSet, types, 16384); + addTypesToUnion(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } - if (!noSubtypeReduction) { + if (subtypeReduction) { removeSubtypes(typeSet); } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - else if (typeSet.length === 1) { - return typeSet[0]; + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; } - var id = getTypeListId(typeSet); + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); - type = unionTypes[id] = createObjectType(16384 | propagatedFlags); - type.types = typeSet; + var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); + type = unionTypes[id] = createObjectType(524288 | propagatedFlags); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node) { + function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), true); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), false, aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getIntersectionType(types) { + function addTypeToIntersection(typeSet, type) { + if (type.flags & 1048576) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + addTypeToIntersection(typeSet, type); + } + } + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToSet(typeSet, types, 32768); + addTypesToIntersection(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); - type = intersectionTypes[id] = createObjectType(32768 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); + type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node) { + function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createObjectType(65536, node.symbol); + var type = createObjectType(2097152, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + links.resolvedType = type; } return links.resolvedType; } - function getStringLiteralTypeForText(text) { - if (ts.hasProperty(stringLiteralTypes, text)) { - return stringLiteralTypes[text]; - } - var type = stringLiteralTypes[text] = createType(256); + function createLiteralType(flags, text) { + var type = createType(flags); type.text = text; return type; } - function getTypeFromStringLiteralTypeNode(node) { + function getFreshTypeOfLiteralType(type) { + if (type.flags & 96 && !(type.flags & 16777216)) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags | 16777216, type.text); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 && type.flags & 16777216 ? type.regularType : type; + } + function getLiteralTypeForText(flags, text) { + var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; + return map[text] || (map[text] = createLiteralType(flags, text)); + } + function getTypeFromLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); } return links.resolvedType; } @@ -17184,7 +21924,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); + var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -17193,8 +21933,8 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 222)) { - if (!(container.flags & 32) && - (container.kind !== 148 || ts.isNodeDescendentOf(node, container.body))) { + if (!(ts.getModifierFlags(container) & 32) && + (container.kind !== 148 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -17208,7 +21948,10 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNodeNoAlias(type) { + return getTypeFromTypeNode(type, undefined, undefined); + } + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117: case 258: @@ -17230,11 +21973,19 @@ var ts; return nullType; case 127: return neverType; + case 283: + return nullType; + case 284: + return undefinedType; + case 285: + return neverType; case 165: case 97: return getTypeFromThisTypeNode(node); case 166: - return getTypeFromStringLiteralTypeNode(node); + return getTypeFromLiteralTypeNode(node); + case 282: + return getTypeFromLiteralTypeNode(node.literal); case 155: case 267: return getTypeFromTypeReference(node); @@ -17251,9 +22002,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162: case 261: - return getTypeFromUnionTypeNode(node); + return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); case 163: - return getTypeFromIntersectionTypeNode(node); + return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); case 164: case 263: case 264: @@ -17261,13 +22012,14 @@ var ts; case 272: case 268: return getTypeFromTypeNode(node.type); + case 265: + return getTypeFromTypeNode(node.literal); case 156: case 157: case 159: case 281: case 269: - case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -17313,6 +22065,7 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; + mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -17321,7 +22074,7 @@ var ts; function getInferenceMapper(context) { if (!context.mapper) { var mapper = function (t) { - var typeParameters = context.typeParameters; + var typeParameters = context.signature.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (t === typeParameters[i]) { context.inferences[i].isFixed = true; @@ -17330,7 +22083,7 @@ var ts; } return t; }; - mapper.mappedTypes = context.typeParameters; + mapper.mappedTypes = context.signature.typeParameters; mapper.context = context; context.mapper = mapper; } @@ -17345,7 +22098,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(512); + var result = createType(16384); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -17380,7 +22133,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -17411,9 +22164,11 @@ var ts; else { mapper.instantiations = []; } - var result = createObjectType(65536 | 131072, type.symbol); + var result = createObjectType(2097152 | 4194304, type.symbol); result.target = type; result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -17465,26 +22220,23 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 512) { + if (type.flags & 16384) { return mapper(type); } - if (type.flags & 65536) { + if (type.flags & 2097152) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 131072 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 4096) { + if (type.flags & 131072) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 8192) { - return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); + if (type.flags & 524288 && !(type.flags & 8190)) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); } - if (type.flags & 16384) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), true); - } - if (type.flags & 32768) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); + if (type.flags & 1048576) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); } } return type; @@ -17527,10 +22279,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(65536, type.symbol); + var result = createObjectType(2097152, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -17541,22 +22293,25 @@ var ts; return type; } function isTypeIdenticalTo(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined); + return isTypeRelatedTo(source, target, identityRelation); } function compareTypesIdentical(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; + return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; } function compareTypesAssignable(source, target) { - return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; + return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; } function isTypeSubtypeOf(source, target) { - return checkTypeSubtypeOf(source, target, undefined); + return isTypeRelatedTo(source, target, subtypeRelation); } function isTypeAssignableTo(source, target) { - return checkTypeAssignableTo(source, target, undefined); + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeInstanceOf(source, target) { + return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); } function isTypeComparableTo(source, target) { - return checkTypeComparableTo(source, target, undefined); + return isTypeRelatedTo(source, target, comparableRelation); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -17669,8 +22424,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) - || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { return isSignatureAssignableTo(erasedSource, erasedTarget, true); } return false; @@ -17696,6 +22451,94 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + var id = source.id + "," + target.id; + if (enumRelation[id] !== undefined) { + return enumRelation[id]; + } + if (source.symbol.name !== target.symbol.name || + !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || + (source.flags & 524288) !== (target.flags & 524288)) { + return enumRelation[id] = false; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + } + return enumRelation[id] = false; + } + } + } + return enumRelation[id] = true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + if (target.flags & 8192) + return false; + if (target.flags & 1 || source.flags & 8192) + return true; + if (source.flags & 34 && target.flags & 2) + return true; + if (source.flags & 340 && target.flags & 4) + return true; + if (source.flags & 136 && target.flags & 8) + return true; + if (source.flags & 256 && target.flags & 16 && source.baseType === target) + return true; + if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + return true; + if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + return true; + if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1) + return true; + if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + return true; + if (source.flags & 256 && + target.flags & 256 && + source.text === target.text && + isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + return true; + } + if (source.flags & 256 && + target.flags & 16 && + isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { + return true; + } + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 && source.flags & 16777216) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 16777216) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 2588672 && target.flags & 2588672) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation[id]; + if (related !== undefined) { + return related === 1; + } + } + if (source.flags & 4177920 || target.flags & 4177920) { + return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + } + return false; + } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; @@ -17734,85 +22577,73 @@ var ts; } reportError(message, sourceType, targetType); } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType() === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; + if (source.flags & 96 && source.flags & 16777216) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 16777216) { + target = target.regularType; + } if (source === target) return -1; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (!(target.flags & 134217728)) { - if (target.flags & 1 || source.flags & 134217728) - return -1; - if (source.flags & 32) { - if (!strictNullChecks || target.flags & (32 | 16)) - return -1; - } - if (source.flags & 64) { - if (!strictNullChecks || target.flags & 64) - return -1; - } - if (source.flags & 128 && target === numberType) - return -1; - if (source.flags & 128 && target.flags & 128) { - if (result = enumRelatedTo(source, target, reportErrors)) { - return result; - } - } - if (source.flags & 256 && target === stringType) - return -1; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return -1; - if (source === numberType && target.flags & 128) - return -1; - } - if (source.flags & 8 && target.flags & 8) { - return -1; - } - } - if (source.flags & 1048576) { + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1; + if (source.flags & 8388608 && source.flags & 16777216) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 49152) { + if (target.flags & 1572864) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 16384) { + if (source.flags & 524288) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors); + result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } else { - result = eachTypeRelatedToType(source, target, reportErrors); + result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } if (result) { return result; } } - else if (target.flags & 32768) { + else if (target.flags & 1048576) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; } } else { - if (source.flags & 32768) { + if (source.flags & 1048576) { if (result = someTypeRelatedToType(source, target, false)) { return result; } } - if (target.flags & 16384) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726))) { + if (target.flags & 524288) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { return result; } } } - if (source.flags & 512) { + if (source.flags & 16384) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1) { constraint = emptyObjectType; @@ -17825,14 +22656,14 @@ var ts; } } else { - if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); + if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -17840,22 +22671,28 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 2588672 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } reportRelationError(headMessage, source, target); } return 0; } function isIdenticalTo(source, target) { var result; - if (source.flags & 80896 && target.flags & 80896) { - if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + if (source.flags & 2588672 && target.flags & 2588672) { + if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 16384 && target.flags & 16384 || - source.flags & 32768 && target.flags & 32768) { + if (source.flags & 524288 && target.flags & 524288 || + source.flags & 1048576 && target.flags & 1048576) { if (result = eachTypeRelatedToSomeType(source, target, false)) { if (result &= eachTypeRelatedToSomeType(target, source, false)) { return result; @@ -17865,7 +22702,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -17874,7 +22711,7 @@ var ts; return true; } } - else if (type.flags & 49152) { + else if (type.flags & 1572864) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -17892,7 +22729,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { + if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -17922,14 +22759,10 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - var len = targetTypes.length; - while (len >= 2 && targetTypes[len - 1].flags & 96) { - var related = isRelatedTo(source, targetTypes[len - 1], false); - if (related) { - return related; - } - len--; + if (target.flags & 524288 && containsType(targetTypes, source)) { + return -1; } + var len = targetTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -17953,14 +22786,10 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - var len = sourceTypes.length; - while (len >= 2 && sourceTypes[len - 1].flags & 96) { - var related = isRelatedTo(sourceTypes[len - 1], target, false); - if (related) { - return related; - } - len--; + if (source.flags & 524288 && containsType(sourceTypes, target)) { + return -1; } + var len = sourceTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -18032,7 +22861,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -18064,7 +22893,7 @@ var ts; if (result) { var maybeCache = maybeStack[depth]; var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyMap(maybeCache, destinationCache); + ts.copyProperties(maybeCache, destinationCache); } else { relation[id] = reportErrors ? 3 : 2; @@ -18077,9 +22906,9 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); - for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { - var targetProp = properties_1[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -18091,8 +22920,8 @@ var ts; } } else if (!(targetProp.flags & 134217728)) { - var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -18143,7 +22972,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 80896 && target.flags & 80896)) { + if (!(source.flags & 2588672 && target.flags & 2588672)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -18256,7 +23085,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 8190))) { return -1; } var sourceInfo = getIndexInfoOfType(source, kind) || @@ -18293,33 +23122,12 @@ var ts; } return 0; } - function enumRelatedTo(source, target, reportErrors) { - if (source.symbol.name !== target.symbol.name || - source.symbol.flags & 128 || - target.symbol.flags & 128) { - return 0; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); - } - return 0; - } - } - } - return -1; - } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = sourceSignature.declaration.flags & (8 | 16); - var targetAccessibility = targetSignature.declaration.flags & (8 | 16); + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; if (targetAccessibility === 8) { return true; } @@ -18336,11 +23144,11 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 65536) { + if (type.flags & 2097152) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && declaration.flags & 128) { + if (declaration && ts.getModifierFlags(declaration) & 128) { return true; } } @@ -18348,12 +23156,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (4096 | 131072) && depth >= 5) { + if (type.flags & (131072 | 4194304) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (4096 | 131072) && t.symbol === symbol) { + if (t.flags & (131072 | 4194304) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -18369,8 +23177,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 | 16); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 | 16); + var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -18395,8 +23203,10 @@ var ts; source.hasRestParameter === target.hasRestParameter) { return true; } - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || - source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -18446,31 +23256,40 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } - function getCombinedFlagsOfTypes(types) { - var flags = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - flags |= t.flags; + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } } - return flags; + return true; + } + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } function getCommonSupertype(types) { if (!strictNullChecks) { - return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); if (!primaryTypes.length) { - return getUnionType(types); + return getUnionType(types, true); } - var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96); + var supertype = getSupertypeOrUnion(primaryTypes); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -18500,44 +23319,80 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 4096 && type.target === globalArrayType; + return type.flags & 131072 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 96) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralUnionType(type) { - return type.flags & 256 ? true : - type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : - false; + function isUnitType(type) { + return (type.flags & (480 | 2048 | 4096)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 ? true : + type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 256 ? type.baseType : + type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 32 && type.flags & 16777216 ? stringType : + type.flags & 64 && type.flags & 16777216 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 256 ? type.baseType : + type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type; } function isTupleType(type) { - return !!(type.flags & 8192); + return !!(type.flags & 131072 && type.target.flags & 262144); } - function getCombinedTypeFlags(type) { - return type.flags & 16384 ? getCombinedFlagsOfTypes(type.types) : type.flags; + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; } - function addTypeKind(type, kind) { - if ((getCombinedTypeFlags(type) & kind) === kind) { + function getFalsyFlags(type) { + return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : + type.flags & 32 ? type.text === "" ? 32 : 0 : + type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 128 ? type === falseType ? 128 : 0 : + type.flags & 7406; + } + function includeFalsyTypes(type, flags) { + if ((getFalsyFlags(type) & flags) === flags) { return type; } var types = [type]; - if (kind & 2) - types.push(stringType); - if (kind & 4) - types.push(numberType); - if (kind & 8) - types.push(booleanType); - if (kind & 16) + if (flags & 34) + types.push(emptyStringType); + if (flags & 340) + types.push(zeroType); + if (flags & 136) + types.push(falseType); + if (flags & 1024) types.push(voidType); - if (kind & 32) + if (flags & 2048) types.push(undefinedType); - if (kind & 64) + if (flags & 4096) types.push(nullType); - return getUnionType(types); + return getUnionType(types, true); + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 7392 ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : + type; } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; @@ -18559,7 +23414,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = {}; + var members = ts.createMap(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -18570,7 +23425,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576)) { + if (!(type.flags & 8388608 && type.flags & 16777216)) { return type; } var regularType = type.regularType; @@ -18580,7 +23435,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; + regularNew.flags = resolved.flags & ~16777216; type.regularType = regularNew; return regularNew; } @@ -18594,31 +23449,28 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 96 ? type : getWidenedType(type); + return type.flags & 6144 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 96) { + if (type.flags & 100663296) { + if (type.flags & 6144) { return anyType; } - if (type.flags & 524288) { + if (type.flags & 8388608) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 16384) { - return getUnionType(ts.map(type.types, getWidenedConstituentType), true); + if (type.flags & 524288) { + return getUnionType(ts.map(type.types, getWidenedConstituentType)); } - if (isArrayType(type)) { - return createArrayType(getWidenedType(type.typeArguments[0])); - } - if (isTupleType(type)) { - return createTupleType(ts.map(type.elementTypes, getWidenedType)); + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 16384) { + if (type.flags & 524288) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -18626,22 +23478,19 @@ var ts; } } } - if (isArrayType(type)) { - return reportWideningErrorsInType(type.typeArguments[0]); - } - if (isTupleType(type)) { - for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 524288) { + if (type.flags & 8388608) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { + if (t.flags & 33554432) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -18686,7 +23535,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -18712,29 +23561,46 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = ts.map(typeParameters, createTypeInferencesObject); + function createInferenceContext(signature, inferUnionTypes) { + var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); return { - typeParameters: typeParameters, + signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length) }; } function createTypeInferencesObject() { return { primary: undefined, secondary: undefined, + topLevel: true, isFixed: false }; } - function inferTypes(context, source, target) { + function couldContainTypeParameters(type) { + return !!(type.flags & 16384 || + type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || + type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || + type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); + } + function couldUnionOrIntersectionContainTypeParameters(type) { + if (type.couldContainTypeParameters === undefined) { + type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + } + return type.couldContainTypeParameters; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 1572864 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypes(context, originalSource, originalTarget) { + var typeParameters = context.signature.typeParameters; var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; - inferFromTypes(source, target); + var visited = ts.createMap(); + inferFromTypes(originalSource, originalTarget); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { if (source === sourceStack[i] && target === targetStack[i]) { @@ -18744,26 +23610,41 @@ var ts; return false; } function inferFromTypes(source, target) { - if (source.flags & 16384 && target.flags & 16384 || - source.flags & 32768 && target.flags & 32768) { + if (!couldContainTypeParameters(target)) { + return; + } + if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || + source.flags & 1048576 && target.flags & 1048576) { + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } var matchingTypes = void 0; - for (var _i = 0, _a = target.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (typeIdenticalToSomeType(t, source.types)) { + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } + else if (t.flags & (64 | 32)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } } if (matchingTypes) { source = removeTypesFromUnionOrIntersection(source, matchingTypes); target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 512) { - if (source.flags & 8388608) { + if (target.flags & 16384) { + if (source.flags & 134217728) { return; } - var typeParameters = context.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { var inferences = context.inferences[i]; @@ -18774,12 +23655,15 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } + if (!isTypeParameterAtTopLevel(originalTarget, target)) { + inferences.topLevel = false; + } } return; } } } - else if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -18787,20 +23671,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { - var sourceTypes = source.elementTypes; - var targetTypes = target.elementTypes; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 49152) { + else if (target.flags & 1572864) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; - for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { - var t = targetTypes_2[_b]; - if (t.flags & 512 && ts.contains(context.typeParameters, t)) { + for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { + var t = targetTypes_2[_d]; + if (t.flags & 16384 && ts.contains(typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -18814,18 +23691,16 @@ var ts; inferiority--; } } - else if (source.flags & 49152) { + else if (source.flags & 1572864) { var sourceTypes = source.types; - for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { - var sourceType = sourceTypes_3[_c]; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || - target.flags & 8192 || - target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (source.flags & 2588672) { if (isInProcess(source, target)) { return; } @@ -18833,7 +23708,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -18854,8 +23729,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -18872,8 +23747,11 @@ var ts; inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } + function inferFromParameterTypes(source, target) { + return inferFromTypes(source, target); + } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromParameterTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -18902,8 +23780,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -18918,19 +23796,28 @@ var ts; reducedTypes.push(t); } } - return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); + return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190); + } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; var inferenceSucceeded; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var signature = context.signature; + var widenLiteralTypes = context.inferences[index].topLevel && + !hasPrimitiveConstraint(signature.typeParameters[index]) && + (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); + var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -18940,7 +23827,7 @@ var ts; } context.inferredTypes[index] = inferredType; if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -18996,10 +23883,6 @@ var ts; } return undefined; } - function isNullOrUndefinedLiteral(node) { - return node.kind === 93 || - node.kind === 69 && getResolvedSymbol(node) === undefinedSymbol; - } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69: @@ -19011,16 +23894,17 @@ var ts; return undefined; } function isMatchingReference(source, target) { - if (source.kind === target.kind) { - switch (source.kind) { - case 69: - return getResolvedSymbol(source) === getResolvedSymbol(target); - case 97: - return true; - case 172: - return source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } + switch (source.kind) { + case 69: + return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 218 || target.kind === 169) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 97: + return target.kind === 97; + case 172: + return target.kind === 172 && + source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); } return false; } @@ -19033,6 +23917,40 @@ var ts; } return false; } + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 172 && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 69) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 172) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.text); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 524288) { + var prop = getPropertyOfType(type, name); + if (!prop) { + var filteredType = getTypeWithFacts(type, 4194304); + if (filteredType !== type && filteredType.flags & 524288) { + prop = getPropertyOfType(filteredType, name); + } + } + if (prop && prop.flags & 268435456) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !prop.hasCommonType && + isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -19059,7 +23977,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 16384)) { + if (!(source.flags & 524288)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -19071,70 +23989,82 @@ var ts; return false; } function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType && declaredType.flags & 16384) { - var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedTypes.length) { - return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); + if (declaredType !== assignedType) { + if (assignedType.flags & 8192) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192)) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); + } function getTypeFacts(type) { var flags = type.flags; - if (flags & 258) { + if (flags & 2) { return strictNullChecks ? 4079361 : 4194049; } - if (flags & 132) { + if (flags & 32) { + return strictNullChecks ? + type.text === "" ? 3030785 : 1982209 : + type.text === "" ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } + if (flags & (64 | 256)) { + var isZero = type.text === "0"; + return strictNullChecks ? + isZero ? 3030658 : 1982082 : + isZero ? 3145346 : 4193922; + } if (flags & 8) { return strictNullChecks ? 4078980 : 4193668; } - if (flags & 80896) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? - strictNullChecks ? 1970144 : 4181984 : - strictNullChecks ? 1972176 : 4184016; + if (flags & 136) { + return strictNullChecks ? + type === falseType ? 3030404 : 1981828 : + type === falseType ? 3145092 : 4193668; } - if (flags & (16 | 32)) { + if (flags & 2588672) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 : 8376288 : + strictNullChecks ? 6166480 : 8378320; + } + if (flags & (1024 | 2048)) { return 2457472; } - if (flags & 64) { + if (flags & 4096) { return 2340752; } - if (flags & 16777216) { + if (flags & 512) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 512) { + if (flags & 16384) { var constraint = getConstraintOfTypeParameter(type); - return constraint ? getTypeFacts(constraint) : 4194303; + return getTypeFacts(constraint || emptyObjectType); } - if (flags & 32768) { - return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0); + if (flags & 1572864) { + return getTypeFactsOfTypes(type.types); } - return 4194303; + return 8388607; } function getTypeWithFacts(type, include) { - if (!(type.flags & 16384)) { - return getTypeFacts(type) & include ? type : neverType; - } - var firstType; - var types; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (getTypeFacts(t) & include) { - if (!firstType) { - firstType = t; - } - else { - if (!types) { - types = [firstType]; - } - types.push(t); - } - } - } - return firstType ? types ? getUnionType(types, true) : firstType : neverType; + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -19228,53 +24158,88 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getReferenceFromExpression(node) { + function getInitialOrAssignedType(node) { + return node.kind === 218 || node.kind === 169 ? + getInitialType(node) : + getAssignedType(node); + } + function getReferenceCandidate(node) { switch (node.kind) { case 178: - return getReferenceFromExpression(node.expression); + return getReferenceCandidate(node.expression); case 187: switch (node.operatorToken.kind) { case 56: - return getReferenceFromExpression(node.left); + return getReferenceCandidate(node.left); case 24: - return getReferenceFromExpression(node.right); + return getReferenceCandidate(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249) { - var expr = clause.expression; - return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; } - return undefined; + return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 524288) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + return true; + } + return containsType(target.types, source); } function filterType(type, f) { - return type.flags & 16384 ? - getUnionType(ts.filter(type.types, f)) : - f(type) ? type : neverType; + if (type.flags & 524288) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32); + var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; - var result = getTypeAtFlowNode(reference.flowNode); + var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288) === neverType) { + if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288).flags & 8192) { return declaredType; } return result; @@ -19312,7 +24277,7 @@ var ts; } else if (flow.flags & 2) { var container = flow.container; - if (container && includeOuterFunctions) { + if (container && container !== flowContainer && reference.kind !== 172) { flow = container.flowNode; continue; } @@ -19331,16 +24296,10 @@ var ts; } function getTypeAtFlowAssignment(flow) { var node = flow.node; - if ((node.kind === 218 || node.kind === 169) && - reference.kind === 69 && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { - return declaredType.flags & 16384 ? - getAssignmentReducedType(declaredType, getInitialType(node)) : - declaredType; - } if (isMatchingReference(reference, node)) { - return declaredType.flags & 16384 ? - getAssignmentReducedType(declaredType, getAssignedType(node)) : + var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; + return declaredType.flags & 524288 && !isIncrementOrDecrement ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -19349,37 +24308,55 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - if (type !== neverType) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (!(type.flags & 8192)) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { - type = narrowType(declaredType, flow.expression, assumeTrue); + if (type.flags & 8192 && isIncomplete(flowType)) { + type = silentNeverType; } } - return type; + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtSwitchClause(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) { return type; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } } - return getUnionType(antecedentTypes); + return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); if (!key) { key = getFlowCacheKey(reference); } @@ -19388,32 +24365,66 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return getUnionType(flowLoopTypes[i]); + return createFlowType(getUnionType(flowLoopTypes[i]), true); } } var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); if (cache[key]) { return cache[key]; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } if (type === declaredType) { break; } } - return cache[key] = getUnionType(antecedentTypes); + var result = getUnionType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, true); + } + return cache[key] = result; + } + function isMatchingReferenceDiscriminant(expr) { + return expr.kind === 172 && + declaredType.flags & 524288 && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(declaredType, expr.name.text); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152) : type; + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + } + if (isMatchingReferenceDiscriminant(expr)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -19423,26 +24434,29 @@ var ts; case 31: case 32: case 33: - var left = expr.left; - var operator = expr.operatorToken.kind; - var right = expr.right; - if (isNullOrUndefinedLiteral(right)) { - return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 182 && right_1.kind === 9) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (isNullOrUndefinedLiteral(left)) { - return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + if (right_1.kind === 182 && left_1.kind === 9) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (left.kind === 182 && right.kind === 9) { - return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } - if (right.kind === 182 && left.kind === 9) { - return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } - if (left.kind === 172) { - return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + if (isMatchingReferenceDiscriminant(left_1)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (right.kind === 172) { - return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); + if (isMatchingReferenceDiscriminant(right_1)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; } break; case 91: @@ -19452,23 +24466,41 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1) { + return type; + } if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { + var valueType = checkExpression(value); + if (valueType.flags & 6144) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 30 || operator === 31; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + value.kind === 93 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); + } + if (type.flags & 2589191) { return type; } - var doubleEquals = operator === 30 || operator === 31; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - literal.kind === 93 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 ? type : narrowedType; + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceFromExpression(typeOfExpr.expression); + var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (containsMatchingReference(reference, target)) { return declaredType; @@ -19478,76 +24510,40 @@ var ts; if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, literal.text); + if (assumeTrue && !(type.flags & 524288)) { + var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, literal.text) || 64 : - ts.getProperty(typeofNEFacts, literal.text) || 8192; + typeofEQFacts[literal.text] || 64 : + typeofNEFacts[literal.text] || 8192; return getTypeWithFacts(type, facts); } - function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { - if (!isMatchingReference(reference, propAccess.expression)) { - return type; - } - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } - var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); - if (!isStringLiteralUnionType(discriminantType)) { - return type; - } - if (operator === 31 || operator === 33) { - assumeTrue = !assumeTrue; - } - if (assumeTrue) { - return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); - } - if (discriminantType.flags & 256) { - return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); - } - return type; - } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - if (!isMatchingReference(reference, switchStatement.expression.expression)) { - return type; - } - var propName = switchStatement.expression.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); - var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; - var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; - var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); - return caseType ? getUnionType([caseType, defaultType]) : defaultType; + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left); + var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (containsMatchingReference(reference, left)) { return declaredType; } return type; } - if (isTypeAny(type)) { - return type; - } var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; @@ -19560,12 +24556,15 @@ var ts; targetType = prototypePropertyType; } } + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 2048) { + if (rightType.flags & 65536) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 65536) { + else if (rightType.flags & 2097152) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -19579,23 +24578,22 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return type.flags & 16384 ? - getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : - type; + return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); } - if (type.flags & 16384) { - var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); - if (assignableConstituents.length) { - return getUnionType(assignableConstituents); + if (type.flags & 524288) { + var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (!(assignableType.flags & 8192)) { + return assignableType; } } - var targetType = type.flags & 512 ? getApparentType(type) : type; - return isTypeAssignableTo(candidate, targetType) ? candidate : + var targetType = type.flags & 16384 ? getApparentType(type) : type; + return isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : - getIntersectionType([type, candidate]); + isTypeAssignableTo(candidate, targetType) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (type.flags & 1 || !hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -19603,6 +24601,9 @@ var ts; if (!predicate) { return type; } + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -19673,31 +24674,62 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 256 || node.kind === 145) { + if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 226 || + node.kind === 256 || + node.kind === 145) { return node; } } } - function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { - var declarationContainer = getControlFlowContainer(declaration); - var container = getControlFlowContainer(reference); - while (container !== declarationContainer && - (container.kind === 179 || container.kind === 180) && - (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { - container = getControlFlowContainer(container); + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304)) { + links.flags |= 4194304; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + while (true) { + node = node.parent; + if (!node) { + return false; + } + if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304) { + return true; + } + } + } + function markParameterAssignments(node) { + if (node.kind === 69) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); } - return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 180) { - if (languageVersion < 2) { + if (languageVersion < 2) { + if (container.kind === 180) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } + else if (ts.hasModifier(container, 256)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } } - if (node.flags & 33554432) { + if (node.flags & 262144) { getNodeLinks(container).flags |= 8192; } } @@ -19705,34 +24737,56 @@ var ts; markAliasSymbolAsReferenced(symbol); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (languageVersion === 2 - && localOrExportSymbol.flags & 32 - && localOrExportSymbol.valueDeclaration.kind === 221 - && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { - getNodeLinks(container).flags |= 524288; - getNodeLinks(node).flags |= 1048576; - break; + if (localOrExportSymbol.flags & 32) { + var declaration_1 = localOrExportSymbol.valueDeclaration; + if (languageVersion === 2 + && declaration_1.kind === 221 + && ts.nodeIsDecorated(declaration_1)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration_1 && container.name !== node) { + getNodeLinks(declaration_1).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration_1.kind === 192) { + var container = ts.getThisContainer(node, false); + while (container !== undefined) { + if (container.parent === declaration_1) { + if (container.kind === 145 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration_1).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + } + break; + } + container = ts.getThisContainer(container, false); } - container = ts.getContainingClass(container); } } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node)) { + var declaration = localOrExportSymbol.valueDeclaration; + if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { return type; } - var declaration = localOrExportSymbol.valueDeclaration; - var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || !declaration || - ts.getRootDeclaration(declaration).kind === 142 || ts.isInAmbientContext(declaration) || - !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); - if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32) && getCombinedTypeFlags(flowType) & 32) { + var isParameter = ts.getRootDeclaration(declaration).kind === 142; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + while (flowContainer !== declarationContainer && + (flowContainer.kind === 179 || flowContainer.kind === 180) && + (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || + isOuterVariable || ts.isInAmbientContext(declaration); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); + if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -19870,7 +24924,7 @@ var ts; break; case 145: case 144: - if (container.flags & 32) { + if (ts.getModifierFlags(container) & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -19895,10 +24949,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -19906,8 +24956,8 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - var type = container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, true, true); + var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type, true, undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -19968,15 +25018,15 @@ var ts; } return unknownType; } - if ((container.flags & 32) || isCallExpression) { + if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } else { nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 147 && container.flags & 256) { - if (ts.isSuperPropertyOrElementAccess(node.parent) && ts.isAssignmentTarget(node.parent)) { + if (container.kind === 147 && ts.getModifierFlags(container) & 256) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } else { @@ -20020,7 +25070,7 @@ var ts; } else { if (ts.isClassLike(container.parent) || container.parent.kind === 171) { - if (container.flags & 32) { + if (ts.getModifierFlags(container) & 32) { return container.kind === 147 || container.kind === 146 || container.kind === 149 || @@ -20040,11 +25090,11 @@ var ts; return false; } } - function getContextuallyTypedThisType(func) { + function getContextualThisParameter(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return getThisTypeOfSignature(contextualSignature); + return contextualSignature.thisParameter; } } return undefined; @@ -20059,14 +25109,14 @@ var ts; if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getTypeOfExpression(iife.arguments[i])); + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } return createArrayType(getUnionType(restTypes)); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; links.resolvedSignature = anySignature; - var type = checkExpression(iife.arguments[indexOfParameter]); + var type = getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])); links.resolvedSignature = cached; return type; } @@ -20101,15 +25151,15 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true); + return getTypeFromBindingPattern(declaration.name, true, false); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_12 = declaration.propertyName || declaration.name; + var name_15 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_12)) { - var text = getTextOfPropertyName(name_12); + !ts.isBindingPattern(name_15)) { + var text = getTextOfPropertyName(name_15); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -20184,6 +25234,9 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 && operator <= 68) { + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + return undefined; + } if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); } @@ -20203,14 +25256,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 16384)) { + if (!(type.flags & 524288)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -20228,7 +25281,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 130048 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -20236,7 +25289,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -20324,6 +25377,7 @@ var ts; case 187: return getContextualTypeForBinaryOperand(node); case 253: + case 254: return getContextualTypeForObjectLiteralElement(parent); case 170: return getContextualTypeForElementExpression(node); @@ -20370,13 +25424,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 16384)) { + if (!(type.flags & 524288)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -20425,14 +25479,14 @@ var ts; } } else { - var type = checkExpression(e, contextualMapper); + var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 191; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -20444,7 +25498,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.elementTypes[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { if (patternElement.kind !== 193) { @@ -20459,17 +25513,22 @@ var ts; } } } - return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, true) : + strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } function isNumericLiteralName(name) { return (+name).toString() === name; } @@ -20477,7 +25536,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 16777216)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -20493,13 +25552,13 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = {}; + var propertiesTable = ts.createMap(); var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -20523,7 +25582,7 @@ var ts; } else { ts.Debug.assert(memberDecl.kind === 254); - type = checkExpression(memberDecl.name, contextualMapper); + type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); @@ -20537,7 +25596,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -20575,7 +25634,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!ts.hasProperty(propertiesTable, prop.name)) { + if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -20587,8 +25646,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -20642,9 +25701,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var indexerType = getIndexTypeOfType(elementAttributesType, 0); - if (indexerType) { - correspondingPropType = indexerType; + var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); + if (attributeType) { + correspondingPropType = attributeType; } else { if (!correspondingPropType) { @@ -20717,7 +25776,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 16384)); + ts.Debug.assert(!(valueType.flags & 524288)); if (isTypeAny(valueType)) { return anyType; } @@ -20729,11 +25788,11 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature)); + return getUnionType(signatures.map(getReturnTypeOfSignature), true); } function getJsxElementPropertiesName() { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064); var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -20756,16 +25815,16 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 16384) { + if (elemType.flags & 524288) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - })); + }), true); } if (elemType.flags & 2) { return anyType; } - else if (elemType.flags & 256) { + else if (elemType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elemType.text; @@ -20818,7 +25877,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 16384) { + else if (attributesType.flags & 524288) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -20901,7 +25960,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = {}; + var nameTable = ts.createMap(); var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { if (node.attributes[i].kind === 246) { @@ -20919,7 +25978,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912) && - nameTable[targetProperties[i].name] === undefined) { + !nameTable[targetProperties[i].name]) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -20936,11 +25995,14 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 145; } - function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + function getDeclarationModifierFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function checkClassPropertyAccess(node, left, type, prop) { - var flags = getDeclarationFlagsFromSymbol(prop); + var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 172 || node.kind === 218 ? node.name : @@ -20955,7 +26017,7 @@ var ts; return false; } } - if (!(flags & (8 | 16))) { + if (!(flags & 24)) { return true; } if (flags & 8) { @@ -20980,10 +26042,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 33554432) { + if (type.flags & 268435456) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (1024 | 2048) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -20992,9 +26054,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getCombinedTypeFlags(type) & 96; + var kind = getFalsyFlags(type) & 6144; if (kind) { - error(node, kind & 32 ? kind & 64 ? + error(node, kind & 2048 ? kind & 4096 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -21011,23 +26073,23 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); - if (isTypeAny(type)) { + if (isTypeAny(type) || type === silentNeverType) { return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 512 && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); + reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); } return unknownType; } if (noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && (prop.valueDeclaration.flags & 8)) { + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { if (prop.flags & 16777216) { getSymbolLinks(prop).target.isReferenced = true; } @@ -21042,10 +26104,24 @@ var ts; var propType = getTypeOfSymbol(prop); if (node.kind !== 172 || ts.isAssignmentTarget(node) || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 16384)) { + !(prop.flags & 8192 && propType.flags & 524288)) { return propType; } - return getFlowTypeOfReference(node, propType, true, false); + return getFlowTypeOfReference(node, propType, true, undefined); + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 524288 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -21113,8 +26189,8 @@ var ts; } var objectType = getApparentType(checkNonNullExpression(node.expression)); var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; - if (objectType === unknownType) { - return unknownType; + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; } var isConstEnum = isConstEnumObjectType(objectType); if (isConstEnum && @@ -21123,21 +26199,22 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_13 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_13 !== undefined) { - var prop = getPropertyOfType(objectType, name_13); + var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_16 !== undefined) { + var prop = getPropertyOfType(objectType, name_16); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_13, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_16, symbolToString(objectType.symbol)); return unknownType; } } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + var allowedNullableFlags = strictNullChecks ? 0 : 6144; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -21182,7 +26259,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 16777216) === 0) { + if ((expressionType.flags & 512) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -21231,22 +26308,22 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_9 = signature.declaration && signature.declaration.parent; + var parent_10 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_9 === lastParent) { + if (lastParent && parent_10 === lastParent) { index++; } else { - lastParent = parent_9; + lastParent = parent_10; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_9; + lastParent = parent_10; } lastSymbol = symbol; - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -21320,7 +26397,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -21330,7 +26407,7 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature.typeParameters, true); + var context = createInferenceContext(signature, true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { inferTypes(context, instantiateType(source, contextualMapper), target); }); @@ -21420,9 +26497,7 @@ var ts; var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { - argType = arg.kind === 9 && !reportErrors - ? getStringLiteralTypeForText(arg.text) - : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { @@ -21526,10 +26601,10 @@ var ts; case 69: case 8: case 9: - return getStringLiteralTypeForText(element.name.text); + return getLiteralTypeForText(32, element.name.text); case 140: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 16777216)) { + if (isTypeOfKind(nameType, 512)) { return nameType; } else { @@ -21655,7 +26730,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -21676,7 +26751,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); } return candidate; } @@ -21701,14 +26776,14 @@ var ts; var candidate = void 0; var typeArgumentsAreValid = void 0; var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate.typeParameters, false) + ? createInferenceContext(originalCandidate, false) : undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -21763,15 +26838,16 @@ var ts; return resolveUntypedCall(node); } var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } var apparentType = getApparentType(funcType); if (apparentType === unknownType) { return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isTypeAny(funcType) || - (isTypeAny(apparentType) && funcType.flags & 512) || - (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -21782,12 +26858,27 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); } return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + if (funcType.flags & 524288) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -21796,12 +26887,15 @@ var ts; } } var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } expressionType = getApparentType(expressionType); if (expressionType === unknownType) { return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 128) { + if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -21837,17 +26931,29 @@ var ts; return true; } var declaration = signature.declaration; - var flags = declaration.flags; - if (!(flags & (8 | 16))) { + var modifiers = ts.getModifierFlags(declaration); + if (!(modifiers & 24)) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - if (flags & 8) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } + if (modifiers & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (flags & 16) { + if (modifiers & 16) { error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -21861,11 +26967,12 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -21892,13 +26999,14 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); return resolveErrorCall(node); @@ -21921,21 +27029,21 @@ var ts; function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); var cached = links.resolvedSignature; - if (cached && cached !== anySignature && !candidatesOutArray) { + if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = anySignature; + links.resolvedSignature = resolvingSignature; var result = resolveSignature(node, candidatesOutArray); links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); } return links.inferredClassType; } @@ -21973,7 +27081,7 @@ var ts; return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { @@ -21992,7 +27100,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32); + return includeFalsyTypes(type, 2048); } } return type; @@ -22004,6 +27112,12 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (context.thisParameter) { + if (!signature.thisParameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); + } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -22019,7 +27133,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193) { + if (!ts.isOmittedExpression(element)) { if (element.name.kind === 69) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -22101,17 +27215,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); - if (!type) { - if (funcIsGenerator) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); - return createIterableIteratorType(unknownType); - } - else { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); - } - } + type = getUnionType(types, true); if (funcIsGenerator) { type = createIterableIteratorType(type); } @@ -22119,6 +27223,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } + if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } var widenedType = getWidenedType(type); return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } @@ -22139,27 +27246,21 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - var expr = node.expression; - if (!node.possiblyExhaustive || expr.kind !== 172) { + if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(expr.expression); - if (!(type.flags & 16384)) { - return false; - } - var propName = expr.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { + var type = checkExpression(node.expression); + if (!isLiteralType(type)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(propType, switchTypes); + return eachTypeContainedIn(type, switchTypes); } function functionHasImplicitReturn(func) { - if (!(func.flags & 32768)) { + if (!(func.flags & 128)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); @@ -22180,7 +27281,7 @@ var ts; if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type === neverType) { + if (type.flags & 8192) { hasReturnOfTypeNever = true; } else if (!ts.contains(aggregatedTypes, type)) { @@ -22206,14 +27307,14 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { return; } if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } - var hasExplicitReturn = func.flags & 65536; - if (returnType === neverType) { + var hasExplicitReturn = func.flags & 256; + if (returnType && returnType.flags & 8192) { error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -22308,7 +27409,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { error(operand, diagnostic); return false; } @@ -22316,8 +27417,8 @@ var ts; } function isReadonlySymbol(symbol) { return symbol.isReadonly || - symbol.flags & 4 && (getDeclarationFlagsFromSymbol(symbol) & 64) !== 0 || - symbol.flags & 3 && (getDeclarationFlagsFromSymbol(symbol) & 2048) !== 0 || + symbol.flags & 4 && (getDeclarationModifierFlagsFromSymbol(symbol) & 64) !== 0 || + symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 || symbol.flags & 98304 && !(symbol.flags & 65536) || (symbol.flags & 8) !== 0; } @@ -22390,7 +27491,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 33554432)) { + if (!(node.flags & 262144)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -22402,16 +27503,25 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 36 && node.operand.kind === 8) { + return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + } switch (node.operator) { case 35: case 36: case 50: - if (maybeTypeOfKind(operandType, 16777216)) { + if (maybeTypeOfKind(operandType, 512)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49: - return booleanType; + var facts = getTypeFacts(operandType) & (1048576 | 2097152); + return facts === 1048576 ? falseType : + facts === 2097152 ? trueType : + booleanType; case 41: case 42: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -22424,6 +27534,9 @@ var ts; } function checkPostfixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); @@ -22434,10 +27547,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 49152) { + if (type.flags & 1572864) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -22449,20 +27562,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 16384) { + if (type.flags & 524288) { var types = type.types; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 32768) { + if (type.flags & 1048576) { var types = type.types; - for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { - var t = types_12[_a]; + for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { + var t = types_16[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -22471,13 +27584,16 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (80896 | 65536) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (isTypeOfKind(leftType, 16777726)) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (isTypeOfKind(leftType, 8190)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -22486,32 +27602,35 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var p = properties_3[_i]; + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var p = properties_4[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); } return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_14 = property.name; - if (name_14.kind === 140) { - checkComputedPropertyName(name_14); + var name_17 = property.name; + if (name_17.kind === 140) { + checkComputedPropertyName(name_17); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_17)) { return undefined; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_17); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -22526,7 +27645,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_14)); + error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); } } else { @@ -22556,8 +27675,9 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { + checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -22587,7 +27707,7 @@ var ts; var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -22616,8 +27736,65 @@ var ts; } return sourceType; } + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 69: + case 9: + case 10: + case 176: + case 189: + case 11: + case 8: + case 99: + case 84: + case 93: + case 135: + case 179: + case 192: + case 180: + case 170: + case 171: + case 182: + case 196: + case 242: + case 241: + return true; + case 188: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 187: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 185: + case 186: + switch (node.operator) { + case 49: + case 35: + case 36: + case 50: + return true; + } + return false; + case 183: + case 177: + case 195: + default: + return false; + } + } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 96) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], true); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -22652,15 +27829,18 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 96) + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (leftType.flags & 6144) leftType = rightType; - if (rightType.flags & 96) + if (rightType.flags & 6144) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; - if ((leftType.flags & 8) && - (rightType.flags & 8) && + if ((leftType.flags & 136) && + (rightType.flags & 136) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -22674,18 +27854,21 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 96) + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (leftType.flags & 6144) leftType = rightType; - if (rightType.flags & 96) + if (rightType.flags & 6144) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { + if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { resultType = numberType; } else { - if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { + if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -22717,6 +27900,12 @@ var ts; case 31: case 32: case 33: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -22726,18 +27915,25 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; + return getTypeFacts(leftType) & 1048576 ? + includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + leftType; case 52: - return getUnionType([getNonNullableType(leftType), rightType]); + return getTypeFacts(leftType) & 2097152 ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; case 56: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); case 24: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : - maybeTypeOfKind(rightType, 16777216) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : + maybeTypeOfKind(rightType, 512) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -22789,7 +27985,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 8388608) || isYieldExpressionInClass(node)) { + if (!(node.flags & 65536) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -22822,14 +28018,22 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getUnionType([type1, type2]); + return getBestChoiceType(type1, type2); } - function checkStringLiteralExpression(node) { - var contextualType = getContextualType(node); - if (contextualType && isStringLiteralUnionType(contextualType)) { - return getStringLiteralTypeForText(node.text); + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + case 8: + return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + case 99: + return trueType; + case 84: + return falseType; } - return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -22854,11 +28058,38 @@ var ts; } return links.resolvedType; } + function isTypeAssertion(node) { + node = skipParenthesizedNodes(node); + return node.kind === 177 || node.kind === 195; + } + function checkDeclarationInitializer(declaration) { + var type = checkExpressionCached(declaration.initializer); + return ts.getCombinedNodeFlags(declaration) & 2 || + ts.getCombinedModifierFlags(declaration) & 64 || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 16384) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (apparentType.flags & (2 | 4 | 8 | 16)) { + return true; + } + contextualType = apparentType; + } + return maybeTypeOfKind(contextualType, 480); + } + return false; + } + function checkExpressionForMutableLocation(node, contextualMapper) { + var type = checkExpression(node, contextualMapper); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } function checkPropertyAssignment(node, contextualMapper) { if (node.name.kind === 140) { checkComputedPropertyName(node.name); } - return checkExpression(node.initializer, contextualMapper); + return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); @@ -22902,10 +28133,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -22916,15 +28143,13 @@ var ts; return checkSuperExpression(node); case 93: return nullWideningType; + case 9: + case 8: case 99: case 84: - return booleanType; - case 8: - return checkNumericLiteral(node); + return checkLiteralExpression(node); case 189: return checkTemplateExpression(node); - case 9: - return checkStringLiteralExpression(node); case 11: return stringType; case 10: @@ -23001,7 +28226,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 92) { + if (ts.getModifierFlags(node) & 92) { func = ts.getContainingFunction(node); if (!(func.kind === 148 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -23069,9 +28294,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_15 = _a[_i].name; - if (ts.isBindingPattern(name_15) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, parameterName, typePredicate.parameterName)) { + var name_18 = _a[_i].name; + if (ts.isBindingPattern(name_18) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -23091,23 +28316,27 @@ var ts; case 156: case 147: case 146: - var parent_10 = node.parent; - if (node === parent_10.type) { - return parent_10; + var parent_11 = node.parent; + if (node === parent_11.type) { + return parent_11; } } } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (name_16.kind === 69 && - name_16.text === predicateVariableName) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name_19 = element.name; + if (name_19.kind === 69 && + name_19.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_16.kind === 168 || - name_16.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, predicateVariableNode, predicateVariableName)) { + else if (name_19.kind === 168 || + name_19.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { return true; } } @@ -23155,22 +28384,21 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (!node.body) { + if (noUnusedIdentifiers && !node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var getter = 1, setter = 2, property = getter | setter; - var instanceNames = {}; - var staticNames = {}; + var instanceNames = ts.createMap(); + var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, property); + addName(instanceNames, param.name, param.name.text, 3); } } } @@ -23181,21 +28409,21 @@ var ts; if (memberName) { switch (member.kind) { case 149: - addName(names, member.name, memberName, getter); + addName(names, member.name, memberName, 1); break; case 150: - addName(names, member.name, memberName, setter); + addName(names, member.name, memberName, 2); break; case 145: - addName(names, member.name, memberName, property); + addName(names, member.name, memberName, 3); break; } } } } function addName(names, location, name, meaning) { - if (ts.hasProperty(names, name)) { - var prev = names[name]; + var prev = names[name]; + if (prev) { if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -23209,7 +28437,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = {}; + var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144) { @@ -23223,7 +28451,7 @@ var ts; default: continue; } - if (ts.hasProperty(names, memberName)) { + if (names[memberName]) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -23277,7 +28505,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); - if (node.flags & 128 && node.body) { + if (ts.getModifierFlags(node) & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -23322,7 +28550,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 145 && - !(n.flags & 32) && + !(ts.getModifierFlags(n) & 32) && !!n.initializer; } var containingClassDecl = node.parent; @@ -23334,7 +28562,7 @@ var ts; error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & 92; }); + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -23364,13 +28592,8 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); if (node.kind === 149) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { - if (node.flags & 65536) { - if (compilerOptions.noImplicitReturns) { - error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -23382,17 +28605,20 @@ var ts; var otherKind = node.kind === 149 ? 150 : 149; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 28) !== (otherAccessor.flags & 28))) { + if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (((node.flags & 128) !== (otherAccessor.flags & 128))) { + if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - getTypeOfAccessors(getSymbolOfNode(node)); + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 149) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -23424,7 +28650,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -23445,6 +28671,9 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } + if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } } } function checkTypeQuery(node) { @@ -23473,10 +28702,10 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 8) && ts.isInAmbientContext(node); + return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedNodeFlags(n); + var flags = ts.getCombinedModifierFlags(n); if (n.parent.kind !== 222 && n.parent.kind !== 221 && n.parent.kind !== 192 && @@ -23557,9 +28786,9 @@ var ts; var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { var reportError = (node.kind === 147 || node.kind === 146) && - (node.flags & 32) !== (subsequentNode.flags & 32); + (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); if (reportError) { - var diagnostic = node.flags & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -23575,7 +28804,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (node.flags & 128) { + if (ts.getModifierFlags(node) & 128) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -23635,7 +28864,7 @@ var ts; }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -23714,10 +28943,10 @@ var ts; case 224: return 2097152 | 1048576; case 229: - var result_1 = 0; + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); - return result_1; + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; default: return 1048576; } @@ -23740,7 +28969,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 4096) { + if (promise.flags & 131072) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -23766,7 +28995,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -23777,13 +29006,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 16384) { + if (type.flags & 524288) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types); + return getUnionType(types, true); } else { var promisedType = getPromisedType(type); @@ -23805,7 +29034,7 @@ var ts; } } } - function checkCorrectPromiseType(returnType, location) { + function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { if (returnType === unknownType) { return unknownType; } @@ -23814,13 +29043,13 @@ var ts; || globalPromiseType === getTargetType(returnType)) { return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } - error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(location, diagnostic, typeName); return unknownType; } function checkAsyncFunctionReturnType(node) { if (languageVersion >= 2) { var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type); + return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { @@ -23835,12 +29064,11 @@ var ts; var typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - return unknownType; + return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); } checkReturnTypeAnnotationAsExpression(node); var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } var promiseName = ts.getEntityNameFromTypeNode(node.type); @@ -23888,7 +29116,7 @@ var ts; function checkTypeNodeAsExpression(node) { if (node && node.kind === 155) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793056 : 1536; + var meaning = root.parent.kind === 155 ? 793064 : 1920; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -24044,21 +29272,20 @@ var ts; function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { var _loop_1 = function(key) { - if (ts.hasProperty(node.locals, key)) { - var local_1 = node.locals[key]; - if (!local_1.isReferenced) { - if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142) { - var parameter = local_1.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); - } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); + var local = node.locals[key]; + if (!local.isReferenced) { + if (local.valueDeclaration && local.valueDeclaration.kind === 142) { + var parameter = local.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + } } }; for (var key in node.locals) { @@ -24066,6 +29293,9 @@ var ts; } } } + function parameterIsThisKeyword(parameter) { + return parameter.name && parameter.name.originalKeywordKind === 97; + } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -24075,15 +29305,15 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 147 || member.kind === 145) { - if (!member.symbol.isReferenced && member.flags & 8) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } else if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && parameter.flags & 8) { - error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -24094,9 +29324,14 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!typeParameter.symbol.isReferenced) { + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -24106,14 +29341,12 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - if (ts.hasProperty(node.locals, key)) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); - } + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } } @@ -24219,12 +29452,12 @@ var ts; return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152) { + if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 3072) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } if (node.kind === 218 && !node.initializer) { @@ -24236,7 +29469,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219); var container = varDeclList.parent.kind === 200 && varDeclList.parent.parent ? varDeclList.parent.parent @@ -24247,8 +29480,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_17 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_17, name_17); + var name_20 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); } } } @@ -24288,7 +29521,7 @@ var ts; return; } if (current.parent.kind === 145 && - !(current.parent.flags & 32) && + !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)) { return; } @@ -24316,12 +29549,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_11 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_11); - var name_18 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_18)); - if (parent_11.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); + var parent_12 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_12); + var name_21 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); + if (parent_12.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -24384,7 +29617,7 @@ var ts; 128 | 64 | 32; - return (left.flags & interestingFlags) === (right.flags & interestingFlags); + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -24495,7 +29728,7 @@ var ts; if (varExpr.kind === 170 || varExpr.kind === 171) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -24503,7 +29736,7 @@ var ts; } } var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -24556,7 +29789,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 4096) && type.target === getGlobalIterableType()) { + if ((type.flags & 131072) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -24571,7 +29804,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), true), errorNode); } } return typeAsIterable.iterableElementType; @@ -24582,7 +29815,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 4096) && type.target === getGlobalIteratorType()) { + if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -24597,7 +29830,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), true); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -24617,7 +29850,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 4096) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -24626,10 +29859,10 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 16384) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); + if (arrayOrStringType.flags & 524288) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); } - else if (arrayOrStringType.flags & 258) { + else if (arrayOrStringType.flags & 34) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -24639,7 +29872,7 @@ var ts; error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); reportedError = true; } - if (arrayType === neverType) { + if (arrayType.flags & 8192) { return stringType; } } @@ -24654,10 +29887,10 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 258) { + if (arrayElementType.flags & 34) { return stringType; } - return getUnionType([arrayElementType, stringType]); + return getUnionType([arrayElementType, stringType], true); } return arrayElementType; } @@ -24669,7 +29902,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -24682,7 +29915,7 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType === neverType) { + if (strictNullChecks || node.expression || returnType.flags & 8192) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (func.asteriskToken) { return; @@ -24717,7 +29950,7 @@ var ts; } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 33554432) { + if (node.flags & 262144) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -24800,7 +30033,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals && ts.hasProperty(locals, identifierName)) { + if (locals) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -24825,11 +30058,11 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(member.flags & 32) && ts.hasDynamicName(member)) { + if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -24840,7 +30073,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 2048)) { + if (!errorNode && (type.flags & 65536)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -24862,7 +30095,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 2048) { + else if (containingType.flags & 65536) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -24927,7 +30160,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 512)) { + if (!node.name && !(ts.getModifierFlags(node) & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -24970,6 +30203,11 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { + error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); + } + } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { @@ -24983,15 +30221,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { + if (!ts.isEntityNameExpression(typeRefNode.expression)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 4096) ? t.target : t; - if (declaredType.flags & (1024 | 2048)) { + var declaredType = (t.flags & 131072) ? t.target : t; + if (declaredType.flags & (32768 | 65536)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -25010,7 +30248,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && declaration.flags & 8) { + if (declaration && ts.getModifierFlags(declaration) & 8) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); @@ -25033,12 +30271,12 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { if (derivedClassDecl.kind === 192) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -25048,7 +30286,7 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); if ((baseDeclarationFlags & 8) || (derivedDeclarationFlags & 8)) { continue; } @@ -25115,19 +30353,19 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = {}; + var seen = ts.createMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; - if (!ts.hasProperty(seen, prop.name)) { + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var prop = properties_5[_a]; + var existing = seen[prop.name]; + if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; } else { - var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -25165,7 +30403,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -25173,7 +30411,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - checkUnusedTypeParameters(node); + registerForUnusedIdentifiersCheck(node); } } function checkTypeAliasDeclaration(node) { @@ -25196,7 +30434,7 @@ var ts; } else { var text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text)) { + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -25488,9 +30726,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -25516,9 +30751,9 @@ var ts; break; case 169: case 218: - var name_19 = node.name; - if (ts.isBindingPattern(name_19)) { - for (var _b = 0, _c = name_19.elements; _b < _c.length; _b++) { + var name_22 = node.name; + if (ts.isBindingPattern(name_22)) { + for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -25544,19 +30779,20 @@ var ts; } } function getFirstIdentifier(node) { - while (true) { - if (node.kind === 139) { - node = node.left; - } - else if (node.kind === 172) { - node = node.expression; - } - else { - break; - } + switch (node.kind) { + case 69: + return node; + case 139: + do { + node = node.left; + } while (node.kind !== 69); + return node; + case 172: + do { + node = node.expression; + } while (node.kind !== 69); + return node; } - ts.Debug.assert(node.kind === 69); - return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -25584,8 +30820,8 @@ var ts; var target = resolveAlias(symbol); if (target !== unknownSymbol) { var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793056 ? 793056 : 0) | - (symbol.flags & 1536 ? 1536 : 0); + (symbol.flags & 793064 ? 793064 : 0) | + (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -25604,7 +30840,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -25631,7 +30867,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1) { + if (ts.getModifierFlags(node) & 1) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -25639,11 +30875,11 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 107455) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1536).flags & 1536)) { + if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793056) { + if (target.flags & 793064) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -25659,7 +30895,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -25687,7 +30923,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); } @@ -25705,7 +30941,7 @@ var ts; error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69) { @@ -25749,7 +30985,7 @@ var ts; continue; } var _a = exports[id], declarations = _a.declarations, flags = _a.flags; - if (flags & (1536 | 64 | 384)) { + if (flags & (1920 | 64 | 384)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -25919,9 +31155,10 @@ var ts; } } function checkSourceFile(node) { - var start = new Date().getTime(); + ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); - ts.checkTime += new Date().getTime() - start; + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); } function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -25992,7 +31229,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -26023,7 +31260,7 @@ var ts; case 221: case 222: if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056); + copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; case 179: @@ -26036,7 +31273,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = location.flags; + memberFlags = ts.getModifierFlags(location); location = location.parent; } copySymbols(globals, meaning); @@ -26044,7 +31281,7 @@ var ts; function copySymbol(symbol, meaning) { if (symbol.flags & meaning) { var id = symbol.name; - if (!ts.hasProperty(symbols, id)) { + if (!symbols[id]) { symbols[id] = symbol; } } @@ -26132,15 +31369,13 @@ var ts; default: } } - if (entityName.parent.kind === 235) { - return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); + if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); } - if (entityName.kind !== 172) { - if (isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); - } + if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 229); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -26148,18 +31383,18 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 194) { - meaning = 793056; + meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; } } else { - meaning = 1536; + meaning = 1920; } meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if (ts.isExpression(entityName)) { + else if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; } @@ -26185,7 +31420,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793056 : 1536; + var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 246) { @@ -26237,7 +31472,7 @@ var ts; } } case 95: - var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case 165: return getTypeFromTypeNode(node).symbol; @@ -26277,16 +31512,16 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { return unknownType; } - if (ts.isTypeNode(node)) { + if (ts.isPartOfTypeNode(node)) { return getTypeFromTypeNode(node); } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { return getTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -26345,11 +31580,11 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return checkExpression(expr); + return getRegularTypeOfLiteralType(checkExpression(expr)); } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 32 + return ts.getModifierFlags(node) & 32 ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -26358,7 +31593,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!ts.hasProperty(propsByName, p.name)) { + if (!propsByName[p.name]) { propsByName[p.name] = p; } }); @@ -26368,9 +31603,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_20 = symbol.name; + var name_23 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_20); + var symbol = getPropertyOfType(t, name_23); if (symbol) { symbols_3.push(symbol); } @@ -26390,11 +31625,17 @@ var ts; return [symbol]; } function isArgumentsLocalBinding(node) { - return getReferencedValueSymbol(node) === argumentsSymbol; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + return getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol) { + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -26403,7 +31644,7 @@ var ts; if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455) - : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -26411,34 +31652,48 @@ var ts; return s && !!(s.flags & 107455); } } - function getReferencedExportContainer(node) { - var symbol = getReferencedValueSymbol(node); - if (symbol) { - if (symbol.flags & 1048576) { - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (exportSymbol.flags & 944) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { - if (parentSymbol.valueDeclaration === ts.getSourceFileOfNode(node)) { - return parentSymbol.valueDeclaration; + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944) { + return undefined; } + symbol = exportSymbol; } - for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 225 || n.kind === 224) && getSymbolOfNode(n) === parentSymbol) { - return n; + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { + var symbolFile = parentSymbol.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + for (var n = node.parent; n; n = n.parent) { + if (ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) { + return n; + } } } } } } function getReferencedImportDeclaration(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && symbol.flags & 8388608 ? getDeclarationOfAliasSymbol(symbol) : undefined; + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && symbol.flags & 8388608) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418) { @@ -26466,30 +31721,53 @@ var ts; return false; } function getReferencedDeclarationWithCollidingName(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; } function isDeclarationWithCollidingName(node) { - return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; } function isValueAliasDeclaration(node) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + return true; + } switch (node.kind) { case 229: case 231: case 232: case 234: case 238: - return isAliasResolvedToValue(getSymbolOfNode(node)); + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); case 235: - return node.expression && node.expression.kind === 69 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; + return node.expression + && node.expression.kind === 69 + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -26507,9 +31785,13 @@ var ts; return isConstEnumSymbol(s) || s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + return true; + } if (ts.isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (getSymbolLinks(symbol).referenced) { + if (symbol && getSymbolLinks(symbol).referenced) { return true; } } @@ -26528,7 +31810,8 @@ var ts; return false; } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + node = ts.getParseTreeNode(node); + return node ? getNodeLinks(node).flags : undefined; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -26547,15 +31830,19 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 80896 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; } - function getTypeReferenceSerializationKind(typeName) { - var valueSymbol = resolveEntityName(typeName, 107455, true); + function getTypeReferenceSerializationKind(typeName, location) { + var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); + var globalPromiseSymbol = tryGetGlobalPromiseConstructorSymbol(); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } var constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793056, true); + var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -26566,22 +31853,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16)) { - return ts.TypeReferenceSerializationKind.VoidType; + else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 8)) { + else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 132)) { + else if (isTypeOfKind(type, 340)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 258)) { + else if (isTypeOfKind(type, 34)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTypeOfKind(type, 8192)) { + else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 16777216)) { + else if (isTypeOfKind(type, 512)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -26597,7 +31884,7 @@ var ts; function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 | 131072)) - ? getTypeOfSymbol(symbol) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -26616,16 +31903,44 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return ts.hasProperty(globals, name); + return !!globals[name]; } - function getReferencedValueSymbol(reference) { - return getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + var parent_13 = reference.parent; + if (ts.isDeclaration(parent_13) && reference === parent_13.name) { + location = getDeclarationContainer(parent_13); + } + } + return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); } function getReferencedValueDeclaration(reference) { - ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getReferencedValueSymbol(reference); - return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 && type.flags & 16777216); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -26633,9 +31948,6 @@ var ts; if (resolvedTypeReferenceDirectives) { fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { - if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { - continue; - } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; @@ -26671,7 +31983,9 @@ var ts; isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { @@ -26679,7 +31993,7 @@ var ts; } var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) ? 107455 | 1048576 - : 793056 | 1536; + : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -26709,9 +32023,9 @@ var ts; } var current = symbol; while (true) { - var parent_12 = getParentOfSymbol(current); - if (parent_12) { - current = parent_12; + var parent_14 = getParentOfSymbol(current); + if (parent_14) { + current = parent_14; } else { break; @@ -26739,11 +32053,15 @@ var ts; return ts.getDeclarationOfKind(moduleSymbol, 256); } function initializeTypeChecker() { - ts.forEach(host.getSourceFiles(), function (file) { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); - }); + } var augmentations; - ts.forEach(host.getSourceFiles(), function (file) { + var requestedExternalEmitHelpers = 0; + var firstFileRequestingExternalHelpers; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -26754,14 +32072,28 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - mergeSymbolTable(globals, file.symbol.globalExports); + var source = file.symbol.globalExports; + for (var id in source) { + if (!(id in globals)) { + globals[id] = source[id]; + } + } } - }); + if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { + var fileRequestedExternalEmitHelpers = file.flags & 31744; + if (fileRequestedExternalEmitHelpers) { + requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; + if (firstFileRequestingExternalHelpers === undefined) { + firstFileRequestingExternalHelpers = file; + } + } + } + } if (augmentations) { - for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { - var list = augmentations_1[_i]; - for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { - var augmentation = list_2[_a]; + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; mergeModuleAugmentation(augmentation); } } @@ -26785,10 +32117,11 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056, undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064, undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); + tryGetGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalSymbol("Promise", 107455, undefined) && getGlobalPromiseConstructorSymbol(); }); getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); getGlobalThenableType = ts.memoize(createThenableType); getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); }); @@ -26805,9 +32138,42 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { + var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); + if (helpersModule) { + var exports = helpersModule.exports; + if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { + verifyHelperSymbol(exports, "__extends", 107455); + } + if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { + verifyHelperSymbol(exports, "__assign", 107455); + } + if (requestedExternalEmitHelpers & 2048) { + verifyHelperSymbol(exports, "__decorate", 107455); + if (compilerOptions.emitDecoratorMetadata) { + verifyHelperSymbol(exports, "__metadata", 107455); + } + } + if (requestedExternalEmitHelpers & 4096) { + verifyHelperSymbol(exports, "__param", 107455); + } + if (requestedExternalEmitHelpers & 8192) { + verifyHelperSymbol(exports, "__awaiter", 107455); + if (languageVersion < 2) { + verifyHelperSymbol(exports, "__generator", 107455); + } + } + } + } + } + function verifyHelperSymbol(symbols, name, meaning) { + var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); + if (!symbol) { + error(undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -26819,7 +32185,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(65536); + var thenableType = createObjectType(2097152); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -26847,49 +32213,9 @@ var ts; return false; } function checkGrammarModifiers(node) { - switch (node.kind) { - case 149: - case 150: - case 148: - case 145: - case 144: - case 147: - case 146: - case 153: - case 225: - case 230: - case 229: - case 236: - case 235: - case 179: - case 180: - case 142: - break; - case 220: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && - node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 221: - case 222: - case 200: - case 223: - if (node.modifiers && node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 224: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && - node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - default: - return false; - } - if (!node.modifiers) { - return; + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -27027,7 +32353,7 @@ var ts; node.kind !== 150) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 && node.parent.flags & 128)) { + if (!(node.parent.kind === 221 && ts.getModifierFlags(node.parent) & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -27082,10 +32408,57 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function checkGrammarAsyncModifier(node, asyncModifier) { - if (languageVersion < 2) { - return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 149: + case 150: + case 148: + case 145: + case 144: + case 147: + case 146: + case 153: + case 225: + case 230: + case 229: + case 236: + case 235: + case 179: + case 180: + case 142: + return false; + default: + if (node.parent.kind === 226 || node.parent.kind === 256) { + return false; + } + switch (node.kind) { + case 220: + return nodeHasAnyModifiersExcept(node, 118); + case 221: + return nodeHasAnyModifiersExcept(node, 115); + case 222: + case 200: + case 223: + return true; + case 224: + return nodeHasAnyModifiersExcept(node, 74); + default: + ts.Debug.fail(); + return false; + } } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { case 147: case 220: @@ -27175,7 +32548,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1023) { + if (ts.getModifierFlags(parameter) !== 0) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -27212,8 +32585,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { - var arg = args_1[_i]; + for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { + var arg = args_2[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -27314,30 +32687,34 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; - var _loop_2 = function(prop) { - var name_21 = prop.name; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var name_24 = prop.name; if (prop.kind === 193 || - name_21.kind === 140) { - checkGrammarComputedPropertyName(name_21); + name_24.kind === 140) { + checkGrammarComputedPropertyName(name_24); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { - return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } - ts.forEach(prop.modifiers, function (mod) { - if (mod.kind !== 118 || prop.kind !== 147) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 118 || prop.kind !== 147) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } } - }); + } var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_21.kind === 8) { - checkGrammarNumericLiteral(name_21); + if (name_24.kind === 8) { + checkGrammarNumericLiteral(name_24); } currentKind = Property; } @@ -27353,51 +32730,46 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_21); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); if (effectiveName === undefined) { - return "continue"; + continue; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_21, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_21)); + grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } - }; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var state_3 = _loop_2(prop); - if (typeof state_3 === "object") return state_3.value; } } function checkGrammarJsxElement(node) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247) { continue; } var jsxAttr = attr; - var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { - seen[name_22.text] = true; + var name_25 = jsxAttr.name; + if (!seen[name_25.text]) { + seen[name_25.text] = true; } else { - return grammarErrorOnNode(name_22, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -27447,7 +32819,7 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(accessor.flags & 128)) { + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { @@ -27584,10 +32956,26 @@ var ts; } } } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 || expr.kind === 8 || + expr.kind === 185 && expr.operator === 36 && + expr.operand.kind === 8; + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 207 && node.parent.parent.kind !== 208) { if (ts.isInAmbientContext(node)) { if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { var equalsTokenLength = "=".length; return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } @@ -27614,7 +33002,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 193) { + if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -27660,8 +33048,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); return true; } } @@ -27721,8 +33109,8 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || - (node.flags & 2) || - (node.flags & (1 | 512))) { + node.kind === 228 || + ts.getModifierFlags(node) & (2 | 1 | 512)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -27767,18 +33155,8019 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); return true; } } - var _a; + function getAmbientModules() { + var result = []; + for (var sym in globals) { + if (ambientModuleSymbolRegex.test(sym)) { + result.push(globals[sym]); + } + } + return result; + } } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; (function (ts) { + ; + var nodeEdgeTraversalMap = ts.createMap((_a = {}, + _a[139] = [ + { name: "left", test: ts.isEntityName }, + { name: "right", test: ts.isIdentifier } + ], + _a[143] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[177] = [ + { name: "type", test: ts.isTypeNode }, + { name: "expression", test: ts.isUnaryExpression } + ], + _a[195] = [ + { name: "expression", test: ts.isExpression }, + { name: "type", test: ts.isTypeNode } + ], + _a[196] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[224] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[225] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[226] = [ + { name: "statements", test: ts.isStatement } + ], + _a[229] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "moduleReference", test: ts.isModuleReference } + ], + _a[240] = [ + { name: "expression", test: ts.isExpression, optional: true } + ], + _a[255] = [ + { name: "name", test: ts.isPropertyName }, + { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } + ], + _a + )); + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + function reduceEachChild(node, f, initial) { + if (node === undefined) { + return initial; + } + var kind = node.kind; + if ((kind > 0 && kind <= 138)) { + return initial; + } + if ((kind >= 154 && kind <= 166)) { + return initial; + } + var result = initial; + switch (node.kind) { + case 198: + case 201: + case 193: + case 217: + case 287: + break; + case 140: + result = reduceNode(node.expression, f, result); + break; + case 142: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 143: + result = reduceNode(node.expression, f, result); + break; + case 145: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 147: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 148: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 149: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 150: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 167: + case 168: + result = ts.reduceLeft(node.elements, f, result); + break; + case 169: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 170: + result = ts.reduceLeft(node.elements, f, result); + break; + case 171: + result = ts.reduceLeft(node.properties, f, result); + break; + case 172: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.name, f, result); + break; + case 173: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.argumentExpression, f, result); + break; + case 174: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 175: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 176: + result = reduceNode(node.tag, f, result); + result = reduceNode(node.template, f, result); + break; + case 179: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 180: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 178: + case 181: + case 182: + case 183: + case 184: + case 190: + case 191: + case 196: + result = reduceNode(node.expression, f, result); + break; + case 185: + case 186: + result = reduceNode(node.operand, f, result); + break; + case 187: + result = reduceNode(node.left, f, result); + result = reduceNode(node.right, f, result); + break; + case 188: + result = reduceNode(node.condition, f, result); + result = reduceNode(node.whenTrue, f, result); + result = reduceNode(node.whenFalse, f, result); + break; + case 189: + result = reduceNode(node.head, f, result); + result = ts.reduceLeft(node.templateSpans, f, result); + break; + case 192: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 194: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + break; + case 197: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.literal, f, result); + break; + case 199: + result = ts.reduceLeft(node.statements, f, result); + break; + case 200: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.declarationList, f, result); + break; + case 202: + result = reduceNode(node.expression, f, result); + break; + case 203: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.thenStatement, f, result); + result = reduceNode(node.elseStatement, f, result); + break; + case 204: + result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, f, result); + break; + case 205: + case 212: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 206: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.condition, f, result); + result = reduceNode(node.incrementor, f, result); + result = reduceNode(node.statement, f, result); + break; + case 207: + case 208: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 211: + case 215: + result = reduceNode(node.expression, f, result); + break; + case 213: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.caseBlock, f, result); + break; + case 214: + result = reduceNode(node.label, f, result); + result = reduceNode(node.statement, f, result); + break; + case 216: + result = reduceNode(node.tryBlock, f, result); + result = reduceNode(node.catchClause, f, result); + result = reduceNode(node.finallyBlock, f, result); + break; + case 218: + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 219: + result = ts.reduceLeft(node.declarations, f, result); + break; + case 220: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 221: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 227: + result = ts.reduceLeft(node.clauses, f, result); + break; + case 230: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.importClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 231: + result = reduceNode(node.name, f, result); + result = reduceNode(node.namedBindings, f, result); + break; + case 232: + result = reduceNode(node.name, f, result); + break; + case 233: + case 237: + result = ts.reduceLeft(node.elements, f, result); + break; + case 234: + case 238: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + break; + case 235: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.expression, f, result); + break; + case 236: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.exportClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 241: + result = reduceNode(node.openingElement, f, result); + result = ts.reduceLeft(node.children, f, result); + result = reduceNode(node.closingElement, f, result); + break; + case 242: + case 243: + result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.attributes, f, result); + break; + case 245: + result = reduceNode(node.tagName, f, result); + break; + case 246: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 247: + result = reduceNode(node.expression, f, result); + break; + case 248: + result = reduceNode(node.expression, f, result); + break; + case 249: + result = reduceNode(node.expression, f, result); + case 250: + result = ts.reduceLeft(node.statements, f, result); + break; + case 251: + result = ts.reduceLeft(node.types, f, result); + break; + case 252: + result = reduceNode(node.variableDeclaration, f, result); + result = reduceNode(node.block, f, result); + break; + case 253: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 254: + result = reduceNode(node.name, f, result); + result = reduceNode(node.objectAssignmentInitializer, f, result); + break; + case 256: + result = ts.reduceLeft(node.statements, f, result); + break; + case 288: + result = reduceNode(node.expression, f, result); + break; + default: + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_1 = edgeTraversalPath; _i < edgeTraversalPath_1.length; _i++) { + var edge = edgeTraversalPath_1[_i]; + var value = node[edge.name]; + if (value !== undefined) { + result = ts.isArray(value) + ? ts.reduceLeft(value, f, result) + : f(result, value); + } + } + } + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { + if (node === undefined) { + return undefined; + } + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + if (!optional) { + Debug.failNotOptional(); + } + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + if (parenthesize !== undefined) { + visitedNode = parenthesize(visitedNode, parentNode); + } + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + function visitNodes(nodes, visitor, test, start, count, parenthesize, parentNode) { + if (nodes === undefined) { + return undefined; + } + var updated; + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + updated = ts.createNodeArray([], undefined, nodes.hasTrailingComma && start + count === length); + } + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + updated = ts.createNodeArray(nodes.slice(0, i), nodes, nodes.hasTrailingComma); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + visitedNode = parenthesize + ? parenthesize(visitedNode, parentNode) + : visitedNode; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + var visitedNode = parenthesize + ? parenthesize(visited, parentNode) + : visited; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + function visitEachChild(node, visitor, context) { + if (node === undefined) { + return undefined; + } + var kind = node.kind; + if ((kind > 0 && kind <= 138)) { + return node; + } + if ((kind >= 154 && kind <= 166)) { + return node; + } + switch (node.kind) { + case 198: + case 201: + case 193: + case 217: + return node; + case 140: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + case 142: + return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 145: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 147: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 148: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 149: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 150: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 167: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 168: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 169: + return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 170: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 171: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 172: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 173: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 174: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 175: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 176: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + case 178: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 179: + return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 180: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, true), context.endLexicalEnvironment())); + case 181: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 182: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 183: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 185: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 186: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 188: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 189: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 190: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 191: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 194: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 197: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + case 199: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 200: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 202: + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 203: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); + case 204: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 205: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 206: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 207: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 208: + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 209: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + case 210: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + case 211: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + case 212: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 213: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 214: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 215: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 216: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + case 218: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 219: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 220: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 221: + return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 227: + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 230: + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 231: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); + case 232: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 233: + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 234: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 235: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 236: + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); + case 237: + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + case 238: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 241: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 242: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 243: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 245: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 246: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 247: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 248: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 249: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + case 250: + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 251: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 252: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + case 253: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 254: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 256: + context.startLexicalEnvironment(); + return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); + case 288: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + default: + var updated = void 0; + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_2 = edgeTraversalPath; _i < edgeTraversalPath_2.length; _i++) { + var edge = edgeTraversalPath_2[_i]; + var value = node[edge.name]; + if (value !== undefined) { + var visited = ts.isArray(value) + ? visitNodes(value, visitor, edge.test, 0, value.length, edge.parenthesize, node) + : visitNode(value, visitor, edge.test, edge.optional, edge.lift, edge.parenthesize, node); + if (updated !== undefined || visited !== value) { + if (updated === undefined) { + updated = ts.getMutableClone(node); + } + if (visited !== value) { + updated[edge.name] = visited; + } + } + } + } + } + return updated ? ts.updateNode(updated, node) : node; + } + } + ts.visitEachChild = visitEachChild; + function mergeFunctionBodyLexicalEnvironment(body, declarations) { + if (body && declarations !== undefined && declarations.length > 0) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.createNodeArray(ts.concatenate(body.statements, declarations), body.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([ts.createReturn(body, body)].concat(declarations), body), body, true); + } + } + return body; + } + ts.mergeFunctionBodyLexicalEnvironment = mergeFunctionBodyLexicalEnvironment; + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + function extractSingleNode(nodes) { + Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0; + } + else if (node.transformFlags & 536870912) { + return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + } + function aggregateTransformFlagsForSubtree(node) { + if (ts.hasModifier(node, 2) || ts.isTypeNode(node)) { + return 0; + } + return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0); + } + function aggregateTransformFlagsForChildNode(transformFlags, child) { + return transformFlags | aggregateTransformFlagsForNode(child); + } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 154 && kind <= 166) { + return -3; + } + switch (kind) { + case 174: + case 175: + case 170: + return 537133909; + case 225: + return 546335573; + case 142: + return 538968917; + case 180: + return 550710101; + case 179: + case 220: + return 550726485; + case 219: + return 538968917; + case 221: + case 192: + return 537590613; + case 148: + return 550593365; + case 147: + case 149: + case 150: + return 550593365; + case 117: + case 130: + case 127: + case 132: + case 120: + case 133: + case 103: + case 141: + case 144: + case 146: + case 151: + case 152: + case 153: + case 222: + case 223: + return -3; + case 171: + return 537430869; + default: + return 536871765; + } + } + var Debug; + (function (Debug) { + Debug.failNotOptional = Debug.shouldAssert(1) + ? function (message) { return Debug.assert(false, message || "Node not optional."); } + : function (message) { }; + Debug.failBadSyntaxKind = Debug.shouldAssert(1) + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."); }); } + : function (node, message) { }; + Debug.assertNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."); }); } + : function (node, test, message) { }; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + })(Debug = ts.Debug || (ts.Debug = {})); + var _a; +})(ts || (ts = {})); +var ts; +(function (ts) { + function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { + if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + var right = node.right; + if (ts.isDestructuringAssignment(right)) { + return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); + } + else { + return node.right; + } + } + var location = node; + var value = node.right; + var expressions = []; + if (needsValue) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment, visitor); + } + else if (ts.nodeIsSynthesized(node)) { + location = value; + } + flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); + if (needsValue) { + expressions.push(value); + } + var expression = ts.inlineExpressions(expressions); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location) { + var expression = ts.createAssignment(name, value, location); + context.setNodeEmitFlags(expression, 2048); + ts.aggregateTransformFlags(expression); + expressions.push(expression); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function flattenParameterDestructuring(context, node, value, visitor) { + var declarations = []; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location) { + var declaration = ts.createVariableDeclaration(name, undefined, value, location); + context.setNodeEmitFlags(declaration, 2048); + ts.aggregateTransformFlags(declaration); + declarations.push(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(undefined); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenParameterDestructuring = flattenParameterDestructuring; + function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { + var declarations = []; + var pendingAssignments; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location, original) { + if (pendingAssignments) { + pendingAssignments.push(value); + value = ts.inlineExpressions(pendingAssignments); + pendingAssignments = undefined; + } + var declaration = ts.createVariableDeclaration(name, undefined, value, location); + declaration.original = original; + context.setNodeEmitFlags(declaration, 2048); + declarations.push(declaration); + ts.aggregateTransformFlags(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + if (recordTempVariable) { + var assignment = ts.createAssignment(name, value, location); + if (pendingAssignments) { + pendingAssignments.push(assignment); + } + else { + pendingAssignments = [assignment]; + } + } + else { + emitAssignment(name, value, location, undefined); + } + return name; + } + } + ts.flattenVariableDestructuring = flattenVariableDestructuring; + function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { + var pendingAssignments = []; + flattenDestructuring(context, node, undefined, node, emitAssignment, emitTempVariableAssignment, visitor); + var expression = ts.inlineExpressions(pendingAssignments); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location, original) { + var left = nameSubstitution && nameSubstitution(name) || name; + emitPendingAssignment(left, value, location, original); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitPendingAssignment(name, value, location, undefined); + return name; + } + function emitPendingAssignment(name, value, location, original) { + var expression = ts.createAssignment(name, value, location); + expression.original = original; + context.setNodeEmitFlags(expression, 2048); + pendingAssignments.push(expression); + return expression; + } + } + ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; + function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { + if (value && visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + if (ts.isBinaryExpression(root)) { + emitDestructuringAssignment(root.left, value, location); + } + else { + emitBindingElement(root, value); + } + function emitDestructuringAssignment(bindingTarget, value, location) { + var target; + if (ts.isShorthandPropertyAssignment(bindingTarget)) { + var initializer = visitor + ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) + : bindingTarget.objectAssignmentInitializer; + if (initializer) { + value = createDefaultValueCheck(value, initializer, location); + } + target = bindingTarget.name; + } + else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56) { + var initializer = visitor + ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) + : bindingTarget.right; + value = createDefaultValueCheck(value, initializer, location); + target = bindingTarget.left; + } + else { + target = bindingTarget; + } + if (target.kind === 171) { + emitObjectLiteralAssignment(target, value, location); + } + else if (target.kind === 170) { + emitArrayLiteralAssignment(target, value, location); + } + else { + var name_26 = ts.getMutableClone(target); + context.setSourceMapRange(name_26, target); + context.setCommentRange(name_26, target); + emitAssignment(name_26, value, location, undefined); + } + } + function emitObjectLiteralAssignment(target, value, location) { + var properties = target.properties; + if (properties.length !== 1) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + if (p.kind === 253 || p.kind === 254) { + var propName = p.name; + var target_1 = p.kind === 254 ? p : p.initializer || propName; + emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); + } + } + } + function emitArrayLiteralAssignment(target, value, location) { + var elements = target.elements; + var numElements = elements.length; + if (numElements !== 1) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var e = elements[i]; + if (e.kind !== 193) { + if (e.kind !== 191) { + emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); + } + else if (i === numElements - 1) { + emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); + } + } + } + } + function emitBindingElement(target, value) { + var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + if (initializer) { + value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + } + else if (!value) { + value = ts.createVoidZero(); + } + var name = target.name; + if (ts.isBindingPattern(name)) { + var elements = name.elements; + var numElements = elements.length; + if (numElements !== 1) { + value = ensureIdentifier(value, numElements !== 0, target, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (ts.isOmittedExpression(element)) { + continue; + } + else if (name.kind === 167) { + var propName = element.propertyName || element.name; + emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); + } + else { + if (!element.dotDotDotToken) { + emitBindingElement(element, ts.createElementAccess(value, i)); + } + else if (i === numElements - 1) { + emitBindingElement(element, ts.createArraySlice(value, i)); + } + } + } + } + else { + emitAssignment(name, value, target, target); + } + } + function createDefaultValueCheck(value, defaultValue, location) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53), defaultValue, ts.createToken(54), value); + } + function createDestructuringPropertyAccess(expression, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, false, propertyName, emitTempVariableAssignment)); + } + else if (ts.isLiteralExpression(propertyName)) { + var clone_2 = ts.getSynthesizedClone(propertyName); + clone_2.text = ts.unescapeIdentifier(clone_2.text); + return ts.createElementAccess(expression, clone_2); + } + else { + if (ts.isGeneratedIdentifier(propertyName)) { + var clone_3 = ts.getSynthesizedClone(propertyName); + clone_3.text = ts.unescapeIdentifier(clone_3.text); + return ts.createPropertyAccess(expression, clone_3); + } + else { + return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + } + } + } + } + function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + if (visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + return emitTempVariableAssignment(value, location); + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var USE_NEW_TYPE_METADATA_FORMAT = false; + function transformTypeScript(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentScope; + var currentSourceFileExternalHelpersModuleName; + var enabledSubstitutions; + var classAliases; + var applicableSubstitutions; + var currentSuperContainer; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function saveStateAndInvoke(node, f) { + var savedCurrentScope = currentScope; + onBeforeVisitNode(node); + var visited = f(node); + currentScope = savedCurrentScope; + return visited; + } + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + function visitorWorker(node) { + if (node.kind === 256) { + return visitSourceFile(node); + } + else if (node.transformFlags & 1) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + function namespaceElementVisitorWorker(node) { + if (node.kind === 236 || + node.kind === 230 || + node.kind === 231 || + (node.kind === 229 && + node.moduleReference.kind === 240)) { + return undefined; + } + else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + function classElementVisitorWorker(node) { + switch (node.kind) { + case 148: + return undefined; + case 145: + case 153: + case 149: + case 150: + case 147: + return visitorWorker(node); + case 198: + return node; + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitTypeScript(node) { + if (ts.hasModifier(node, 2) && ts.isStatement(node)) { + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 82: + case 77: + return currentNamespace ? undefined : node; + case 112: + case 110: + case 111: + case 115: + case 118: + case 74: + case 122: + case 128: + case 160: + case 161: + case 159: + case 154: + case 141: + case 117: + case 120: + case 132: + case 130: + case 127: + case 103: + case 133: + case 157: + case 156: + case 158: + case 155: + case 162: + case 163: + case 164: + case 165: + case 166: + case 153: + case 143: + case 223: + case 145: + case 148: + return undefined; + case 222: + return ts.createNotEmittedStatement(node); + case 221: + return visitClassDeclaration(node); + case 192: + return visitClassExpression(node); + case 251: + return visitHeritageClause(node); + case 194: + return visitExpressionWithTypeArguments(node); + case 147: + return visitMethodDeclaration(node); + case 149: + return visitGetAccessor(node); + case 150: + return visitSetAccessor(node); + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + case 180: + return visitArrowFunction(node); + case 142: + return visitParameter(node); + case 178: + return visitParenthesizedExpression(node); + case 177: + case 195: + return visitAssertionExpression(node); + case 196: + return visitNonNullExpression(node); + case 224: + return visitEnumDeclaration(node); + case 184: + return visitAwaitExpression(node); + case 200: + return visitVariableStatement(node); + case 225: + return visitModuleDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 256: + case 227: + case 226: + case 199: + currentScope = node; + break; + } + } + function visitSourceFile(node) { + currentSourceFile = node; + if (node.flags & 31744 + && compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); + var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); + var externalHelpersModuleImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + externalHelpersModuleImport.parent = node; + externalHelpersModuleImport.flags &= ~8; + statements.push(externalHelpersModuleImport); + currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + currentSourceFileExternalHelpersModuleName = undefined; + node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + node.externalHelpersModuleName = externalHelpersModuleName; + } + else { + node = ts.visitEachChild(node, visitor, context); + } + setNodeEmitFlags(node, 1 | node.emitFlags); + return node; + } + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function visitClassDeclaration(node) { + var staticProperties = getInitializedProperties(node, true); + var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; + var isDecoratedClass = shouldEmitDecorateCallForClass(node); + var classAlias; + var name = node.name; + if (!name && staticProperties.length > 0) { + name = ts.getGeneratedNameForNode(node); + } + var statements = []; + if (!isDecoratedClass) { + var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + ts.setOriginalNode(classDeclaration, node); + if (staticProperties.length > 0) { + setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + } + statements.push(classDeclaration); + } + else { + classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); + } + if (staticProperties.length) { + addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, true)); + } + addClassElementDecorationStatements(statements, node, false); + addClassElementDecorationStatements(statements, node, true); + addConstructorDecorationStatement(statements, node, classAlias); + if (isNamespaceExport(node)) { + addExportMemberAssignment(statements, node); + } + else if (isDecoratedClass) { + if (isDefaultExternalModuleExport(node)) { + statements.push(ts.createExportAssignment(undefined, undefined, false, getLocalName(node))); + } + else if (isNamedExternalModuleExport(node)) { + statements.push(createExternalModuleExport(name)); + } + } + return statements; + } + function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + var location = ts.moveRangePastDecorators(node); + var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), location), node); + if (!name) { + name = ts.getGeneratedNameForNode(node); + } + var classAlias; + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + } + var declaredName = getDeclarationName(node, true); + var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) + ]), location); + setCommentRange(transformedClassExpression, node); + statements.push(ts.setOriginalNode(transformedClassExpression, node)); + if (classAlias) { + statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(declaredName, undefined, classAlias) + ]), location), node)); + } + return classAlias; + } + function visitClassExpression(node) { + var staticProperties = getInitializedProperties(node, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, heritageClauses !== undefined); + var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members, node), node); + if (staticProperties.length > 0) { + var expressions = []; + var temp = ts.createTempVariable(hoistVariableDeclaration); + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + } + setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + return classExpression; + } + function transformClassMembers(node, hasExtendsClause) { + var members = []; + var constructor = transformConstructor(node, hasExtendsClause); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.createNodeArray(members, node.members); + } + function transformConstructor(node, hasExtendsClause) { + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = node.transformFlags & 131072; + var constructor = ts.getFirstConstructorWithBody(node); + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor(undefined, undefined, parameters, body, constructor || node), constructor)); + } + function transformConstructorParameters(constructor) { + return constructor + ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) + : []; + } + function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + var statements = []; + var indexOfFirstStatement = 0; + startLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (hasExtendsClause) { + statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + var properties = getInitializedProperties(node, false); + addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + if (constructor) { + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + ts.addRange(statements, endLexicalEnvironment()); + return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined), true); + } + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + var index = ts.addPrologueDirectives(result, statements, false, visitor); + if (index === statements.length) { + return index; + } + var statement = statements[index]; + if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92) + && ts.isIdentifier(parameter.name); + } + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + setNodeEmitFlags(propertyName, 49152 | 1536); + var localName = ts.getMutableClone(name); + setNodeEmitFlags(localName, 49152); + return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); + } + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, true); + } + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, false); + } + function isInitializedProperty(member, isStatic) { + return member.kind === 145 + && isStatic === ts.hasModifier(member, 32) + && member.initializer !== undefined; + } + function addInitializedPropertyStatements(statements, node, properties, receiver) { + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var property = properties_7[_i]; + var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); + setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + setCommentRange(statement, property); + statements.push(statement); + } + } + function generateInitializedPropertyExpressions(node, properties, receiver) { + var expressions = []; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var expression = transformInitializedProperty(node, property, receiver); + expression.startsOnNewLine = true; + setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + setCommentRange(expression, property); + expressions.push(expression); + } + return expressions; + } + function transformInitializedProperty(node, property, receiver) { + var propertyName = visitPropertyNameOfClassElement(property); + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); + return ts.createAssignment(memberAccess, initializer); + } + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + } + function isStaticDecoratedClassElement(member) { + return isDecoratedClassElement(member, true); + } + function isInstanceDecoratedClassElement(member) { + return isDecoratedClassElement(member, false); + } + function isDecoratedClassElement(member, isStatic) { + return ts.nodeOrChildIsDecorated(member) + && isStatic === ts.hasModifier(member, 32); + } + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 149: + case 150: + return getAllDecoratorsOfAccessors(node, member); + case 147: + return getAllDecoratorsOfMethod(member); + case 145: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + if (accessor !== firstAccessor) { + return undefined; + } + var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + function transformAllDecoratorsOfDeclaration(node, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, decoratorExpressions); + return decoratorExpressions; + } + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, true); + var descriptor = languageVersion > 0 + ? member.kind === 145 + ? ts.createVoidZero() + : ts.createNull() + : undefined; + var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + setNodeEmitFlags(helper, 49152); + return helper; + } + function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { + var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + if (expression) { + statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + } + } + function generateConstructorDecorationExpression(node, decoratedClassAlias) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + if (decoratedClassAlias) { + var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); + var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152); + return result; + } + else { + var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152); + return result; + } + } + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); + setNodeEmitFlags(helper, 49152); + expressions.push(helper); + } + } + return expressions; + } + function addTypeMetadata(node, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, decoratorExpressions); + } + else { + addOldTypeMetadata(node, decoratorExpressions); + } + } + function addOldTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeParameterTypesOfNode(node)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); + } + } + } + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 147 + || kind === 149 + || kind === 150 + || kind === 145; + } + function shouldAddReturnTypeMetadata(node) { + return node.kind === 147; + } + function shouldAddParamTypesMetadata(node) { + var kind = node.kind; + return kind === 221 + || kind === 192 + || kind === 147 + || kind === 149 + || kind === 150; + } + function serializeTypeOfNode(node) { + switch (node.kind) { + case 145: + case 142: + case 149: + return serializeTypeNode(node.type); + case 150: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 221: + case 192: + case 147: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + function getRestParameterElementType(node) { + if (node && node.kind === 160) { + return node.elementType; + } + else if (node && node.kind === 155) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + function serializeParameterTypesOfNode(node) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = valueDeclaration.parameters; + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunctionLike(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 103: + return ts.createVoidZero(); + case 164: + return serializeTypeNode(node.type); + case 156: + case 157: + return ts.createIdentifier("Function"); + case 160: + case 161: + return ts.createIdentifier("Array"); + case 154: + case 120: + return ts.createIdentifier("Boolean"); + case 132: + return ts.createIdentifier("String"); + case 166: + switch (node.literal.kind) { + case 9: + return ts.createIdentifier("String"); + case 8: + return ts.createIdentifier("Number"); + case 99: + case 84: + return ts.createIdentifier("Boolean"); + default: + ts.Debug.failBadSyntaxKind(node.literal); + break; + } + break; + case 130: + return ts.createIdentifier("Number"); + case 133: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 155: + return serializeTypeReferenceNode(node); + case 158: + case 159: + case 162: + case 163: + case 117: + case 165: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + return ts.createIdentifier("Object"); + } + function serializeTypeReferenceNode(node) { + switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + case ts.TypeReferenceSerializationKind.Unknown: + var serialized = serializeEntityNameAsExpression(node.typeName, true); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName, false); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + default: + return ts.createIdentifier("Object"); + } + } + function serializeEntityNameAsExpression(node, useFallback) { + switch (node.kind) { + case 69: + var name_27 = ts.getMutableClone(node); + name_27.flags &= ~8; + name_27.original = undefined; + name_27.parent = currentScope; + if (useFallback) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_27), ts.createLiteral("undefined")), name_27); + } + return name_27; + case 139: + return serializeQualifiedNameAsExpression(node, useFallback); + } + } + function serializeQualifiedNameAsExpression(node, useFallback) { + var left; + if (node.left.kind === 69) { + left = serializeEntityNameAsExpression(node.left, useFallback); + } + else if (useFallback) { + var temp = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, true)), temp); + } + else { + left = serializeEntityNameAsExpression(node.left, false); + } + return ts.createPropertyAccess(left, node.right); + } + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53), ts.createIdentifier("Symbol"), ts.createToken(54), ts.createIdentifier("Object")); + } + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(name.text); + } + else { + return ts.getSynthesizedClone(name); + } + } + function visitPropertyNameOfClassElement(member) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + if (member.decorators) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + expression = ts.createAssignment(generatedName, expression); + } + return ts.setOriginalNode(ts.createComputedPropertyName(expression, name), name); + } + else { + return name; + } + } + function visitHeritageClause(node) { + if (node.token === 83) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.createHeritageClause(83, types, node); + } + return undefined; + } + function visitExpressionWithTypeArguments(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createExpressionWithTypeArguments(undefined, expression, node); + } + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + setCommentRange(method, node); + setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(method, node); + return method; + } + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); + } + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var func = ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + if (isNamespaceExport(node)) { + var statements = [func]; + addExportMemberAssignment(statements, node); + return statements; + } + return func; + } + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + var func = ts.createFunctionExpression(node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + return func; + } + function visitArrowFunction(node) { + var func = ts.createArrowFunction(undefined, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.equalsGreaterThanToken, transformConciseBody(node), node); + ts.setOriginalNode(func, node); + return func; + } + function transformFunctionBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformFunctionBodyWorker(node.body); + } + function transformFunctionBodyWorker(body, start) { + if (start === void 0) { start = 0; } + var savedCurrentScope = currentScope; + currentScope = body; + startLexicalEnvironment(); + var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); + var visited = ts.updateBlock(body, statements); + var declarations = endLexicalEnvironment(); + currentScope = savedCurrentScope; + return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + } + function transformConciseBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformConciseBodyWorker(node.body, false); + } + function transformConciseBodyWorker(body, forceBlockFunctionBody) { + if (ts.isBlock(body)) { + return transformFunctionBodyWorker(body); + } + else { + startLexicalEnvironment(); + var visited = ts.visitNode(body, visitor, ts.isConciseBody); + var declarations = endLexicalEnvironment(); + var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + if (forceBlockFunctionBody && !ts.isBlock(merged)) { + return ts.createBlock([ + ts.createReturn(merged) + ]); + } + else { + return merged; + } + } + } + function getPromiseConstructor(type) { + var typeName = ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function transformAsyncFunctionBody(node) { + var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(node.type) : undefined; + var isArrowFunction = node.kind === 180; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); + statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + var block = ts.createBlock(statements, node.body, true); + if (languageVersion >= 2) { + if (resolver.getNodeCheckFlags(node) & 4096) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 8); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 4); + } + } + return block; + } + else { + return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, true)); + } + } + function visitParameter(node) { + if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + return undefined; + } + var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); + ts.setOriginalNode(parameter, node); + setCommentRange(parameter, node); + setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + setNodeEmitFlags(parameter.name, 1024); + return parameter; + } + function visitVariableStatement(node) { + if (isNamespaceExport(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + } + else { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), node); + } + } + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + } + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2); + if (ts.isAssertionExpression(innerExpression)) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function shouldEmitEnumDeclaration(node) { + return !ts.isConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + function shouldEmitVarForEnumDeclaration(node) { + return !ts.hasModifier(node, 1) + || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + } + function addVarForEnumExportedFromNamespace(statements, node) { + var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); + setSourceMapRange(statement, node); + statements.push(statement); + } + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + var emitFlags = 64; + if (shouldEmitVarForEnumDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = getExportName(node); + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); + ts.setOriginalNode(enumStatement, node); + setNodeEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + if (isNamespaceExport(node)) { + addVarForEnumExportedFromNamespace(statements, node); + } + return statements; + } + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, ts.map(node.members, transformEnumMember)); + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); + } + function transformEnumMember(member) { + var name = getExpressionForPropertyName(member, false); + return ts.createStatement(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name, member), member); + } + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + function isModuleMergedWithES6Class(node) { + return languageVersion === 2 + && ts.isMergedWithClass(node); + } + function isES6ExportedDeclaration(node) { + return isExternalModuleExport(node) + && moduleKind === ts.ModuleKind.ES6; + } + function shouldEmitVarForModuleDeclaration(node) { + return !isModuleMergedWithES6Class(node) + && (!isES6ExportedDeclaration(node) + || ts.isFirstDeclarationOfKind(node, node.kind)); + } + function addVarForEnumOrModuleDeclaration(statements, node) { + var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) + ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) + : undefined, [ + ts.createVariableDeclaration(getDeclarationName(node, false, true)) + ]); + ts.setOriginalNode(statement, node); + if (node.kind === 224) { + setSourceMapRange(statement.declarationList, node); + } + else { + setSourceMapRange(statement, node); + } + setCommentRange(statement, node); + setNodeEmitFlags(statement, 32768); + statements.push(statement); + } + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + var emitFlags = 64; + if (shouldEmitVarForModuleDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = getExportName(node); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (ts.hasModifier(node, 1) && !isES6ExportedDeclaration(node)) { + var localName = getLocalName(node); + moduleArg = ts.createAssignment(localName, moduleArg); + } + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); + ts.setOriginalNode(moduleStatement, node); + setNodeEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + return statements; + } + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 226) { + ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); + if (body.kind !== 226) { + setNodeEmitFlags(block, block.emitFlags | 49152); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 225) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function shouldEmitImportEqualsDeclaration(node) { + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + return ts.visitEachChild(node, visitor, context); + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + setNodeEmitFlags(moduleReference, 49152 | 65536); + if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(node.name, undefined, moduleReference) + ]), node), node); + } + else { + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + function isNamespaceExport(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1); + } + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1); + } + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512); + } + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512); + } + function expressionToStatement(expression) { + return ts.createStatement(expression, undefined); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); + setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var statement = ts.createStatement(expression); + setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, false, true), exportValue), location); + } + function createExternalModuleExport(exportName) { + return ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([ + ts.createExportSpecifier(exportName) + ])); + } + function getNamespaceMemberName(name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), name); + var emitFlags; + if (!allowComments) { + emitFlags |= 49152; + } + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (emitFlags) { + setNodeEmitFlags(qualifiedName, emitFlags); + } + return qualifiedName; + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return getNamespaceMemberName(name, false, true); + } + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + setSourceMapRange(name, node.name); + return name; + } + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + function getLocalName(node, noSourceMaps, allowComments) { + return getDeclarationName(node, allowComments, !noSourceMaps, 262144); + } + function getExportName(node, noSourceMaps, allowComments) { + if (isNamespaceExport(node)) { + return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); + } + return getDeclarationName(node, allowComments, !noSourceMaps, 131072); + } + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name) { + var name_28 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (!allowComments) { + emitFlags |= 49152; + } + if (emitFlags) { + setNodeEmitFlags(name_28, emitFlags); + } + return name_28; + } + else { + return ts.getGeneratedNameForNode(node); + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32) + ? getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8) === 0) { + enabledSubstitutions |= 8; + context.enableSubstitution(69); + } + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 4) === 0) { + enabledSubstitutions |= 4; + context.enableSubstitution(174); + context.enableSubstitution(172); + context.enableSubstitution(173); + context.enableEmitNotification(221); + context.enableEmitNotification(147); + context.enableEmitNotification(149); + context.enableEmitNotification(150); + context.enableEmitNotification(148); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(69); + classAliases = ts.createMap(); + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(69); + context.enableSubstitution(254); + context.enableEmitNotification(225); + } + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 221 + || kind === 148 + || kind === 147 + || kind === 149 + || kind === 150; + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 225; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 224; + } + function onEmitNode(node, emit) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSuperContainer = currentSuperContainer; + if (enabledSubstitutions & 4 && isSuperContainer(node)) { + currentSuperContainer = node; + } + if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2; + } + if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8; + } + previousOnEmitNode(node, emit); + applicableSubstitutions = savedApplicableSubstitutions; + currentSuperContainer = savedCurrentSuperContainer; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2) { + var name_29 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_29); + if (exportedName) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name_29, initializer, node); + } + return ts.createPropertyAssignment(name_29, exportedName, node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + } + if (enabledSubstitutions & 4) { + switch (node.kind) { + case 174: + return substituteCallExpression(node); + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1) { + if (resolver.getNodeCheckFlags(node) & 16777216) { + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; + if (classAlias) { + var clone_4 = ts.getSynthesizedClone(classAlias); + setSourceMapRange(clone_4, node); + setCommentRange(clone_4, node); + return clone_4; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + var container = resolver.getReferencedExportContainer(node, false); + if (container) { + var substitute = (applicableSubstitutions & 2 && container.kind === 225) || + (applicableSubstitutions & 8 && container.kind === 224); + if (substitute) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, node); + } + } + } + return undefined; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 95) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 95) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + } + } + ts.transformTypeScript = transformTypeScript; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES6Module(context) { + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 231: + return visitImportClause(node); + case 233: + case 232: + return visitNamedBindings(node); + case 234: + return visitImportSpecifier(node); + case 235: + return visitExportAssignment(node); + case 236: + return visitExportDeclaration(node); + case 237: + return visitNamedExports(node); + case 238: + return visitExportSpecifier(node); + } + return node; + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var original = ts.getOriginalNode(node); + return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, true); + if (node.exportClause === newExportClause) { + return node; + } + return newExportClause + ? ts.createExportDeclaration(undefined, undefined, newExportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); + if (node.elements === newExports) { + return node; + } + return newExports.length ? ts.createNamedExports(newExports) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + function visitImportEqualsDeclaration(node) { + return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitImportDeclaration(node) { + if (node.importClause) { + var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); + if (!newImportClause.name && !newImportClause.namedBindings) { + return undefined; + } + else if (newImportClause !== node.importClause) { + return ts.createImportDeclaration(undefined, undefined, newImportClause, node.moduleSpecifier); + } + } + return node; + } + function visitImportClause(node) { + var newDefaultImport = node.name; + if (!resolver.isReferencedAliasDeclaration(node)) { + newDefaultImport = undefined; + } + var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true); + return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings + ? ts.createImportClause(newDefaultImport, newNamedBindings) + : node; + } + function visitNamedBindings(node) { + if (node.kind === 232) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); + if (!newNamedImportElements || newNamedImportElements.length == 0) { + return undefined; + } + if (newNamedImportElements === node.elements) { + return node; + } + return ts.createNamedImports(newNamedImportElements); + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + } + ts.transformES6Module = transformES6Module; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformSystemModule(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69); + context.enableSubstitution(187); + context.enableSubstitution(185); + context.enableSubstitution(186); + context.enableEmitNotification(256); + var exportFunctionForFileMap = []; + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var hasExportStarsToExportValues; + var exportFunctionForFile; + var contextObjectForFile; + var exportedLocalNames; + var exportedFunctionDeclarations; + var enclosingBlockScopedContainer; + var currentParent; + var currentNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + currentNode = node; + var updated = transformSystemModuleWorker(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + exportedLocalNames = undefined; + exportedFunctionDeclarations = undefined; + return updated; + } + return node; + } + function transformSystemModuleWorker(node) { + ts.Debug.assert(!exportFunctionForFile); + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + exportFunctionForFile = ts.createUniqueName("exports"); + contextObjectForFile = ts.createUniqueName("context"); + exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; + var dependencyGroups = collectDependencyGroups(externalImports); + var statements = []; + addSystemModuleBody(statements, node, dependencyGroups); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); + var body = ts.createFunctionExpression(undefined, undefined, undefined, [ + ts.createParameter(exportFunctionForFile), + ts.createParameter(contextObjectForFile) + ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ? [moduleName, dependencies, body] + : [dependencies, body])) + ], ~1 & getNodeEmitFlags(node)); + var _a; + } + function addSystemModuleBody(statements, node, dependencyGroups) { + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitSourceElement); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) + ]))); + var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); + ts.addRange(statements, endLexicalEnvironment()); + ts.addRange(statements, exportedFunctionDeclarations); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) + ]), true))); + } + function addExportStarIfNeeded(statements) { + if (!hasExportStarsToExportValues) { + return; + } + if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + if (externalImport.kind === 236 && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + return addExportStarFunction(statements, undefined); + } + } + var exportedNames = []; + if (exportedLocalNames) { + for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { + var exportedLocalName = exportedLocalNames_1[_a]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); + } + } + for (var _b = 0, externalImports_2 = externalImports; _b < externalImports_2.length; _b++) { + var externalImport = externalImports_2[_b]; + if (externalImport.kind !== 236) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + continue; + } + for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { + var element = _d[_c]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) + ]))); + return addExportStarFunction(statements, exportedNamesStorageRef); + } + function generateSetters(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 230: + if (!entry.importClause) { + break; + } + case 229: + ts.Debug.assert(importVariableName !== undefined); + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 236: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); + } + else { + statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, ts.createBlock(statements, undefined, true))); + } + return ts.createArrayLiteral(setters, undefined, true); + } + function visitSourceElement(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 236: + return visitExportDeclaration(node); + case 235: + return visitExportAssignment(node); + default: + return visitNestedNode(node); + } + } + function visitNestedNode(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var currentGrandparent = currentParent; + currentParent = currentNode; + currentNode = node; + if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { + enclosingBlockScopedContainer = currentParent; + } + var result = visitNestedNodeWorker(node); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return result; + } + function visitNestedNodeWorker(node) { + switch (node.kind) { + case 200: + return visitVariableStatement(node); + case 220: + return visitFunctionDeclaration(node); + case 221: + return visitClassDeclaration(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 208: + return visitForOfStatement(node); + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 214: + return visitLabeledStatement(node); + case 212: + return visitWithStatement(node); + case 213: + return visitSwitchStatement(node); + case 227: + return visitCaseBlock(node); + case 249: + return visitCaseClause(node); + case 250: + return visitDefaultClause(node); + case 216: + return visitTryStatement(node); + case 252: + return visitCatchClause(node); + case 199: + return visitBlock(node); + case 202: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (node.importClause && ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitImportEqualsDeclaration(node) { + if (ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + var statements = []; + ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); + return statements; + } + return undefined; + } + function visitExportSpecifier(specifier) { + if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) + || resolver.isValueAliasDeclaration(specifier)) { + recordExportName(specifier.name); + return createExportStatement(specifier.name, specifier.propertyName || specifier.name); + } + return undefined; + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + return createExportStatement(ts.createLiteral("default"), node.expression); + } + } + return undefined; + } + function visitVariableStatement(node) { + var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3) == 0) || + enclosingBlockScopedContainer.kind === 256; + if (!shouldHoist) { + return node; + } + var isExported = ts.hasModifier(node, 1); + var expressions = []; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, isExported); + if (visited) { + expressions.push(visited); + } + } + if (expressions.length) { + return ts.createStatement(ts.inlineExpressions(expressions), node); + } + return undefined; + } + function transformVariable(node, isExported) { + hoistBindingElement(node, isExported); + if (!node.initializer) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + return ts.createAssignment(name, node.initializer); + } + else { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); + } + } + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1)) { + var name_30 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_30, undefined, node.parameters, undefined, node.body, node); + recordExportedFunctionDeclaration(node); + if (!ts.hasModifier(node, 512)) { + recordExportName(name_30); + } + ts.setOriginalNode(newNode, node); + node = newNode; + } + hoistFunctionDeclaration(node); + return undefined; + } + function visitExpressionStatement(node) { + var originalNode = ts.getOriginalNode(node); + if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { + var name_31 = getDeclarationName(originalNode); + if (originalNode.kind === 224) { + hoistVariableDeclaration(name_31); + } + return [ + node, + createExportStatement(name_31, name_31) + ]; + } + return node; + } + function visitClassDeclaration(node) { + var name = getDeclarationName(node); + hoistVariableDeclaration(name); + var statements = []; + statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, node.heritageClauses, node.members, node)), node)); + if (ts.hasModifier(node, 1)) { + if (!ts.hasModifier(node, 512)) { + recordExportName(name); + } + statements.push(createDeclarationExport(node)); + } + return statements; + } + function shouldHoistLoopInitializer(node) { + return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3) === 0; + } + function visitForStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var expressions = []; + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, false); + if (visited) { + expressions.push(visited); + } + } + ; + return ts.createFor(expressions.length + ? ts.inlineExpressions(expressions) + : ts.createSynthesizedNode(193), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), node); + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function transformForBinding(node) { + var firstDeclaration = ts.firstOrUndefined(node.declarations); + hoistBindingElement(firstDeclaration, false); + var name = firstDeclaration.name; + return ts.isIdentifier(name) + ? name + : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); + } + function visitForInStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function visitForOfStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function visitDoStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitWhileStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitLabeledStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitWithStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitSwitchStatement(node) { + var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); + if (caseBlock !== node.caseBlock) { + var updated = ts.getMutableClone(node); + updated.caseBlock = caseBlock; + return updated; + } + return node; + } + function visitCaseBlock(node) { + var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); + if (clauses !== node.clauses) { + var updated = ts.getMutableClone(node); + updated.clauses = clauses; + return updated; + } + return node; + } + function visitCaseClause(node) { + var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); + if (statements !== node.statements) { + var updated = ts.getMutableClone(node); + updated.statements = statements; + return updated; + } + return node; + } + function visitDefaultClause(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function visitTryStatement(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function visitCatchClause(node) { + var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); + if (block !== node.block) { + var updated = ts.getMutableClone(node); + updated.block = block; + return updated; + } + return node; + } + function visitBlock(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function onEmitNode(node, emit) { + if (node.kind === 256) { + exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + exportFunctionForFile = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 187: + return substituteBinaryExpression(node); + case 185: + case 186: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + var importBinding = createImportBinding(importDeclaration); + if (importBinding) { + return importBinding; + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return substituteAssignmentExpression(node); + } + return node; + } + function substituteAssignmentExpression(node) { + setNodeEmitFlags(node, 128); + var left = node.left; + switch (left.kind) { + case 69: + var exportDeclaration = resolver.getReferencedExportContainer(left); + if (exportDeclaration) { + return createExportExpression(left, node); + } + break; + case 171: + case 170: + if (hasExportedReferenceInDestructuringPattern(left)) { + return substituteDestructuring(node); + } + break; + } + return node; + } + function isExportedBinding(name) { + var container = resolver.getReferencedExportContainer(name); + return container && container.kind === 256; + } + function hasExportedReferenceInDestructuringPattern(node) { + switch (node.kind) { + case 69: + return isExportedBinding(node); + case 171: + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (hasExportedReferenceInObjectDestructuringElement(property)) { + return true; + } + } + break; + case 170: + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (hasExportedReferenceInArrayDestructuringElement(element)) { + return true; + } + } + break; + } + return false; + } + function hasExportedReferenceInObjectDestructuringElement(node) { + if (ts.isShorthandPropertyAssignment(node)) { + return isExportedBinding(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringElement(node.initializer); + } + else { + return false; + } + } + function hasExportedReferenceInArrayDestructuringElement(node) { + if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else { + return hasExportedReferenceInDestructuringElement(node); + } + } + function hasExportedReferenceInDestructuringElement(node) { + if (ts.isBinaryExpression(node)) { + var left = node.left; + return node.operatorToken.kind === 56 + && isDestructuringPattern(left) + && hasExportedReferenceInDestructuringPattern(left); + } + else if (ts.isIdentifier(node)) { + return isExportedBinding(node); + } + else if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else if (isDestructuringPattern(node)) { + return hasExportedReferenceInDestructuringPattern(node); + } + else { + return false; + } + } + function isDestructuringPattern(node) { + var kind = node.kind; + return kind === 69 + || kind === 171 + || kind === 170; + } + function substituteDestructuring(node) { + return ts.flattenDestructuringAssignment(context, node, true, hoistVariableDeclaration); + } + function substituteUnaryExpression(node) { + var operand = node.operand; + var operator = node.operator; + var substitute = ts.isIdentifier(operand) && + (node.kind === 186 || + (node.kind === 185 && (operator === 41 || operator === 42))); + if (substitute) { + var exportDeclaration = resolver.getReferencedExportContainer(operand); + if (exportDeclaration) { + var expr = ts.createPrefix(node.operator, operand, node); + setNodeEmitFlags(expr, 128); + var call = createExportExpression(operand, expr); + if (node.kind === 185) { + return call; + } + else { + return operator === 41 + ? ts.createSubtract(call, ts.createLiteral(1)) + : ts.createAdd(call, ts.createLiteral(1)); + } + } + } + return node; + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function addExportStarFunction(statements, localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); + } + statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(m)], undefined, ts.createBlock([ + ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, undefined) + ]), m, ts.createBlock([ + setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ])), + ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) + ], undefined, true))); + return exportStarFunction; + } + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; + return ts.createCall(exportFunctionForFile, undefined, [exportName, value]); + } + function createExportStatement(name, value) { + return ts.createStatement(createExportExpression(name, value)); + } + function createDeclarationExport(node) { + var declarationName = getDeclarationName(node); + var exportName = ts.hasModifier(node, 512) ? ts.createLiteral("default") : declarationName; + return createExportStatement(exportName, declarationName); + } + function createImportBinding(importDeclaration) { + var importAlias; + var name; + if (ts.isImportClause(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); + name = ts.createIdentifier("default"); + } + else if (ts.isImportSpecifier(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); + name = importDeclaration.propertyName || importDeclaration.name; + } + else { + return undefined; + } + if (name.originalKeywordKind && languageVersion === 0) { + return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); + } + else { + return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); + } + } + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + continue; + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + function getNameOfDependencyGroup(dependencyGroup) { + return dependencyGroup.name; + } + function recordExportName(name) { + if (!exportedLocalNames) { + exportedLocalNames = []; + } + exportedLocalNames.push(name); + } + function recordExportedFunctionDeclaration(node) { + if (!exportedFunctionDeclarations) { + exportedFunctionDeclarations = []; + } + exportedFunctionDeclarations.push(createDeclarationExport(node)); + } + function hoistBindingElement(node, isExported) { + if (ts.isOmittedExpression(node)) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + if (isExported) { + recordExportName(name); + } + } + else if (ts.isBindingPattern(name)) { + ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + } + } + function hoistExportedBindingElement(node) { + hoistBindingElement(node, true); + } + function hoistNonExportedBindingElement(node) { + hoistBindingElement(node, false); + } + function updateSourceFile(node, statements, nodeEmitFlags) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + setNodeEmitFlags(updated, nodeEmitFlags); + return updated; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a + )); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69); + context.enableSubstitution(187); + context.enableSubstitution(185); + context.enableSubstitution(186); + context.enableSubstitution(254); + context.enableEmitNotification(256); + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var bindingNameExportSpecifiersMap; + var bindingNameExportSpecifiersForFileMap = ts.createMap(); + var hasExportStarsToExportValues; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule_1(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + return updated; + } + return node; + var _a; + } + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, false); + var updated = updateSourceFile(node, statements); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + } + return updated; + } + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, true); + } + function transformUMDModule(node) { + var define = ts.createIdentifier("define"); + setNodeEmitFlags(define, 16); + return transformAsynchronousModule(node, define, undefined, false); + } + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createFunctionExpression(undefined, undefined, undefined, [ + ts.createParameter("require"), + ts.createParameter("exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + ]))) + ]); + } + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, true); + var body = ts.createBlock(statements, undefined, true); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(body, 2); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (emitAsReturn) { + var statement = ts.createReturn(exportEquals.expression, exportEquals); + setNodeEmitFlags(statement, 12288 | 49152); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); + setNodeEmitFlags(statement, 49152); + statements.push(statement); + } + } + } + function visitor(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 236: + return visitExportDeclaration(node); + case 235: + return visitExportAssignment(node); + case 200: + return visitVariableStatement(node); + case 220: + return visitFunctionDeclaration(node); + case 221: + return visitClassDeclaration(node); + case 202: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var statements = []; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + statements.push(ts.createStatement(createRequireCall(node), node)); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + } + else { + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); + } + } + statements.push(ts.createVariableStatement(undefined, ts.createConstDeclarationList(variables), node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node), node) + ]))); + } + addExportImportAssignments(statements, node); + return ts.singleOrMany(statements); + } + function visitImportEqualsDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + setNodeEmitFlags(node.name, 128); + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1)) { + statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), node)); + } + else { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) + ], undefined, languageVersion >= 2 ? 2 : 0), node)); + } + } + else { + if (ts.hasModifier(node, 1)) { + statements.push(ts.createStatement(createExportAssignment(node.name, node.name), node)); + } + } + addExportImportAssignments(statements, node); + return statements; + } + function visitExportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) + ]), node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + if (resolver.isValueAliasDeclaration(specifier)) { + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), specifier)); + } + } + return ts.singleOrMany(statements); + } + else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), node); + } + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + var statements = []; + addExportDefault(statements, node.expression, node); + return statements; + } + } + return undefined; + } + function addExportDefault(statements, expression, location) { + tryAddExportDefaultCompat(statements); + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); + } + function tryAddExportDefaultCompat(statements) { + var original = ts.getOriginalNode(currentSourceFile); + ts.Debug.assert(original.kind === 256); + if (!original.symbol.exports["___esModule"]) { + if (languageVersion === 0) { + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + function addExportImportAssignments(statements, node) { + if (ts.isImportEqualsDeclaration(node)) { + addExportMemberAssignments(statements, node.name); + } + else { + var names = ts.reduceEachChild(node, collectExportMembers, []); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_32 = names_1[_i]; + addExportMemberAssignments(statements, name_32); + } + } + } + function collectExportMembers(names, node) { + if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { + var name_33 = node.name; + if (ts.isIdentifier(name_33)) { + names.push(name_33); + } + } + return ts.reduceEachChild(node, collectExportMembers, names); + } + function addExportMemberAssignments(statements, name) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), specifier.name))); + } + } + } + function addExportMemberAssignment(statements, node) { + if (ts.hasModifier(node, 512)) { + addExportDefault(statements, getDeclarationName(node), node); + } + else { + statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + } + } + function visitVariableStatement(node) { + var originalKind = ts.getOriginalNode(node).kind; + if (originalKind === 225 || + originalKind === 224 || + originalKind === 221) { + if (!ts.hasModifier(node, 1)) { + return node; + } + return ts.setOriginalNode(ts.createVariableStatement(undefined, node.declarationList), node); + } + var resultStatements = []; + if (ts.hasModifier(node, 1)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length > 0) { + var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + resultStatements.push(inlineAssignments); + } + } + else { + resultStatements.push(node); + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + addExportMemberAssignmentsForBindingName(resultStatements, decl.name); + } + return resultStatements; + } + function addExportMemberAssignmentsForBindingName(resultStatements, name) { + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + addExportMemberAssignmentsForBindingName(resultStatements, element.name); + } + } + } + else { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + var sourceFileId = ts.getOriginalNodeId(currentSourceFile); + if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { + bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); + } + bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; + addExportMemberAssignments(resultStatements, name); + } + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); + } + else { + return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + } + function visitFunctionDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1)) { + statements.push(ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name, undefined, node.parameters, undefined, node.body, node), node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitClassDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1)) { + statements.push(ts.setOriginalNode(ts.createClassDeclaration(undefined, undefined, name, undefined, node.heritageClauses, node.members, node), node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name && !(node.decorators && node.decorators.length)) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitExpressionStatement(node) { + var original = ts.getOriginalNode(node); + var origKind = original.kind; + if (origKind === 224 || origKind === 225) { + return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); + } + else if (origKind === 221) { + var classDecl = original; + if (classDecl.name) { + var statements = [node]; + addExportMemberAssignments(statements, classDecl.name); + return statements; + } + } + return node; + } + function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { + var statements = [node]; + if (ts.hasModifier(original, 1) && + original.kind === 224 && + ts.isFirstDeclarationOfKind(original, 224)) { + addVarForExportedEnumOrNamespaceDeclaration(statements, original); + } + addExportMemberAssignments(statements, original.name); + return statements; + } + function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { + var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); + setNodeEmitFlags(transformedStatement, 49152); + statements.push(transformedStatement); + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function onEmitNode(node, emit) { + if (node.kind === 256) { + bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + bindingNameExportSpecifiersMap = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 187: + return substituteBinaryExpression(node); + case 186: + case 185: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteExportedName(node) + || trySubstituteImportedName(node) + || node; + } + function substituteBinaryExpression(node) { + var left = node.left; + if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { + setNodeEmitFlags(node, 128); + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, node); + } + return nestedExportAssignment; + } + } + return node; + } + function substituteUnaryExpression(node) { + var operator = node.operator; + var operand = node.operand; + if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { + setNodeEmitFlags(node, 128); + var transformedUnaryExpression = void 0; + if (node.kind === 186) { + transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + setNodeEmitFlags(transformedUnaryExpression, 128); + } + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, transformedUnaryExpression || node); + } + return nestedExportAssignment; + } + } + return node; + } + function trySubstituteExportedName(node) { + var emitFlags = getNodeEmitFlags(node); + if ((emitFlags & 262144) === 0) { + var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); + if (container) { + if (container.kind === 256) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); + } + } + } + return undefined; + } + function trySubstituteImportedName(node) { + if ((getNodeEmitFlags(node) & 262144) === 0) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (ts.isImportClause(declaration)) { + if (languageVersion >= 1) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), node); + } + else { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), node); + } + } + else if (ts.isImportSpecifier(declaration)) { + var name_34 = declaration.propertyName || declaration.name; + if (name_34.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), node); + } + else { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), node); + } + } + } + } + return undefined; + } + function getModuleMemberName(name) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), name, name); + } + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (ts.isDefined(moduleName)) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), undefined, args); + } + function createExportStatement(name, value, location) { + var statement = ts.createStatement(createExportAssignment(name, value)); + statement.startsOnNewLine = true; + if (location) { + setSourceMapRange(statement, location); + } + return statement; + } + function createExportAssignment(name, value) { + return ts.createAssignment(name.originalKeywordKind === 77 && languageVersion === 0 + ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) + : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + var aliasedModuleNames = []; + var unaliasedModuleNames = []; + var importAliasNames = []; + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { + var importNode = externalImports_3[_b]; + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + setNodeEmitFlags(importAliasName, 128); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function updateSourceFile(node, statements) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + return updated; + } + var _a; + } + ts.transformModule = transformModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + var entities = createEntitiesMap(); + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + return node; + } + function visitor(node) { + if (node.transformFlags & 4) { + return visitorWorker(node); + } + else if (node.transformFlags & 8) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 241: + return visitJsxElement(node, false); + case 242: + return visitJsxSelfClosingElement(node, false); + case 248: + return visitJsxExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 244: + return visitJsxText(node); + case 248: + return visitJsxExpression(node); + case 241: + return visitJsxElement(node, true); + case 242: + return visitJsxSelfClosingElement(node, true); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, undefined, isChild, node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes; + if (attrs.length === 0) { + objectProperties = ts.createNull(); + } + else { + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + segments.unshift(ts.createObjectLiteral()); + } + objectProperties = ts.singleOrUndefined(segments) + || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + } + var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createLiteral(true); + } + else if (node.kind === 9) { + var decoded = tryDecodeEntities(node.text); + return decoded ? ts.createLiteral(decoded, node) : node; + } + else if (node.kind === 248) { + return visitJsxExpression(node); + } + else { + ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var text = ts.getTextOfNode(node, true); + var parts; + var firstNonWhitespace = 0; + var lastNonWhitespace = -1; + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { + var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + if (!parts) { + parts = []; + } + parts.push(ts.createLiteral(decodeEntities(part))); + } + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpace(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + if (firstNonWhitespace !== -1) { + var part = text.substr(firstNonWhitespace); + if (!parts) { + parts = []; + } + parts.push(ts.createLiteral(decodeEntities(part))); + } + if (parts) { + return ts.reduceLeft(parts, aggregateJsxTextParts); + } + return undefined; + } + function aggregateJsxTextParts(left, right) { + return ts.createAdd(ts.createAdd(left, ts.createLiteral(" ")), right); + } + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities[word]; + return ch ? String.fromCharCode(ch) : match; + } + }); + } + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 241) { + return getTagName(node.openingElement); + } + else { + var name_35 = node.tagName; + if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { + return ts.createLiteral(name_35.text); + } + else { + return ts.createExpressionFromEntityName(name_35); + } + } + } + function getAttributeName(node) { + var name = node.name; + if (/^[A-Za-z_]\w*$/.test(name.text)) { + return name; + } + else { + return ts.createLiteral(name.text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + function createEntitiesMap() { + return ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES7(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if (node.transformFlags & 16) { + return visitorWorker(node); + } + else if (node.transformFlags & 32) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 187: + return visitBinaryExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (node.operatorToken.kind === 60) { + var target = void 0; + var value = void 0; + if (ts.isElementAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); + } + else if (ts.isPropertyAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); + value = ts.createPropertyAccess(expressionTemp, left.name, left); + } + else { + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, node), node); + } + else if (node.operatorToken.kind === 38) { + return ts.createMathPow(left, right, node); + } + else { + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + } + ts.transformES7 = transformES7; +})(ts || (ts = {})); +var ts; +(function (ts) { + var instructionNames = ts.createMap((_a = {}, + _a[2] = "return", + _a[3] = "break", + _a[4] = "yield", + _a[5] = "yield*", + _a[7] = "endfinally", + _a + )); + function transformGenerators(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + var blocks; + var blockOffsets; + var blockActions; + var blockStack; + var labelOffsets; + var labelExpressions; + var nextLabelId = 1; + var operations; + var operationArguments; + var operationLocations; + var state; + var blockIndex = 0; + var labelNumber = 0; + var labelNumbers; + var lastOperationWasAbrupt; + var lastOperationWasCompletion; + var clauses; + var statements; + var exceptionBlockStack; + var currentExceptionBlock; + var withBlockStack; + return transformSourceFile; + function transformSourceFile(node) { + if (node.transformFlags & 1024) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + } + return node; + } + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 512) { + return visitGenerator(node); + } + else if (transformFlags & 1024) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 213: + return visitSwitchStatement(node); + case 214: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + case 149: + case 150: + return visitAccessorDeclaration(node); + case 200: + return visitVariableStatement(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 210: + return visitBreakStatement(node); + case 209: + return visitContinueStatement(node); + case 211: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (1024 | 8388608)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 187: + return visitBinaryExpression(node); + case 188: + return visitConditionalExpression(node); + case 190: + return visitYieldExpression(node); + case 170: + return visitArrayLiteralExpression(node); + case 171: + return visitObjectLiteralExpression(node); + case 173: + return visitElementAccessExpression(node); + case 174: + return visitCallExpression(node); + case 175: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitGenerator(node) { + switch (node.kind) { + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitFunctionDeclaration(node) { + if (node.asteriskToken && node.emitFlags & 2097152) { + node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + function visitFunctionExpression(node) { + if (node.asteriskToken && node.emitFlags & 2097152) { + node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + function transformGeneratorFunctionBody(body) { + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(undefined); + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addRange(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.createBlock(statements, body, body.multiLine); + } + function visitVariableStatement(node) { + if (node.transformFlags & 4194304) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + if (node.emitFlags & 8388608) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + } + } + function visitBinaryExpression(node) { + switch (ts.getExpressionAssociativity(node)) { + case 0: + return visitLeftAssociativeBinaryExpression(node); + case 1: + return visitRightAssociativeBinaryExpression(node); + default: + ts.Debug.fail("Unknown associativity."); + } + } + function isCompoundAssignment(kind) { + return kind >= 57 + && kind <= 68; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 57: return 35; + case 58: return 36; + case 59: return 37; + case 60: return 38; + case 61: return 39; + case 62: return 40; + case 63: return 43; + case 64: return 44; + case 65: return 45; + case 66: return 46; + case 67: return 47; + case 68: return 48; + } + } + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 172: + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 173: + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.createBinary(target, 56, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 24) { + return visitCommaExpression(node); + } + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + function visitLogicalBinaryExpression(node) { + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); + if (node.operatorToken.kind === 51) { + emitBreakWhenFalse(resultLabel, resultLocal, node.left); + } + else { + emitBreakWhenTrue(resultLabel, resultLocal, node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), node.right); + markLabel(resultLabel); + return resultLocal; + } + function visitCommaExpression(node) { + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + function visitConditionalExpression(node) { + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + emitYieldStar(expression, node); + } + else { + emitYield(expression, node); + } + markLabel(resumeLabel); + return createGeneratorResume(); + } + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, node.multiLine); + } + function visitElements(elements, multiLine) { + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp = declareLocal(); + var hasAssignedTemp = false; + if (numInitialElements > 0) { + emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + hasAssignedTemp = true; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions)); + hasAssignedTemp = true; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + visited.startsOnNewLine = true; + } + expressions.push(visited); + } + return expressions; + } + } + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, false), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, false)), undefined, [], node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 199: + return transformAndEmitBlock(node); + case 202: + return transformAndEmitExpressionStatement(node); + case 203: + return transformAndEmitIfStatement(node); + case 204: + return transformAndEmitDoStatement(node); + case 205: + return transformAndEmitWhileStatement(node); + case 206: + return transformAndEmitForStatement(node); + case 207: + return transformAndEmitForInStatement(node); + case 209: + return transformAndEmitContinueStatement(node); + case 210: + return transformAndEmitBreakStatement(node); + case 211: + return transformAndEmitReturnStatement(node); + case 212: + return transformAndEmitWithStatement(node); + case 213: + return transformAndEmitSwitchStatement(node); + case 214: + return transformAndEmitLabeledStatement(node); + case 215: + return transformAndEmitThrowStatement(node); + case 216: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement, true)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression, true), ts.visitNode(node.incrementor, visitor, ts.isExpression, true), ts.visitNode(node.statement, visitor, ts.isStatement, false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + if (containsYield(node)) { + var keysArray = declareLocal(); + var key = declareLocal(); + var keysIndex = ts.createLoopVariable(); + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); + emitBreak(label, node); + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); + emitBreak(label, node); + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression, true), node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression, true), node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 250 && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 249) { + var caseClause = clause; + if (containsYield(caseClause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(caseClause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], caseClause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + beginLabeledBlock(node.label.text); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(node.label.text); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return node && (node.transformFlags & 4194304) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (renamedCatchVariables && ts.hasProperty(renamedCatchVariables, node.text)) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_36) { + var clone_7 = ts.getMutableClone(name_36); + setSourceMapRange(clone_7, node); + setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node)) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(undefined); + hoistVariableDeclaration(temp); + return temp; + } + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + function endBlock() { + var block = peekBlock(); + ts.Debug.assert(block !== undefined, "beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1); + var block = endBlock(); + markLabel(block.endLabel); + } + function isWithBlock(block) { + return block.kind === 1; + } + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0, + state: 0, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0); + var text = variable.name.text; + var name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = ts.createMap(); + context.enableSubstitution(69); + } + renamedCatchVariables[text] = true; + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [])); + emitNop(); + } + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2; + exception.finallyLabel = finallyLabel; + } + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = endBlock(); + var state = exception.state; + if (state < 2) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3; + } + function isExceptionBlock(block) { + return block.kind === 0; + } + function beginScriptLoopBlock() { + beginBlock({ + kind: 3, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel + }); + return breakLabel; + } + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2, + isScript: true, + breakLabel: -1 + }); + } + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2, + isScript: false, + breakLabel: breakLabel + }); + return breakLabel; + } + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + function supportsUnlabeledBreak(block) { + return block.kind === 2 + || block.kind === 3; + } + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4; + } + function supportsUnlabeledContinue(block) { + return block.kind === 3; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + function findBreakTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + return 0; + } + function findContinueTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + return 0; + } + function createLabel(label) { + if (label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createSynthesizedNode(8); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createNode(193); + } + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + literal.trailingComment = instructionNames[instruction]; + return literal; + } + function createInlineBreak(label, location) { + ts.Debug.assert(label > 0, "Invalid label: " + label); + return ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), location); + } + function createInlineReturn(expression, location) { + return ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)]), location); + } + function createGeneratorResume(location) { + return ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [], location); + } + function emitNop() { + emitWorker(0); + } + function emitStatement(node) { + if (node) { + emitWorker(1, [node]); + } + else { + emitNop(); + } + } + function emitAssignment(left, right, location) { + emitWorker(2, [left, right], location); + } + function emitBreak(label, location) { + emitWorker(3, [label], location); + } + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4, [label, condition], location); + } + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5, [label, condition], location); + } + function emitYieldStar(expression, location) { + emitWorker(7, [expression], location); + } + function emitYield(expression, location) { + emitWorker(6, [expression], location); + } + function emitReturn(expression, location) { + emitWorker(8, [expression], location); + } + function emitThrow(expression, location) { + emitWorker(9, [expression], location); + } + function emitEndfinally() { + emitWorker(10); + } + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ + ts.createThis(), + setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ]); + } + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + switchStatement.startsOnNewLine = true; + return [switchStatement]; + } + if (statements) { + return statements; + } + return []; + } + function flushLabel() { + if (!statements) { + return; + } + appendLabel(!lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(undefined, undefined); + } + if (statements && clauses) { + appendLabel(false); + } + updateLabelExpressions(); + } + function isFinalLabelReachable(operationIndex) { + if (!lastOperationWasCompletion) { + return true; + } + if (!labelOffsets || !labelExpressions) { + return false; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + if (isExceptionBlock(block)) { + if (blockAction === 0) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + } + else if (isWithBlock(block)) { + if (blockAction === 0) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1) { + withBlockStack.pop(); + } + } + } + } + } + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0) { + return; + } + else if (opcode === 10) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2: + return writeAssign(args[0], args[1], location); + case 3: + return writeBreak(args[0], location); + case 4: + return writeBreakWhenTrue(args[0], args[1], location); + case 5: + return writeBreakWhenFalse(args[0], args[1], location); + case 6: + return writeYield(args[0], location); + case 7: + return writeYieldStar(args[0], location); + case 8: + return writeReturn(args[0], location); + case 9: + return writeThrow(args[0], location); + } + } + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + function writeAssign(left, right, operationLocation) { + writeStatement(ts.createStatement(ts.createAssignment(left, right), operationLocation)); + } + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createThrow(expression, operationLocation)); + } + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)]), operationLocation)); + } + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation)); + } + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.createIf(condition, ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation))); + } + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.createIf(ts.createLogicalNot(condition), ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation))); + } + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4), expression] + : [createInstruction(4)]), operationLocation)); + } + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5), + expression + ]), operationLocation)); + } + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7) + ]))); + } + } + ts.transformGenerators = transformGenerators; + var _a; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES6(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + var convertedLoopState; + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64) !== 0 || + node.kind === 214 || + (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { + switch (node.kind) { + case 211: + return visitReturnStatement(node); + case 200: + return visitVariableStatement(node); + case 213: + return visitSwitchStatement(node); + case 210: + case 209: + return visitBreakOrContinueStatement(node); + case 97: + return visitThisKeyword(node); + case 69: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 82: + return node; + case 221: + return visitClassDeclaration(node); + case 192: + return visitClassExpression(node); + case 142: + return visitParameter(node); + case 220: + return visitFunctionDeclaration(node); + case 180: + return visitArrowFunction(node); + case 179: + return visitFunctionExpression(node); + case 218: + return visitVariableDeclaration(node); + case 69: + return visitIdentifier(node); + case 219: + return visitVariableDeclarationList(node); + case 214: + return visitLabeledStatement(node); + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 208: + return visitForOfStatement(node); + case 202: + return visitExpressionStatement(node); + case 171: + return visitObjectLiteralExpression(node); + case 254: + return visitShorthandPropertyAssignment(node); + case 170: + return visitArrayLiteralExpression(node); + case 174: + return visitCallExpression(node); + case 175: + return visitNewExpression(node); + case 178: + return visitParenthesizedExpression(node, true); + case 187: + return visitBinaryExpression(node, true); + case 11: + case 12: + case 13: + case 14: + return visitTemplateLiteral(node); + case 176: + return visitTaggedTemplateExpression(node); + case 189: + return visitTemplateExpression(node); + case 190: + return visitYieldExpression(node); + case 95: + return visitSuperKeyword(node); + case 190: + return ts.visitEachChild(node, visitor, context); + case 147: + return visitMethodDeclaration(node); + case 256: + return visitSourceFileNode(node); + case 200: + return visitVariableStatement(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 180) { + enclosingNonArrowFunction = currentNode; + if (!(currentNode.emitFlags & 2097152)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + switch (currentNode.kind) { + case 200: + enclosingVariableStatement = currentNode; + break; + case 219: + case 218: + case 169: + case 167: + case 168: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps |= 2; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 180) { + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + var jump = node.kind === 210 ? 2 : 4; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 210) { + convertedLoopState.nonLocalJumps |= 2; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4; + labelMarker = "continue"; + } + } + else { + if (node.kind === 210) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 24, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 24, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitClassDeclaration(node) { + var modifierFlags = ts.getModifierFlags(node); + var isExported = modifierFlags & 1; + var isDefault = modifierFlags & 512; + var modifiers = isExported && !isDefault + ? ts.filter(node.modifiers, isExportModifier) + : undefined; + var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(getDeclarationName(node, true), undefined, transformClassLikeDeclarationToExpression(node)) + ]), node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + if (isExported && isDefault) { + var statements = [statement]; + statements.push(ts.createExportAssignment(undefined, undefined, false, getDeclarationName(node, false))); + return statements; + } + return statement; + } + function isExportModifier(node) { + return node.kind === 82; + } + function visitClassExpression(node) { + return transformClassLikeDeclarationToExpression(node); + } + function transformClassLikeDeclarationToExpression(node) { + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); + if (getNodeEmitFlags(node) & 524288) { + setNodeEmitFlags(classFunction, 524288); + } + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + setNodeEmitFlags(inner, 49152); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + setNodeEmitFlags(outer, 49152); + return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16); + var localName = getLocalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + setNodeEmitFlags(outer, 49152); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + setNodeEmitFlags(statement, 49152 | 12288); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); + setNodeEmitFlags(block, 49152); + return block; + } + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), extendsClauseElement)); + } + } + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + } + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + if (constructor && !hasSynthesizedSuper) { + return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); + } + return []; + } + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + startLexicalEnvironment(); + if (constructor) { + addCaptureThisForNodeIfNeeded(statements, constructor); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + } + addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); + if (constructor) { + var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + ts.addRange(statements, body); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); + if (!constructor) { + setNodeEmitFlags(block, 49152); + } + return block; + } + function transformConstructorBodyWithSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); + } + function transformConstructorBodyWithoutSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + } + function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { + if (constructor ? hasSynthesizedSuper : extendsClauseElement) { + statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + } + } + function visitParameter(node) { + if (node.dotDotDotToken) { + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), undefined, node), node); + } + else if (node.initializer) { + return ts.setOriginalNode(ts.createParameter(node.name, undefined, node), node); + } + else { + return node; + } + } + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536) !== 0; + } + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_37)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + } + } + } + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + if (name.elements.length > 0) { + statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + } + else if (initializer) { + statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + } + } + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + ], parameter), 32 | 1024 | 12288), undefined, parameter); + statement.startsOnNewLine = true; + setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + statements.push(statement); + } + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 69 && !inConstructorWithSynthesizedSuper; + } + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + var declarationName = ts.getMutableClone(parameter.name); + setNodeEmitFlags(declarationName, 1536); + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) + ]), parameter), 8388608)); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) + ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) + ])); + setNodeEmitFlags(forStatement, 8388608); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 && node.kind !== 180) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, ts.createThis()) + ])); + setNodeEmitFlags(captureThisStatement, 49152 | 8388608); + setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + } + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 198: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 147: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 149: + case 150: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 148: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(member); + } + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = getCommentRange(member); + var sourceMapRange = getSourceMapRange(member); + var func = transformFunctionLikeToExpression(member, member, undefined); + setNodeEmitFlags(func, 49152); + setSourceMapRange(func, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); + ts.setOriginalNode(statement, member); + setCommentRange(statement, commentRange); + setNodeEmitFlags(statement, 1536); + return statement; + } + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); + setNodeEmitFlags(statement, 49152); + return statement; + } + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var target = ts.getMutableClone(receiver); + setNodeEmitFlags(target, 49152 | 1024); + setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + setNodeEmitFlags(propertyName, 49152 | 512); + setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); + setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + var getter = ts.createPropertyAssignment("get", getterFunction); + setCommentRange(getter, getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); + setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + var setter = ts.createPropertyAssignment("set", setterFunction); + setCommentRange(setter, getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, undefined, true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + function visitArrowFunction(node) { + if (node.transformFlags & 8192) { + enableSubstitutionsForCapturedThis(); + } + var func = transformFunctionLikeToExpression(node, node, undefined); + setNodeEmitFlags(func, 256); + return func; + } + function visitFunctionExpression(node) { + return transformFunctionLikeToExpression(node, node, node.name); + } + function visitFunctionDeclaration(node) { + return ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node), node); + } + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 180) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + function transformFunctionBody(node) { + var multiLine = false; + var singleLine = false; + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + startLexicalEnvironment(); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, false); + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 180); + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, body); + setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + statements.push(returnStatement); + closeBraceLocation = body; + } + var lexicalEnvironment = endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + setNodeEmitFlags(block, 32); + } + if (closeBraceLocation) { + setTokenSourceMapRange(block, 16, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitExpressionStatement(node) { + switch (node.expression.kind) { + case 178: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); + case 187: + return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParenthesizedExpression(node, needsDestructuringValue) { + if (needsDestructuringValue) { + switch (node.expression.kind) { + case 178: + return ts.createParen(visitParenthesizedExpression(node.expression, true), node); + case 187: + return ts.createParen(visitBinaryExpression(node.expression, true), node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitBinaryExpression(node, needsDestructuringValue) { + ts.Debug.assert(ts.isDestructuringAssignment(node)); + return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3) == 0) { + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); + } + else { + assignment = ts.createBinary(decl.name, 56, decl.initializer); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24, acc); }), node); + } + else { + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclarationList(node) { + if (node.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, node); + ts.setOriginalNode(declarationList, node); + setCommentRange(declarationList, node); + if (node.transformFlags & 2097152 + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + function shouldEmitExplicitInitializerForLetDeclaration(node) { + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072; + var isDeclaredInLoop = flags & 262144; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 207 + && enclosingBlockScopeContainer.kind !== 208 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, false))); + return emitExplicitInitializer; + } + function visitVariableDeclarationInLetDeclarationList(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_8 = ts.getMutableClone(node); + clone_8.initializer = ts.createVoidZero(); + return clone_8; + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name)) { + var recordTempVariablesInLine = !enclosingVariableStatement + || !ts.hasModifier(enclosingVariableStatement, 1); + return ts.flattenVariableDestructuring(context, node, undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 69 + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(undefined); + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); + var declarationList = ts.createVariableDeclarationList(declarations, initializer); + ts.setOriginalNode(declarationList, initializer); + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement(undefined, declarationList)); + } + else { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, ts.createElementAccess(rhsReference, counter)) + ], ts.moveRangePos(initializer, -1)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); + if (ts.isDestructuringAssignment(assignment)) { + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, false, hoistVariableDeclaration, visitor))); + } + else { + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); + setNodeEmitFlags(body, 1536 | 12288); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) + ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); + setNodeEmitFlags(forStatement, 8192); + return forStatement; + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var numProperties = properties.length; + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 4194304 + || property.name.kind === 140) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var expressions = []; + var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536) !== 0; + } + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 69) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 | 4; + } + var result = convert ? convert(node, undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 206: + case 207: + case 208: + var initializer = node.initializer; + if (initializer && initializer.kind === 219) { + loopInitializer = initializer; + } + break; + } + var loopParameters = []; + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + if (outerConvertedLoopState.argumentsName) { + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length) { + var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + copyOutParameters(loopOutParameters, 1, statements_3); + loopBody = ts.createBlock(statements_3, undefined, true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], undefined, true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (node.statement.transformFlags & 4194304) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 256; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 2097152; + } + var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ])); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + if (currentState.argumentsName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + if (outerConvertedLoopState) { + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var name_38 in currentState.hoistedLocalVariables) { + var identifier = currentState.hoistedLocalVariables[name_38]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { + var outParam = loopOutParameters_1[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + loop.statement = undefined; + loop = ts.visitEachChild(loop, visitor, context); + loop.statement = ts.createBlock(convertedLoopBodyStatements, undefined, true); + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 214 + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 56, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + var isSimpleLoop = !(state.nonLocalJumps & ~4) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0, statements); + if (state.nonLocalJumps & 8) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 32, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(name)); + if (resolver.getNodeCheckFlags(decl) & 2097152) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 149: + case 150: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 253: + expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 254: + expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 147: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined), method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function visitMethodDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); + setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, node); + } + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), node); + } + function visitYieldExpression(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitArrayLiteralExpression(node) { + return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); + } + function visitCallExpression(node) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.transformFlags & 262144) { + return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + } + else { + return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + } + } + function visitNewExpression(node) { + ts.Debug.assert((node.transformFlags & 262144) !== 0); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); + } + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpreadElement(node) { + return ts.isSpreadElementExpression(node) + ? visitSpanOfSpreadElements + : visitSpanOfNonSpreadElements; + } + function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.map(chunk, visitExpressionOfSpreadElement); + } + function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, undefined, hasTrailingComma), visitor, ts.isExpression), undefined, multiLine); + } + function visitExpressionOfSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, node); + } + function visitTaggedTemplateExpression(node) { + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, undefined, templateArguments) + ])); + } + function getRawLiteral(node) { + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + var isLast = node.kind === 11 || node.kind === 14; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, node); + } + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + function shouldAddTemplateHead(node) { + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + function visitSuperKeyword(node) { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32) + && currentParent.kind !== 174 + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + function visitSourceFileNode(node) { + var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, prologue); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); + ts.addRange(statements, endLexicalEnvironment()); + var clone = ts.getMutableClone(node); + clone.statements = ts.createNodeArray(statements, node.statements); + return clone; + } + function onEmitNode(node, emit) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { + enclosingFunction = node; + } + previousOnEmitNode(node, emit); + enclosingFunction = savedEnclosingFunction; + } + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(69); + } + } + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(97); + context.enableEmitNotification(148); + context.enableEmitNotification(147); + context.enableEmitNotification(149); + context.enableEmitNotification(150); + context.enableEmitNotification(180); + context.enableEmitNotification(179); + context.enableEmitNotification(220); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + function substituteIdentifier(node) { + if (enabledSubstitutions & 2) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 169: + case 221: + case 224: + case 218: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 97: + return substituteThisKeyword(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 + && enclosingFunction + && enclosingFunction.emitFlags & 256) { + return ts.createIdentifier("_this", node); + } + return node; + } + function getLocalName(node, allowComments, allowSourceMaps) { + return getDeclarationName(node, allowComments, allowSourceMaps, 262144); + } + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && !ts.isGeneratedIdentifier(node.name)) { + var name_39 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (!allowComments) { + emitFlags |= 49152; + } + if (emitFlags) { + setNodeEmitFlags(name_39, emitFlags); + } + return name_39; + } + return ts.getGeneratedNameForNode(node); + } + function getClassMemberPrefix(node, member) { + var expression = getLocalName(node); + return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + var parameter = ts.singleOrUndefined(constructor.parameters); + if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression === parameter.name; + } + } + ts.transformES6 = transformES6; +})(ts || (ts = {})); +var ts; +(function (ts) { + var moduleTransformerMap = ts.createMap((_a = {}, + _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.System] = ts.transformSystemModule, + _a[ts.ModuleKind.AMD] = ts.transformModule, + _a[ts.ModuleKind.CommonJS] = ts.transformModule, + _a[ts.ModuleKind.UMD] = ts.transformModule, + _a[ts.ModuleKind.None] = ts.transformModule, + _a + )); + function getTransformers(compilerOptions) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + transformers.push(ts.transformTypeScript); + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (jsx === 2) { + transformers.push(ts.transformJsx); + } + transformers.push(ts.transformES7); + if (languageVersion < 2) { + transformers.push(ts.transformES6); + transformers.push(ts.transformGenerators); + } + return transformers; + } + ts.getTransformers = getTransformers; + var nextTransformId = 1; + function transformFiles(resolver, host, sourceFiles, transformers) { + var transformId = nextTransformId; + nextTransformId++; + var tokenSourceMapRanges = ts.createMap(); + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var enabledSyntaxKindFeatures = new Array(289); + var parseTreeNodesWithAnnotations = []; + var lastTokenSourceMapRangeNode; + var lastTokenSourceMapRangeToken; + var lastTokenSourceMapRange; + var lexicalEnvironmentStackOffset = 0; + var hoistedVariableDeclarations; + var hoistedFunctionDeclarations; + var lexicalEnvironmentDisabled; + var context = { + getCompilerOptions: function () { return host.getCompilerOptions(); }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + getNodeEmitFlags: getNodeEmitFlags, + setNodeEmitFlags: setNodeEmitFlags, + getSourceMapRange: getSourceMapRange, + setSourceMapRange: setSourceMapRange, + getTokenSourceMapRange: getTokenSourceMapRange, + setTokenSourceMapRange: setTokenSourceMapRange, + getCommentRange: getCommentRange, + setCommentRange: setCommentRange, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + startLexicalEnvironment: startLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + onSubstituteNode: onSubstituteNode, + enableSubstitution: enableSubstitution, + isSubstitutionEnabled: isSubstitutionEnabled, + onEmitNode: onEmitNode, + enableEmitNotification: enableEmitNotification, + isEmitNotificationEnabled: isEmitNotificationEnabled + }; + var transformation = chain.apply(void 0, transformers)(context); + var transformed = ts.map(sourceFiles, transformSourceFile); + lexicalEnvironmentDisabled = true; + return { + getSourceFiles: function () { return transformed; }, + getTokenSourceMapRange: getTokenSourceMapRange, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + onSubstituteNode: context.onSubstituteNode, + onEmitNode: context.onEmitNode, + dispose: function () { + for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { + var node = parseTreeNodesWithAnnotations_1[_i]; + if (node.transformId === transformId) { + node.transformId = 0; + node.emitFlags = 0; + node.commentRange = undefined; + node.sourceMapRange = undefined; + } + } + parseTreeNodesWithAnnotations.length = 0; + } + }; + function transformSourceFile(sourceFile) { + if (ts.isDeclarationFile(sourceFile)) { + return sourceFile; + } + return transformation(sourceFile); + } + function enableSubstitution(kind) { + enabledSyntaxKindFeatures[kind] |= 1; + } + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + } + function onSubstituteNode(node, isExpression) { + return node; + } + function enableEmitNotification(kind) { + enabledSyntaxKindFeatures[kind] |= 2; + } + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 + || (getNodeEmitFlags(node) & 64) !== 0; + } + function onEmitNode(node, emit) { + emit(node); + } + function beforeSetAnnotation(node) { + if ((node.flags & 8) === 0 && node.transformId !== transformId) { + parseTreeNodesWithAnnotations.push(node); + node.transformId = transformId; + } + } + function getNodeEmitFlags(node) { + return node.emitFlags; + } + function setNodeEmitFlags(node, emitFlags) { + beforeSetAnnotation(node); + node.emitFlags = emitFlags; + return node; + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + function setSourceMapRange(node, range) { + beforeSetAnnotation(node); + node.sourceMapRange = range; + return node; + } + function getTokenSourceMapRange(node, token) { + if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { + return lastTokenSourceMapRange; + } + var range; + var current = node; + while (current) { + range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; + if (range !== undefined) { + break; + } + current = current.original; + } + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + return range; + } + function setTokenSourceMapRange(node, token, range) { + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; + return node; + } + function getCommentRange(node) { + return node.commentRange || node; + } + function setCommentRange(node, range) { + beforeSetAnnotation(node); + node.commentRange = range; + return node; + } + function hoistVariableDeclaration(name) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var decl = ts.createVariableDeclaration(name); + if (!hoistedVariableDeclarations) { + hoistedVariableDeclarations = [decl]; + } + else { + hoistedVariableDeclarations.push(decl); + } + } + function hoistFunctionDeclaration(func) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + if (!hoistedFunctionDeclarations) { + hoistedFunctionDeclarations = [func]; + } + else { + hoistedFunctionDeclarations.push(func); + } + } + function startLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentStackOffset++; + hoistedVariableDeclarations = undefined; + hoistedFunctionDeclarations = undefined; + } + function endLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + var statements; + if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { + if (hoistedFunctionDeclarations) { + statements = hoistedFunctionDeclarations.slice(); + } + if (hoistedVariableDeclarations) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + lexicalEnvironmentStackOffset--; + hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + return statements; + } + } + ts.transformFiles = transformFiles; + function chain(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + function compose(a, b, c, d, e) { + if (e) { + var args_4 = []; + for (var i = 0; i < arguments.length; i++) { + args_4[i] = arguments[i]; + } + return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + var _a; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { + if (compilerOptions.extendedDiagnostics) { + return createSourceMapWriterWithExtendedDiagnostics(host, writer); + } + return createSourceMapWriterWorker(host, writer); + } + else { + return getNullSourceMapWriter(); + } + } + ts.createSourceMapWriter = createSourceMapWriter; var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { }, + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitPos: function (pos) { }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + changeEmitSourcePos: function () { }, + stopOverridingSpan: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -27786,27 +41175,11 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitStart: function (range) { }, - emitEnd: function (range, stopOverridingSpan) { }, - emitPos: function (pos) { }, - changeEmitSourcePos: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; }, - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; - function createSourceMapWriter(host, writer) { + function createSourceMapWriterWorker(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; + var currentSourceText; var sourceMapDir; var stopOverridingSpan = false; var modifyLastSourcePos = false; @@ -27815,23 +41188,29 @@ var ts; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; + var disableDepth; return { + initialize: initialize, + reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitStart: emitStart, emitEnd: emitEnd, + emitTokenStart: emitTokenStart, + emitTokenEnd: emitTokenEnd, changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: function () { return stopOverridingSpan = true; }, getText: getText, - getSourceMappingURL: getSourceMappingURL, - initialize: initialize, - reset: reset + getSourceMappingURL: getSourceMappingURL }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { if (sourceMapData) { reset(); } currentSourceFile = undefined; + currentSourceText = undefined; + disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -27878,6 +41257,15 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + disableDepth = 0; + } + function enable() { + if (disableDepth > 0) { + disableDepth--; + } + } + function disable() { + disableDepth++; } function updateLastEncodedAndRecordedSpans() { if (modifyLastSourcePos) { @@ -27931,9 +41319,12 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (pos === -1) { + if (ts.positionIsSynthesized(pos) || disableDepth > 0) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); sourceLinePos.line++; sourceLinePos.character++; @@ -27961,17 +41352,70 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } - function getStartPos(range) { + function getStartPosPastDecorators(range) { var rangeHasDecorators = !!range.decorators; - return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); } - function emitStart(range) { - emitPos(getStartPos(range)); + function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(getStartPosPastDecorators(range)); + } + if (ignoreChildrenCallback(contextNode)) { + disable(); + } + } + else { + emitPos(getStartPosPastDecorators(range)); + } } - function emitEnd(range, stopOverridingEnd) { - emitPos(range.end); - stopOverridingSpan = stopOverridingEnd; + function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (ignoreChildrenCallback(contextNode)) { + enable(); + } + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(range.end); + } + } + else { + emitPos(range.end); + } + stopOverridingSpan = false; + } + function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return ts.skipTrivia(currentSourceText, tokenStartPos); + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenStartPos = range.pos; + } + } + tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); + emitPos(tokenStartPos); + return tokenStartPos; + } + function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return tokenEndPos; + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenEndPos = range.end; + } + } + emitPos(tokenEndPos); + return tokenEndPos; } function changeEmitSourcePos() { ts.Debug.assert(!modifyLastSourcePos); @@ -27979,15 +41423,16 @@ var ts; } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); - sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); } } } @@ -28013,7 +41458,46 @@ var ts; } } } - ts.createSourceMapWriter = createSourceMapWriter; + function createSourceMapWriterWithExtendedDiagnostics(host, writer) { + var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; + return { + initialize: initialize, + reset: reset, + getSourceMapData: getSourceMapData, + setSourceFile: setSourceFile, + emitPos: function (pos) { + ts.performance.mark("sourcemapStart"); + emitPos(pos); + ts.performance.measure("sourceMapTime", "sourcemapStart"); + }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitStart"); + emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); + }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitEnd"); + emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); + }, + emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenStart"); + tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); + return tokenStartPos; + }, + emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenEnd"); + tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); + return tokenEndPos; + }, + changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: stopOverridingSpan, + getText: getText, + getSourceMappingURL: getSourceMappingURL + }; + } var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -28041,6 +41525,267 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function createCommentWriter(host, writer, sourceMap) { + var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; + var newLine = host.getNewLine(); + var emitPos = sourceMap.emitPos; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentSourceFile; + var currentText; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var disabled = compilerOptions.removeComments; + return { + reset: reset, + setSourceFile: setSourceFile, + emitNodeWithComments: emitNodeWithComments, + emitBodyWithDetachedComments: emitBodyWithDetachedComments, + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + }; + function emitNodeWithComments(node, emitCallback) { + if (disabled) { + emitCallback(node); + return; + } + if (node) { + var _a = node.commentRange || node, pos = _a.pos, end = _a.end; + var emitFlags = node.emitFlags; + if ((pos < 0 && end < 0) || (pos === end)) { + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + } + else { + if (extendedDiagnostics) { + ts.performance.mark("preEmitNodeWithComment"); + } + var isEmittedNode = node.kind !== 287; + var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 32768) !== 0; + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if (!skipLeadingComments) { + containerPos = pos; + } + if (!skipTrailingComments) { + containerEnd = end; + if (node.kind === 219) { + declarationListContainerEnd = end; + } + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitNodeWithComment"); + } + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitNodeWithComment"); + } + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitNodeWithComment"); + } + } + } + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + if (extendedDiagnostics) { + ts.performance.mark("preEmitBodyWithDetachedComments"); + } + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = node.emitFlags; + var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); + } + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + } + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, true); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + } + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); + hasWrittenComment = true; + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + if (!writer.isAtStartOfLine()) { + writer.write(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos) { + if (disabled) { + return; + } + if (extendedDiagnostics) { + ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); + } + forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); + } + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + if (containerPos === -1 || pos !== containerPos) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { + ts.forEachTrailingCommentRange(currentText, end, cb); + } + } + function reset() { + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentText = currentSourceFile.text; + currentLineMap = ts.getLineStarts(currentSourceFile); + detachedCommentsInfo = undefined; + } + function disableCommentsAndEmit(node, emitCallback) { + if (disabled) { + emitCallback(node); + } + else { + disabled = true; + emitCallback(node); + disabled = false; + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + function isTripleSlashComment(commentPos, commentEnd) { + if (currentText.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + currentText.charCodeAt(commentPos + 2) === 47) { + var textSubStr = currentText.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? + true : false; + } + return false; + } + } + ts.createCommentWriter = createCommentWriter; +})(ts || (ts = {})); +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { var declarationDiagnostics = ts.createDiagnosticCollection(); @@ -28138,9 +41883,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -28229,11 +41972,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = {}; + usedTypeDirectiveReferences = ts.createMap(); } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { + if (!(directive in usedTypeDirectiveReferences)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -28258,7 +42001,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -28317,7 +42060,7 @@ var ts; if (declaration) { var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, false, true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -28385,7 +42128,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); emitEntityName(node.expression); if (node.typeArguments) { @@ -28454,15 +42197,15 @@ var ts; } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentIdentifiers, baseName)) { + if (!(baseName in currentIdentifiers)) { return baseName; } var count = 0; while (true) { count++; - var name_23 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_23)) { - return name_23; + var name_40 = baseName + "_" + count; + if (!(name_40 in currentIdentifiers)) { + return name_40; } } } @@ -28560,10 +42303,11 @@ var ts; } function emitModuleElementDeclarationFlags(node) { if (node.parent.kind === 256) { - if (node.flags & 1) { + var modifiers = ts.getModifierFlags(node); + if (modifiers & 1) { write("export "); } - if (node.flags & 512) { + if (modifiers & 512) { write("default "); } else if (node.kind !== 222 && !noDeclare) { @@ -28590,7 +42334,7 @@ var ts; } function writeImportEqualsDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { write("export "); } write("import "); @@ -28626,7 +42370,7 @@ var ts; } function writeImportDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { write("export "); } write("import "); @@ -28717,7 +42461,7 @@ var ts; write("global "); } else { - if (node.flags & 4096) { + if (node.flags & 16) { write("namespace "); } else { @@ -28800,7 +42544,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 && (node.parent.flags & 8); + return node.parent.kind === 147 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -28842,7 +42586,7 @@ var ts; break; case 147: case 146: - if (node.parent.flags & 32) { + if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 221) { @@ -28877,7 +42621,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93) { @@ -28909,7 +42653,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 92) { + if (ts.hasModifier(param, 92)) { emitPropertyDeclaration(param); } }); @@ -28917,7 +42661,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 128) { + if (ts.hasModifier(node, 128)) { write("abstract "); } write("class "); @@ -28963,7 +42707,7 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); emitVariableDeclaration(node); write(";"); writeLine(); @@ -28975,13 +42719,18 @@ var ts; } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || node.kind === 142) && ts.hasQuestionToken(node)) { + if ((node.kind === 145 || node.kind === 144 || + (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 8)) { + else if (resolver.isLiteralConstDeclaration(node)) { + write(" = "); + resolver.writeLiteralConstValue(node, writer); + } + else if (!ts.hasModifier(node, 8)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -28995,7 +42744,7 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } else if (node.kind === 145 || node.kind === 144) { - if (node.flags & 32) { + if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29088,9 +42837,9 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64)); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); writeTextOfNode(currentText, node.name); - if (!(node.flags & 8)) { + if (!ts.hasModifier(node, 8)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -29117,7 +42866,7 @@ var ts; function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 150) { - if (accessorWithTypeAnnotation.parent.flags & 32) { + if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -29134,7 +42883,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 32) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -29166,7 +42915,7 @@ var ts; emitModuleElementDeclarationFlags(node); } else if (node.kind === 147 || node.kind === 148) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } if (node.kind === 220) { write("function "); @@ -29193,7 +42942,7 @@ var ts; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; if (node.kind === 153) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { @@ -29224,7 +42973,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 148 && !(node.flags & 8)) { + else if (node.kind !== 148 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -29255,7 +43004,7 @@ var ts; break; case 147: case 146: - if (node.flags & 32) { + if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -29312,7 +43061,7 @@ var ts; node.parent.parent.kind === 159) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 8)) { + else if (!ts.hasModifier(node.parent, 8)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { @@ -29341,7 +43090,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 147: case 146: - if (node.parent.flags & 32) { + if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29499,6283 +43248,71 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getResolvedExternalModuleName(host, file) { - return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); - } - ts.getResolvedExternalModuleName = getResolvedExternalModuleName; - function getExternalModuleNameFromDeclaration(host, resolver, declaration) { - var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || ts.isDeclarationFile(file)) { - return undefined; - } - return getResolvedExternalModuleName(host, file); - } - ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = { - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }; function emitFiles(resolver, host, targetSourceFile) { + var delimiters = createDelimiterMap(); + var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; + var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; + var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; + var superHelper = "\nconst _super = name => super[name];"; + var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var emitSkipped = false; var newLine = host.getNewLine(); - var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); + var transformers = ts.getTransformers(compilerOptions); + var writer = ts.createTextWriter(newLine); + var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = ts.createSourceMapWriter(host, writer); + var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var comments = ts.createCommentWriter(host, writer, sourceMap); + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var nodeIdToGeneratedName; + var autoGeneratedIdToGeneratedName; + var generatedNameSet; + var tempFlags; + var currentSourceFile; + var currentText; + var currentFileIdentifiers; + var extendsEmitted; + var assignEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; + var isOwnFileEmit; + var emitSkipped = false; + ts.performance.mark("beforeTransform"); + var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.measure("transformTime", "beforeTransform"); + var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); + transformed.dispose(); + ts.performance.measure("printTime", "beforePrint"); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList }; - function isUniqueLocalName(name, container) { - for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name)) { - if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { - return false; - } - } - } - return true; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function hoistVariableDeclarationFromLoop(state, declaration) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(declaration.name); - function visit(node) { - if (node.kind === 69) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _a = 0, _b = node.elements; _a < _b.length; _a++) { - var element = _b[_a]; - visit(element.name); - } - } - } - } - function createFileEmitter() { - var writer = ts.createTextWriter(newLine); - var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; - var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); - var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; - var currentSourceFile; - var currentText; - var currentLineMap; - var currentFileIdentifiers; - var renamedDependencies; - var isEs6Module; - var isCurrentFileExternalModule; - var exportFunctionForFile; - var contextObjectForFile; - var generatedNameSet; - var nodeToGeneratedName; - var computedPropertyNamesToGeneratedNames; - var decoratedClassAliases; - var convertedLoopState; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; - var tempFlags = 0; - var tempVariables; - var tempParameters; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var detachedCommentsInfo; - var sourceMapData; - var isOwnFileEmit; - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; - var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, - _a[ts.ModuleKind.ES6] = emitES6Module, - _a[ts.ModuleKind.AMD] = emitAMDModule, - _a[ts.ModuleKind.System] = emitSystemModule, - _a[ts.ModuleKind.UMD] = emitUMDModule, - _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, - _a - ); - var bundleEmitDelegates = (_b = {}, - _b[ts.ModuleKind.ES6] = function () { }, - _b[ts.ModuleKind.AMD] = emitAMDModule, - _b[ts.ModuleKind.System] = emitSystemModule, - _b[ts.ModuleKind.UMD] = function () { }, - _b[ts.ModuleKind.CommonJS] = function () { }, - _b - ); - return doEmit; - function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = {}; - nodeToGeneratedName = []; - decoratedClassAliases = []; - isOwnFileEmit = !isBundledEmit; - if (isBundledEmit && modulekind) { - ts.forEach(sourceFiles, emitEmitHelpers); - } - ts.forEach(sourceFiles, emitSourceFile); - writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); - if (sourceMappingURL) { - write("//# sourceMappingURL=" + sourceMappingURL); - } - writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles); - sourceMap.reset(); - writer.reset(); - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - generatedNameSet = undefined; - nodeToGeneratedName = undefined; - decoratedClassAliases = undefined; - computedPropertyNamesToGeneratedNames = undefined; - convertedLoopState = undefined; - extendsEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; - assignEmitted = false; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = undefined; - detachedCommentsInfo = undefined; - sourceMapData = undefined; - isEs6Module = false; - renamedDependencies = undefined; - isCurrentFileExternalModule = false; - } - function emitSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = sourceFile.text; - currentLineMap = ts.getLineStarts(sourceFile); - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; - renamedDependencies = sourceFile.renamedDependencies; - currentFileIdentifiers = sourceFile.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - setSourceFile(sourceFile); - emitNodeWithCommentsAndWithoutSourcemap(sourceFile); - } - function isUniqueName(name) { - return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); - } - function makeTempVariableName(flags) { - if (flags && !(tempFlags & flags)) { - var name_24 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_24)) { - tempFlags |= flags; - return name_24; - } - } - while (true) { - var count = tempFlags & 268435455; - tempFlags++; - if (count !== 8 && count !== 13) { - var name_25 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_25)) { - return name_25; - } - } - } - } - function makeUniqueName(baseName) { - if (baseName.charCodeAt(baseName.length - 1) !== 95) { - baseName += "_"; - } - var i = 1; - while (true) { - var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - return generatedNameSet[generatedName] = generatedName; - } - i++; - } - } - function generateNameForModuleOrEnum(node) { - var name = node.name.text; - return isUniqueLocalName(name, node) ? name : makeUniqueName(name); - } - function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - return makeUniqueName(baseName); - } - function generateNameForExportDefault() { - return makeUniqueName("default"); - } - function generateNameForClassExpression() { - return makeUniqueName("class"); - } - function generateNameForNode(node) { - switch (node.kind) { - case 69: - return makeUniqueName(node.text); - case 225: - case 224: - return generateNameForModuleOrEnum(node); - case 230: - case 236: - return generateNameForImportOrExportDeclaration(node); - case 220: - case 221: - case 235: - return generateNameForExportDefault(); - case 192: - return generateNameForClassExpression(); - default: - ts.Debug.fail(); - } - } - function getGeneratedNameForNode(node) { - var id = ts.getNodeId(node); - return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); - } - function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark, sourceFiles) { - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); - } - ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark, sourceFiles); - } - function createTempVariable(flags) { - var result = ts.createSynthesizedNode(69); - result.text = makeTempVariableName(flags); - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function createAndRecordTempVariable(flags) { - var temp = createTempVariable(flags); - recordTempDeclaration(temp); - return temp; - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - function emitToken(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - emitPos(tokenStartPos); - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - var tokenEndPos = tokenStartPos + tokenString.length; - emitPos(tokenEndPos); - return tokenEndPos; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitParenthesizedIf(node, parenthesized) { - if (parenthesized) { - write("("); - } - emit(node); - if (parenthesized) { - write(")"); - } - } - function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { - ts.Debug.assert(nodes.length > 0); - increaseIndent(); - if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - for (var i = 0, n = nodes.length; i < n; i++) { - if (i) { - if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { - write(", "); - } - else { - write(","); - writeLine(); - } - } - emit(nodes[i]); - } - if (nodes.hasTrailingComma && allowTrailingComma) { - write(","); - } - decreaseIndent(); - if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - } - function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) { - if (!emitNode) { - emitNode = emit; - } - for (var i = 0; i < count; i++) { - if (multiLine) { - if (i || leadingComma) { - write(","); - } - writeLine(); - } - else { - if (i || leadingComma) { - write(", "); - } - } - var node = nodes[start + i]; - emitTrailingCommentsOfPosition(node.pos); - emitNode(node); - leadingComma = true; - } - if (trailingComma) { - write(","); - } - if (multiLine && !noTrailingNewLine) { - writeLine(); - } - return count; - } - function emitCommaList(nodes) { - if (nodes) { - emitList(nodes, 0, nodes.length, false, false); - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(node, text) { - if (node.kind === 8 && text.length > 1) { - switch (text.charCodeAt(1)) { - case 98: - case 66: - case 111: - case 79: - return true; - } - } - return false; - } - function emitLiteral(node) { - var text = getLiteralText(node); - if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (languageVersion < 2 && isBinaryOrOctalIntegerLiteral(node, text)) { - write(node.text); - } - else { - write(text); - } - } - function getLiteralText(node) { - if (languageVersion < 2 && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { - return getQuotedEscapedLiteralText('"', node.text, '"'); - } - if (node.parent) { - return ts.getTextOfNodeFromSourceText(currentText, node); - } - switch (node.kind) { - case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11: - return getQuotedEscapedLiteralText("`", node.text, "`"); - case 12: - return getQuotedEscapedLiteralText("`", node.text, "${"); - case 13: - return getQuotedEscapedLiteralText("}", node.text, "${"); - case 14: - return getQuotedEscapedLiteralText("}", node.text, "`"); - case 8: - return node.text; - } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); - } - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; - } - function emitDownlevelRawTemplateLiteral(node) { - var text = ts.getTextOfNodeFromSourceText(currentText, node); - var isLast = node.kind === 11 || node.kind === 14; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - text = text.replace(/\r\n?/g, "\n"); - text = ts.escapeString(text); - write("\"" + text + "\""); - } - function emitDownlevelTaggedTemplateArray(node, literalEmitter) { - write("["); - if (node.template.kind === 11) { - literalEmitter(node.template); - } - else { - literalEmitter(node.template.head); - ts.forEach(node.template.templateSpans, function (child) { - write(", "); - literalEmitter(child.literal); - }); - } - write("]"); - } - function emitDownlevelTaggedTemplate(node) { - var tempVariable = createAndRecordTempVariable(0); - write("("); - emit(tempVariable); - write(" = "); - emitDownlevelTaggedTemplateArray(node, emit); - write(", "); - emit(tempVariable); - write(".raw = "); - emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral); - write(", "); - emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); - write("("); - emit(tempVariable); - if (node.template.kind === 189) { - ts.forEach(node.template.templateSpans, function (templateSpan) { - write(", "); - var needsParens = templateSpan.expression.kind === 187 - && templateSpan.expression.operatorToken.kind === 24; - emitParenthesizedIf(templateSpan.expression, needsParens); - }); - } - write("))"); - } - function emitTemplateExpression(node) { - if (languageVersion >= 2) { - ts.forEachChild(node, emit); - return; - } - var emitOuterParens = ts.isExpression(node.parent) - && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - var headEmitted = false; - if (shouldEmitTemplateHead()) { - emitLiteral(node.head); - headEmitted = true; - } - for (var i = 0, n = node.templateSpans.length; i < n; i++) { - var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 178 - && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; - if (i > 0 || headEmitted) { - write(" + "); - } - emitParenthesizedIf(templateSpan.expression, needsParens); - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - } - if (emitOuterParens) { - write(")"); - } - function shouldEmitTemplateHead() { - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 174: - case 175: - return parent.expression === template; - case 176: - case 178: - return false; - default: - return comparePrecedenceToBinaryPlus(parent) !== -1; - } - } - function comparePrecedenceToBinaryPlus(expression) { - switch (expression.kind) { - case 187: - switch (expression.operatorToken.kind) { - case 37: - case 39: - case 40: - return 1; - case 35: - case 36: - return 0; - default: - return -1; - } - case 190: - case 188: - return -1; - default: - return 1; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - function jsxEmitReact(node) { - function emitTagName(name) { - if (name.kind === 69 && ts.isIntrinsicJsxName(name.text)) { - write('"'); - emit(name); - write('"'); - } - else { - emit(name); - } - } - function emitAttributeName(name) { - if (/^[A-Za-z_]\w*$/.test(name.text)) { - emit(name); - } - else { - write('"'); - emit(name); - write('"'); - } - } - function emitJsxAttribute(node) { - emitAttributeName(node.name); - write(": "); - if (node.initializer) { - emit(node.initializer); - } - else { - write("true"); - } - } - function emitJsxElement(openingNode, children) { - var syntheticReactRef = ts.createSynthesizedNode(69); - syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; - syntheticReactRef.parent = openingNode; - emitLeadingComments(openingNode); - emitExpressionIdentifier(syntheticReactRef); - write(".createElement("); - emitTagName(openingNode.tagName); - write(", "); - if (openingNode.attributes.length === 0) { - write("null"); - } - else { - var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 247; })) { - write("__assign("); - var haveOpenedObjectLiteral = false; - for (var i = 0; i < attrs.length; i++) { - if (attrs[i].kind === 247) { - if (i === 0) { - write("{}, "); - } - if (haveOpenedObjectLiteral) { - write("}"); - haveOpenedObjectLiteral = false; - } - if (i > 0) { - write(", "); - } - emit(attrs[i].expression); - } - else { - ts.Debug.assert(attrs[i].kind === 246); - if (haveOpenedObjectLiteral) { - write(", "); - } - else { - haveOpenedObjectLiteral = true; - if (i > 0) { - write(", "); - } - write("{"); - } - emitJsxAttribute(attrs[i]); - } - } - if (haveOpenedObjectLiteral) - write("}"); - write(")"); - } - else { - write("{"); - for (var i = 0, n = attrs.length; i < n; i++) { - if (i > 0) { - write(", "); - } - emitJsxAttribute(attrs[i]); - } - write("}"); - } - } - if (children) { - var firstChild = void 0; - var multipleEmittableChildren = false; - for (var i = 0, n = children.length; i < n; i++) { - var jsxChild = children[i]; - if (isJsxChildEmittable(jsxChild)) { - if (!firstChild) { - write(", "); - firstChild = jsxChild; - } - else { - if (!multipleEmittableChildren) { - multipleEmittableChildren = true; - increaseIndent(); - writeLine(); - emit(firstChild); - } - write(", "); - writeLine(); - emit(jsxChild); - } - } - } - if (multipleEmittableChildren) { - decreaseIndent(); - } - else if (firstChild) { - if (firstChild.kind !== 241 && firstChild.kind !== 242) { - emit(firstChild); - } - else { - increaseIndent(); - writeLine(); - emit(firstChild); - writeLine(); - decreaseIndent(); - } - } - } - write(")"); - emitTrailingComments(openingNode); - } - if (node.kind === 241) { - emitJsxElement(node.openingElement, node.children); - } - else { - ts.Debug.assert(node.kind === 242); - emitJsxElement(node); - } - } - function jsxEmitPreserve(node) { - function emitJsxAttribute(node) { - emit(node.name); - if (node.initializer) { - write("="); - emit(node.initializer); - } - } - function emitJsxSpreadAttribute(node) { - write("{..."); - emit(node.expression); - write("}"); - } - function emitAttributes(attribs) { - for (var i = 0, n = attribs.length; i < n; i++) { - if (i > 0) { - write(" "); - } - if (attribs[i].kind === 247) { - emitJsxSpreadAttribute(attribs[i]); - } - else { - ts.Debug.assert(attribs[i].kind === 246); - emitJsxAttribute(attribs[i]); - } - } - } - function emitJsxOpeningOrSelfClosingElement(node) { - write("<"); - emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 242)) { - write(" "); - } - emitAttributes(node.attributes); - if (node.kind === 242) { - write("/>"); - } - else { - write(">"); - } - } - function emitJsxClosingElement(node) { - write(""); - } - function emitJsxElement(node) { - emitJsxOpeningOrSelfClosingElement(node.openingElement); - for (var i = 0, n = node.children.length; i < n; i++) { - emit(node.children[i]); - } - emitJsxClosingElement(node.closingElement); - } - if (node.kind === 241) { - emitJsxElement(node); - } - else { - ts.Debug.assert(node.kind === 242); - emitJsxOpeningOrSelfClosingElement(node); - } - } - function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 169); - if (node.kind === 9) { - emitLiteral(node); - } - else if (node.kind === 140) { - if (ts.nodeIsDecorated(node.parent)) { - if (!computedPropertyNamesToGeneratedNames) { - computedPropertyNamesToGeneratedNames = []; - } - var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)]; - if (generatedName) { - write(generatedName); - return; - } - generatedName = createAndRecordTempVariable(0).text; - computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName; - write(generatedName); - write(" = "); - } - emit(node.expression); - } - else { - write('"'); - if (node.kind === 8) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - write('"'); - } - } - function isExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 170: - case 195: - case 184: - case 187: - case 174: - case 249: - case 140: - case 188: - case 143: - case 181: - case 204: - case 173: - case 235: - case 202: - case 194: - case 206: - case 207: - case 208: - case 203: - case 245: - case 242: - case 243: - case 247: - case 248: - case 175: - case 196: - case 178: - case 186: - case 185: - case 211: - case 254: - case 191: - case 213: - case 176: - case 197: - case 215: - case 177: - case 182: - case 183: - case 205: - case 212: - case 190: - return true; - case 169: - case 255: - case 142: - case 253: - case 145: - case 218: - return parent.initializer === node; - case 172: - return parent.expression === node; - case 180: - case 179: - return parent.body === node; - case 229: - return parent.moduleReference === node; - case 139: - return parent.left === node; - } - return false; - } - function emitExpressionIdentifier(node) { - var container = resolver.getReferencedExportContainer(node); - if (container) { - if (container.kind === 256) { - if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - else { - write(getGeneratedNameForNode(container)); - write("."); - } - } - else { - if (modulekind !== ts.ModuleKind.ES6) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (declaration.kind === 231) { - write(getGeneratedNameForNode(declaration.parent)); - write(languageVersion === 0 ? '["default"]' : ".default"); - return; - } - else if (declaration.kind === 234) { - write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_26 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_26); - if (languageVersion === 0 && identifier === "default") { - write('["default"]'); - } - else { - write("."); - write(identifier); - } - return; - } - } - } - if (languageVersion < 2) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - else if (resolver.getNodeCheckFlags(node) & 1048576) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; - if (classAlias !== undefined) { - write(classAlias); - return; - } - } - } - } - if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { - if (languageVersion < 2) { - var parent_13 = node.parent; - switch (parent_13.kind) { - case 169: - case 221: - case 224: - case 218: - return parent_13.name === node && resolver.isDeclarationWithCollidingName(parent_13); - } - } - return false; - } - function getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node) { - if (languageVersion >= 2) { - var parent_14 = node.parent; - if (parent_14.kind === 172 && parent_14.expression === node) { - parent_14 = parent_14.parent; - while (parent_14 && parent_14.kind !== 145) { - parent_14 = parent_14.parent; - } - return parent_14 && parent_14.kind === 145 && (parent_14.flags & 32) !== 0 && - parent_14.parent.kind === 192 ? parent_14.parent : undefined; - } - } - return undefined; - } - function emitIdentifier(node) { - if (convertedLoopState) { - if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_27 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_27); - return; - } - } - if (!node.parent) { - write(node.text); - } - else if (isExpressionIdentifier(node)) { - var classExpression = getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node); - if (classExpression) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration === classExpression) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - emitExpressionIdentifier(node); - } - else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { - write(getGeneratedNameForNode(node)); - } - else if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2) { - write("_this"); - } - else if (convertedLoopState) { - write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); - } - else { - write("this"); - } - } - function emitSuper(node) { - if (languageVersion >= 2) { - write("super"); - } - else { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 256) { - write("_super.prototype"); - } - else { - write("_super"); - } - } - } - function emitObjectBindingPattern(node) { - write("{ "); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write("]"); - } - function emitBindingElement(node) { - if (node.propertyName) { - emit(node.propertyName); - write(": "); - } - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emit(node.name); - } - else { - emitModuleMemberName(node); - } - emitOptional(" = ", node.initializer); - } - function emitSpreadElementExpression(node) { - write("..."); - emit(node.expression); - } - function emitYieldExpression(node) { - write(ts.tokenToString(114)); - if (node.asteriskToken) { - write("*"); - } - if (node.expression) { - write(" "); - emit(node.expression); - } - } - function emitAwaitExpression(node) { - var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); - if (needsParenthesis) { - write("("); - } - write(ts.tokenToString(114)); - write(" "); - emit(node.expression); - if (needsParenthesis) { - write(")"); - } - } - function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 187 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { - return true; - } - else if (node.parent.kind === 188 && node.parent.condition === node) { - return true; - } - return false; - } - function needsParenthesisForPropertyAccessOrInvocation(node) { - switch (node.kind) { - case 69: - case 170: - case 172: - case 173: - case 174: - case 178: - return false; - } - return true; - } - function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { - var pos = 0; - var group = 0; - var length = elements.length; - while (pos < length) { - if (group === 1 && useConcat) { - write(".concat("); - } - else if (group > 0) { - write(", "); - } - var e = elements[pos]; - if (e.kind === 191) { - e = e.expression; - emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); - pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 170) { - write(".slice()"); - } - } - else { - var i = pos; - while (i < length && elements[i].kind !== 191) { - i++; - } - write("["); - if (multiLine) { - increaseIndent(); - } - emitList(elements, pos, i - pos, multiLine, trailingComma && i === length); - if (multiLine) { - decreaseIndent(); - } - write("]"); - pos = i; - } - group++; - } - if (group > 1) { - if (useConcat) { - write(")"); - } - } - } - function isSpreadElementExpression(node) { - return node.kind === 191; - } - function emitArrayLiteral(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else if (languageVersion >= 2 || !ts.forEach(elements, isSpreadElementExpression)) { - write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, false); - write("]"); - } - else { - emitListWithSpread(elements, true, node.multiLine, elements.hasTrailingComma, true); - } - } - function emitObjectLiteralBody(node, numElements) { - if (numElements === 0) { - write("{}"); - return; - } - write("{"); - if (numElements > 0) { - var properties = node.properties; - if (numElements === properties.length) { - emitLinePreservingList(node, properties, languageVersion >= 1, true); - } - else { - var multiLine = node.multiLine; - if (!multiLine) { - write(" "); - } - else { - increaseIndent(); - } - emitList(properties, 0, numElements, multiLine, false); - if (!multiLine) { - write(" "); - } - else { - decreaseIndent(); - } - } - } - write("}"); - } - function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = node.multiLine; - var properties = node.properties; - write("("); - if (multiLine) { - increaseIndent(); - } - var tempVar = createAndRecordTempVariable(0); - emit(tempVar); - write(" = "); - emitObjectLiteralBody(node, firstComputedPropertyIndex); - for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); - var property = properties[i]; - emitStart(property); - if (property.kind === 149 || property.kind === 150) { - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property !== accessors.firstAccessor) { - continue; - } - write("Object.defineProperty("); - emit(tempVar); - write(", "); - emitStart(property.name); - emitExpressionForPropertyName(property.name); - emitEnd(property.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("})"); - emitEnd(property); - } - else { - emitLeadingComments(property); - emitStart(property.name); - emit(tempVar); - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - if (property.kind === 253) { - emit(property.initializer); - } - else if (property.kind === 254) { - emitExpressionIdentifier(property.name); - } - else if (property.kind === 147) { - emitFunctionDeclaration(property); - } - else { - ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); - } - } - emitEnd(property); - } - writeComma(); - emit(tempVar); - if (multiLine) { - decreaseIndent(); - writeLine(); - } - write(")"); - function writeComma() { - if (multiLine) { - write(","); - writeLine(); - } - else { - write(", "); - } - } - } - function emitObjectLiteral(node) { - var properties = node.properties; - if (languageVersion < 2) { - var numProperties = properties.length; - var numInitialNonComputedProperties = numProperties; - for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 140) { - numInitialNonComputedProperties = i; - break; - } - } - var hasComputedProperty = numInitialNonComputedProperties !== properties.length; - if (hasComputedProperty) { - emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); - return; - } - } - emitObjectLiteralBody(node, properties.length); - } - function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(187, startsOnNewLine); - result.operatorToken = ts.createSynthesizedNode(operator); - result.left = left; - result.right = right; - return result; - } - function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(172); - result.expression = parenthesizeForAccess(expression); - result.name = name; - return result; - } - function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(173); - result.expression = parenthesizeForAccess(expression); - result.argumentExpression = argumentExpression; - return result; - } - function parenthesizeForAccess(expr) { - while (expr.kind === 177 || - expr.kind === 195 || - expr.kind === 196) { - expr = expr.expression; - } - if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 175 && - expr.kind !== 8) { - return expr; - } - var node = ts.createSynthesizedNode(178); - node.expression = expr; - return node; - } - function emitComputedPropertyName(node) { - write("["); - emitExpressionForPropertyName(node); - write("]"); - } - function emitMethod(node) { - if (languageVersion >= 2 && node.asteriskToken) { - write("*"); - } - emit(node.name); - if (languageVersion < 2) { - write(": function "); - } - emitSignatureAndBody(node); - } - function emitPropertyAssignment(node) { - emit(node.name); - write(": "); - emitTrailingCommentsOfPosition(node.initializer.pos); - emit(node.initializer); - } - function isExportReference(node) { - var container = resolver.getReferencedExportContainer(node); - return !!container; - } - function isImportedReference(node) { - var declaration = resolver.getReferencedImportDeclaration(node); - return declaration && (declaration.kind === 231 || declaration.kind === 234); - } - function emitShorthandPropertyAssignment(node) { - writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { - write(": "); - emitExpressionIdentifier(node.name); - } - if (languageVersion >= 2 && node.objectAssignmentInitializer) { - write(" = "); - emit(node.objectAssignmentInitializer); - } - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(constantValue.toString()); - if (!compilerOptions.removeComments) { - var propertyName = node.kind === 172 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return node.kind === 172 || node.kind === 173 - ? resolver.getConstantValue(node) - : undefined; - } - function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) { - var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); - var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); - if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { - increaseIndent(); - writeLine(); - return true; - } - else { - if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); - } - return false; - } - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 && - node.expression.kind === 95 && - isInAsyncMethodWithSuperInES6(node)) { - var name_28 = ts.createSynthesizedNode(9); - name_28.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_28); - return; - } - emit(node.expression); - var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; - var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); - var shouldEmitSpace = false; - if (!indentedBeforeDot) { - if (node.expression.kind === 8) { - var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); - shouldEmitSpace = text.indexOf(ts.tokenToString(21)) < 0; - } - else { - var constantValue = tryGetConstEnumValue(node.expression); - shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; - } - } - if (shouldEmitSpace) { - write(" ."); - } - else { - write("."); - } - var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); - emit(node.name); - decreaseIndentIf(indentedBeforeDot, indentedAfterDot); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitQualifiedNameAsExpression(node, useFallback) { - if (node.left.kind === 69) { - emitEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = createAndRecordTempVariable(0); - write("("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(node.left, true); - write(") && "); - emitNodeWithoutSourceMap(temp); - } - else { - emitEntityNameAsExpression(node.left, false); - } - write("."); - emit(node.right); - } - function emitEntityNameAsExpression(node, useFallback) { - switch (node.kind) { - case 69: - if (useFallback) { - write("typeof "); - emitExpressionIdentifier(node); - write(" !== 'undefined' && "); - } - emitExpressionIdentifier(node); - break; - case 139: - emitQualifiedNameAsExpression(node, useFallback); - break; - default: - emitNodeWithoutSourceMap(node); - break; - } - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 && - node.expression.kind === 95 && - isInAsyncMethodWithSuperInES6(node)) { - emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 191; }); - } - function skipParentheses(node) { - while (node.kind === 178 || - node.kind === 177 || - node.kind === 195 || - node.kind === 196) { - node = node.expression; - } - return node; - } - function emitCallTarget(node) { - if (node.kind === 69 || node.kind === 97 || node.kind === 95) { - emit(node); - return node; - } - var temp = createAndRecordTempVariable(0); - write("("); - emit(temp); - write(" = "); - emit(node); - write(")"); - return temp; - } - function emitCallWithSpread(node) { - var target; - var expr = skipParentheses(node.expression); - if (expr.kind === 172) { - target = emitCallTarget(expr.expression); - write("."); - emit(expr.name); - } - else if (expr.kind === 173) { - target = emitCallTarget(expr.expression); - write("["); - emit(expr.argumentExpression); - write("]"); - } - else if (expr.kind === 95) { - target = expr; - write("_super"); - } - else { - emit(node.expression); - } - write(".apply("); - if (target) { - if (target.kind === 95) { - emitThis(target); - } - else { - emit(target); - } - } - else { - write("void 0"); - } - write(", "); - emitListWithSpread(node.arguments, false, false, false, true); - write(")"); - } - function isInAsyncMethodWithSuperInES6(node) { - if (languageVersion === 2) { - var container = ts.getSuperContainer(node, false); - if (container && resolver.getNodeCheckFlags(container) & (2048 | 4096)) { - return true; - } - } - return false; - } - function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { - var container = ts.getSuperContainer(superNode, false); - var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096; - write("_super("); - emit(argumentExpression); - write(isSuperBinding ? ").value" : ")"); - } - function emitCallExpression(node) { - if (languageVersion < 2 && hasSpreadElement(node.arguments)) { - emitCallWithSpread(node); - return; - } - var expression = node.expression; - var superCall = false; - var isAsyncMethodWithSuper = false; - if (expression.kind === 95) { - emitSuper(expression); - superCall = true; - } - else { - superCall = ts.isSuperPropertyOrElementAccess(expression); - isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); - emit(expression); - } - if (superCall && (languageVersion < 2 || isAsyncMethodWithSuper)) { - write(".call("); - emitThis(expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - if (languageVersion === 1 && - node.arguments && - hasSpreadElement(node.arguments)) { - write("("); - var target = emitCallTarget(node.expression); - write(".bind.apply("); - emit(target); - write(", [void 0].concat("); - emitListWithSpread(node.arguments, false, false, false, false); - write(")))"); - write("()"); - } - else { - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - } - function emitTaggedTemplateExpression(node) { - if (languageVersion >= 2) { - emit(node.tag); - write(" "); - emit(node.template); - } - else { - emitDownlevelTaggedTemplate(node); - } - } - function emitParenExpression(node) { - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 180) { - if (node.expression.kind === 177 || - node.expression.kind === 195 || - node.expression.kind === 196) { - var operand = node.expression.expression; - while (operand.kind === 177 || - operand.kind === 195 || - operand.kind === 196) { - operand = operand.expression; - } - if (operand.kind !== 185 && - operand.kind !== 183 && - operand.kind !== 182 && - operand.kind !== 181 && - operand.kind !== 186 && - operand.kind !== 175 && - !(operand.kind === 174 && node.parent.kind === 175) && - !(operand.kind === 179 && node.parent.kind === 174) && - !(operand.kind === 8 && node.parent.kind === 172)) { - emit(operand); - return; - } - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(78)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(103)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(101)); - write(" "); - emit(node.expression); - } - function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) { - if (!isCurrentFileSystemExternalModule() || node.kind !== 69 || ts.nodeIsSynthesized(node)) { - return false; - } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 218 || node.parent.kind === 169); - var targetDeclaration = isVariableDeclarationOrBindingElement - ? node.parent - : resolver.getReferencedValueDeclaration(node); - return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, true); - } - function isNameOfExportedDeclarationInNonES6Module(node) { - if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { - return false; - } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); - } - function emitPrefixUnaryExpression(node) { - var isPlusPlusOrMinusMinus = (node.operator === 41 - || node.operator === 42); - var externalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - if (externalExportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - } - var internalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedDeclarationInNonES6Module(node.operand); - if (internalExportChanged) { - emitAliasEqual(node.operand); - } - write(ts.tokenToString(node.operator)); - if (node.operand.kind === 185) { - var operand = node.operand; - if (node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) { - write(" "); - } - else if (node.operator === 36 && (operand.operator === 36 || operand.operator === 42)) { - write(" "); - } - } - emit(node.operand); - if (externalExportChanged) { - write(")"); - } - } - function emitPostfixUnaryExpression(node) { - var externalExportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - var internalExportChanged = isNameOfExportedDeclarationInNonES6Module(node.operand); - if (externalExportChanged) { - write("(" + exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - write(ts.tokenToString(node.operator)); - emit(node.operand); - if (node.operator === 41) { - write(") - 1)"); - } - else { - write(") + 1)"); - } - } - else if (internalExportChanged) { - emitAliasEqual(node.operand); - emit(node.operand); - if (node.operator === 41) { - write(" += 1"); - } - else { - write(" -= 1"); - } - } - else { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - } - function shouldHoistDeclarationInSystemJsModule(node) { - return isSourceFileLevelDeclarationInSystemJsModule(node, false); - } - function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { - if (!node || !isCurrentFileSystemExternalModule()) { - return false; - } - var current = ts.getRootDeclaration(node).parent; - while (current) { - if (current.kind === 256) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); - } - else if (ts.isDeclaration(current)) { - return false; - } - else { - current = current.parent; - } - } - } - function emitExponentiationOperator(node) { - var leftHandSideExpression = node.left; - if (node.operatorToken.kind === 60) { - var synthesizedLHS = void 0; - var shouldEmitParentheses = false; - if (ts.isElementAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(173, false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); - synthesizedLHS.expression = identifier; - if (leftHandSideExpression.argumentExpression.kind !== 8 && - leftHandSideExpression.argumentExpression.kind !== 9) { - var tempArgumentExpression = createAndRecordTempVariable(268435456); - synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, true, leftHandSideExpression.expression); - } - else { - synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; - } - write(", "); - } - else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(172, false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); - synthesizedLHS.expression = identifier; - synthesizedLHS.name = leftHandSideExpression.name; - write(", "); - } - emit(synthesizedLHS || leftHandSideExpression); - write(" = "); - write("Math.pow("); - emit(synthesizedLHS || leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - if (shouldEmitParentheses) { - write(")"); - } - } - else { - write("Math.pow("); - emit(leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - } - } - function emitAliasEqual(name) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - emitStart(specifier.name); - emitContainingModuleName(specifier); - if (languageVersion === 0 && name.text === "default") { - write('["default"]'); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - } - emitEnd(specifier.name); - write(" = "); - } - return true; - } - function emitBinaryExpression(node) { - if (languageVersion < 2 && node.operatorToken.kind === 56 && - (node.left.kind === 171 || node.left.kind === 170)) { - emitDestructuring(node, node.parent.kind === 202); - } - else { - var isAssignment = ts.isAssignmentOperator(node.operatorToken.kind); - var externalExportChanged = isAssignment && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left); - if (externalExportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.left); - write("\", "); - } - var internalExportChanged = isAssignment && - isNameOfExportedDeclarationInNonES6Module(node.left); - if (internalExportChanged) { - emitAliasEqual(node.left); - } - if (node.operatorToken.kind === 38 || node.operatorToken.kind === 60) { - emitExponentiationOperator(node); - } - else { - emit(node.left); - var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 ? " " : undefined); - write(ts.tokenToString(node.operatorToken.kind)); - var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); - emit(node.right); - decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); - } - if (externalExportChanged) { - write(")"); - } - } - } - function synthesizedNodeStartsOnNewLine(node) { - return ts.nodeIsSynthesized(node) && node.startsOnNewLine; - } - function emitConditionalExpression(node) { - emit(node.condition); - var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); - write("?"); - var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); - emit(node.whenTrue); - decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); - write(":"); - var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); - emit(node.whenFalse); - decreaseIndentIf(indentedBeforeColon, indentedAfterColon); - } - function decreaseIndentIf(value1, value2) { - if (value1) { - decreaseIndent(); - } - if (value2) { - decreaseIndent(); - } - } - function isSingleLineEmptyBlock(node) { - if (node && node.kind === 199) { - var block = node; - return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); - } - } - function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - emitToken(15, node.pos); - write(" "); - emitToken(16, node.statements.end); - return; - } - emitToken(15, node.pos); - increaseIndent(); - if (node.kind === 226) { - ts.Debug.assert(node.parent.kind === 225); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 226) { - emitTempDeclarations(true); - } - decreaseIndent(); - writeLine(); - emitToken(16, node.statements.end); - } - function emitEmbeddedStatement(node) { - if (node.kind === 199) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 180); - write(";"); - } - function emitIfStatement(node) { - var endPos = emitToken(88, node.pos); - write(" "); - endPos = emitToken(17, endPos); - emit(node.expression); - emitToken(18, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(80, node.thenStatement.end); - if (node.elseStatement.kind === 203) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - } - function emitDoStatement(node) { - emitLoop(node, emitDoStatementWorker); - } - function emitDoStatementWorker(node, loop) { - write("do"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - if (node.statement.kind === 199) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - emitLoop(node, emitWhileStatementWorker); - } - function emitWhileStatementWorker(node, loop) { - write("while ("); - emit(node.expression); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function tryEmitStartOfVariableDeclarationList(decl) { - if (shouldHoistVariable(decl, true)) { - return false; - } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072) === 0) { - for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { - var varDecl = _b[_a]; - hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); - } - return false; - } - emitStart(decl); - if (decl && languageVersion >= 2) { - if (ts.isLet(decl)) { - write("let "); - } - else if (ts.isConst(decl)) { - write("const "); - } - else { - write("var "); - } - } - else { - write("var "); - } - return true; - } - function emitVariableDeclarationListSkippingUninitializedEntries(list) { - var started = false; - for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) { - var decl = _b[_a]; - if (!decl.initializer) { - continue; - } - if (!started) { - started = true; - } - else { - write(", "); - } - emit(decl); - } - return started; - } - function shouldConvertLoopBody(node) { - return languageVersion < 2 && - (resolver.getNodeCheckFlags(node) & 65536) !== 0; - } - function emitLoop(node, loopEmitter) { - var shouldConvert = shouldConvertLoopBody(node); - if (!shouldConvert) { - loopEmitter(node, undefined); - } - else { - var loop = convertLoopBody(node); - if (node.parent.kind === 214) { - emitLabelAndColon(node.parent); - } - loopEmitter(node, loop); - } - } - function convertLoopBody(node) { - var functionName = makeUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206: - case 207: - case 208: - var initializer = node.initializer; - if (initializer && initializer.kind === 219) { - loopInitializer = node.initializer; - } - break; - } - var loopParameters; - var loopOutParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072)) { - loopParameters = []; - for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { - var varDeclaration = _b[_a]; - processVariableDeclaration(varDeclaration.name); - } - } - var bodyIsBlock = node.statement.kind === 199; - var paramList = loopParameters ? loopParameters.join(", ") : ""; - writeLine(); - write("var " + functionName + " = function(" + paramList + ")"); - var convertedOuterLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (convertedOuterLoopState) { - if (convertedOuterLoopState.argumentsName) { - convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; - } - if (convertedOuterLoopState.thisName) { - convertedLoopState.thisName = convertedOuterLoopState.thisName; - } - if (convertedOuterLoopState.hoistedLocalVariables) { - convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; - } - } - write(" {"); - writeLine(); - increaseIndent(); - if (bodyIsBlock) { - emitLines(node.statement.statements); - } - else { - emit(node.statement); - } - writeLine(); - copyLoopOutParameters(convertedLoopState, 1, true); - decreaseIndent(); - writeLine(); - write("};"); - writeLine(); - if (loopOutParameters) { - write("var "); - for (var i = 0; i < loopOutParameters.length; i++) { - if (i !== 0) { - write(", "); - } - write(loopOutParameters[i].outParamName); - } - write(";"); - writeLine(); - } - if (convertedLoopState.argumentsName) { - if (convertedOuterLoopState) { - convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; - } - else { - write("var " + convertedLoopState.argumentsName + " = arguments;"); - writeLine(); - } - } - if (convertedLoopState.thisName) { - if (convertedOuterLoopState) { - convertedOuterLoopState.thisName = convertedLoopState.thisName; - } - else { - write("var " + convertedLoopState.thisName + " = this;"); - writeLine(); - } - } - if (convertedLoopState.hoistedLocalVariables) { - if (convertedOuterLoopState) { - convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; - } - else { - write("var "); - var seen = void 0; - for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { - var id = _d[_c]; - if (!seen) { - seen = {}; - } - else { - write(", "); - } - if (!ts.hasProperty(seen, id.text)) { - emit(id); - seen[id.text] = id.text; - } - } - write(";"); - writeLine(); - } - } - var currentLoopState = convertedLoopState; - convertedLoopState = convertedOuterLoopState; - return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function processVariableDeclaration(name) { - if (name.kind === 69) { - var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) - ? getGeneratedNameForNode(name) - : name.text; - loopParameters.push(nameText); - if (resolver.getNodeCheckFlags(name.parent) & 2097152) { - var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; - (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); - } - } - else { - for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { - var element = _b[_a]; - processVariableDeclaration(element.name); - } - } - } - } - function emitNormalLoopBody(node, emitAsEmbeddedStatement) { - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 | 4; - } - if (emitAsEmbeddedStatement) { - emitEmbeddedStatement(node.statement); - } - else if (node.statement.kind === 199) { - emitLines(node.statement.statements); - } - else { - writeLine(); - emit(node.statement); - } - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function copyLoopOutParameters(state, copyDirection, emitAsStatements) { - if (state.loopOutParameters) { - for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { - var outParam = _b[_a]; - if (copyDirection === 0) { - emitIdentifier(outParam.originalName); - write(" = " + outParam.outParamName); - } - else { - write(outParam.outParamName + " = "); - emitIdentifier(outParam.originalName); - } - if (emitAsStatements) { - write(";"); - writeLine(); - } - else { - write(", "); - } - } - } - } - function emitConvertedLoopCall(loop, emitAsBlock) { - if (emitAsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } - var isSimpleLoop = !(loop.state.nonLocalJumps & ~4) && - !loop.state.labeledNonLocalBreaks && - !loop.state.labeledNonLocalContinues; - var loopResult = makeUniqueName("state"); - if (!isSimpleLoop) { - write("var " + loopResult + " = "); - } - write(loop.functionName + "(" + loop.paramList + ");"); - writeLine(); - copyLoopOutParameters(loop.state, 0, true); - if (!isSimpleLoop) { - writeLine(); - if (loop.state.nonLocalJumps & 8) { - write("if (typeof " + loopResult + " === \"object\") "); - if (convertedLoopState) { - write("return " + loopResult + ";"); - convertedLoopState.nonLocalJumps |= 8; - } - else { - write("return " + loopResult + ".value;"); - } - writeLine(); - } - if (loop.state.nonLocalJumps & 2) { - write("if (" + loopResult + " === \"break\") break;"); - writeLine(); - } - emitDispatchTableForLabeledJumps(loopResult, loop.state, convertedLoopState); - } - if (emitAsBlock) { - writeLine(); - decreaseIndent(); - write("}"); - } - function emitDispatchTableForLabeledJumps(loopResultVariable, currentLoop, outerLoop) { - if (!currentLoop.labeledNonLocalBreaks && !currentLoop.labeledNonLocalContinues) { - return; - } - write("switch(" + loopResultVariable + ") {"); - increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, false, loopResultVariable, outerLoop); - decreaseIndent(); - writeLine(); - write("}"); - } - function emitDispatchEntriesForLabeledJumps(table, isBreak, loopResultVariable, outerLoop) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - writeLine(); - write("case \"" + labelMarker + "\": "); - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - if (isBreak) { - write("break "); - } - else { - write("continue "); - } - write(labelText + ";"); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - write("return " + loopResultVariable + ";"); - } - } - } - } - function emitForStatement(node) { - emitLoop(node, emitForStatementWorker); - } - function emitForStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - if (node.initializer && node.initializer.kind === 219) { - var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); - if (startIsEmitted) { - emitCommaList(variableDeclarationList.declarations); - } - else { - emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList); - } - } - else if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.incrementor); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 208) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } - else { - emitLoop(node, emitForInOrForOfStatementWorker); - } - } - function emitForInOrForOfStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - if (node.initializer.kind === 219) { - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList); - emit(variableDeclarationList.declarations[0]); - } - } - else { - emit(node.initializer); - } - if (node.kind === 207) { - write(" in "); - } - else { - write(" of "); - } - emit(node.expression); - emitToken(18, node.expression.end); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function emitDownLevelForOfStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - var counter = createTempVariable(268435456); - var rhsReference = ts.createSynthesizedNode(69); - rhsReference.text = node.expression.kind === 69 ? - makeUniqueName(node.expression.text) : - makeTempVariableName(0); - emitStart(node.expression); - write("var "); - emitNodeWithoutSourceMap(counter); - write(" = 0"); - emitEnd(node.expression); - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - write("; "); - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write(" < "); - emitNodeWithCommentsAndWithoutSourcemap(rhsReference); - write(".length"); - emitEnd(node.expression); - write("; "); - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write("++"); - emitEnd(node.expression); - emitToken(18, node.expression.end); - write(" {"); - writeLine(); - increaseIndent(); - var rhsIterationValue = createElementAccessExpression(rhsReference, counter); - emitStart(node.initializer); - if (node.initializer.kind === 219) { - write("var "); - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length > 0) { - var declaration = variableDeclarationList.declarations[0]; - if (ts.isBindingPattern(declaration.name)) { - emitDestructuring(declaration, false, rhsIterationValue); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(declaration); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - emitNodeWithoutSourceMap(createTempVariable(0)); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - var assignmentExpression = createBinaryExpression(node.initializer, 56, rhsIterationValue, false); - if (node.initializer.kind === 170 || node.initializer.kind === 171) { - emitDestructuring(assignmentExpression, true, undefined); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression); - } - } - emitEnd(node.initializer); - write(";"); - if (loop) { - writeLine(); - emitConvertedLoopCall(loop, false); - } - else { - emitNormalLoopBody(node, false); - } - writeLine(); - decreaseIndent(); - write("}"); - } - function emitBreakOrContinueStatement(node) { - if (convertedLoopState) { - var jump = node.kind === 210 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - write("return "); - copyLoopOutParameters(convertedLoopState, 1, false); - if (!node.label) { - if (node.kind === 210) { - convertedLoopState.nonLocalJumps |= 2; - write("\"break\";"); - } - else { - convertedLoopState.nonLocalJumps |= 4; - write("\"continue\";"); - } - } - else { - var labelMarker = void 0; - if (node.kind === 210) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); - } - write("\"" + labelMarker + "\";"); - } - return; - } - } - emitToken(node.kind === 210 ? 70 : 75, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - if (convertedLoopState) { - convertedLoopState.nonLocalJumps |= 8; - write("return { value: "); - if (node.expression) { - emit(node.expression); - } - else { - write("void 0"); - } - write(" };"); - return; - } - emitToken(94, node.pos); - emitOptional(" ", node.expression); - write(";"); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(96, node.pos); - write(" "); - emitToken(17, endPos); - emit(node.expression); - endPos = emitToken(18, node.expression.end); - write(" "); - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps |= 2; - } - emitCaseBlock(node.caseBlock, endPos); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function emitCaseBlock(node, startPos) { - emitToken(15, startPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(16, node.clauses.end); - } - function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); - } - function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 249) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(72, node.pos); - write(" "); - emitToken(17, endPos); - emit(node.variableDeclaration); - emitToken(18, node.variableDeclaration ? node.variableDeclaration.end : endPos); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(76, node.pos); - write(";"); - } - function emitLabelAndColon(node) { - emit(node.label); - write(": "); - } - function emitLabeledStatement(node) { - if (!ts.isIterationStatement(node.statement, false) || !shouldConvertLoopBody(node.statement)) { - emitLabelAndColon(node); - } - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - emit(node.statement); - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 225); - return node; - } - function emitContainingModuleName(node) { - var container = getContainingModule(node); - write(container ? getGeneratedNameForNode(container) : "exports"); - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1) { - var container = getContainingModule(node); - if (container) { - write(getGeneratedNameForNode(container)); - write("."); - } - else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - emitNodeWithCommentsAndWithoutSourcemap(node.name); - emitEnd(node.name); - } - function createVoidZero() { - var zero = ts.createSynthesizedNode(8); - zero.text = "0"; - var result = ts.createSynthesizedNode(183); - result.expression = zero; - return result; - } - function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 256) { - ts.Debug.assert(!!(node.flags & 512) || node.kind === 235); - if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { - if (!isEs6Module) { - if (languageVersion !== 0) { - write('Object.defineProperty(exports, "__esModule", { value: true });'); - writeLine(); - } - else { - write("exports.__esModule = true;"); - writeLine(); - } - } - } - } - } - function emitExportMemberAssignment(node) { - if (node.flags & 1) { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { - write(exportFunctionForFile + "(\""); - if (node.flags & 512) { - write("default"); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - write("\", "); - emitDeclarationName(node); - write(")"); - } - else { - if (node.flags & 512) { - emitEs6ExportDefaultCompat(node); - if (languageVersion === 0) { - write('exports["default"]'); - } - else { - write("exports.default"); - } - } - else { - emitModuleMemberName(node); - } - write(" = "); - emitDeclarationName(node); - } - emitEnd(node); - write(";"); - } - } - function emitExportMemberAssignments(name) { - if (modulekind === ts.ModuleKind.System) { - return; - } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - writeLine(); - emitStart(specifier.name); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - emitEnd(specifier.name); - write(" = "); - emitExpressionIdentifier(name); - write(";"); - } - } - } - function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === ts.ModuleKind.System); - if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { - return; - } - writeLine(); - emitStart(specifier.name); - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write("\", "); - emitExpressionIdentifier(specifier.propertyName || specifier.name); - write(")"); - emitEnd(specifier.name); - write(";"); - } - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { - if (shouldEmitCommaBeforeAssignment) { - write(", "); - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(name); - write("\", "); - } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 218 || name.parent.kind === 169); - emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); - withTemporaryNoSourceMap(function () { - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - }); - emitEnd(nodeForSourceMap, true); - if (exportChanged) { - write(")"); - } - } - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { - var identifier = createTempVariable(0); - if (!canDefineTempVariablesInPlace) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); - return identifier; - } - function isFirstVariableDeclaration(root) { - return root.kind === 218 && - root.parent.kind === 219 && - root.parent.declarations[0] === root; - } - function emitDestructuring(root, isAssignmentExpressionStatement, value) { - var emitCount = 0; - var canDefineTempVariablesInPlace = false; - if (root.kind === 218) { - var isExported = ts.getCombinedNodeFlags(root) & 1; - var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); - canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; - } - else if (root.kind === 142) { - canDefineTempVariablesInPlace = true; - } - if (root.kind === 187) { - emitAssignmentExpression(root); - } - else { - ts.Debug.assert(!isAssignmentExpressionStatement); - if (isFirstVariableDeclaration(root)) { - sourceMap.changeEmitSourcePos(); - } - emitBindingElement(root, value); - } - function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { - if (expr.kind === 69 && reuseIdentifierExpressions) { - return expr; - } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); - emitCount++; - return identifier; - } - function createDefaultValueCheck(value, defaultValue, sourceMapNode) { - value = ensureIdentifier(value, true, sourceMapNode); - var equals = ts.createSynthesizedNode(187); - equals.left = value; - equals.operatorToken = ts.createSynthesizedNode(32); - equals.right = createVoidZero(); - return createConditionalExpression(equals, defaultValue, value); - } - function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(188); - cond.condition = condition; - cond.questionToken = ts.createSynthesizedNode(53); - cond.whenTrue = whenTrue; - cond.colonToken = ts.createSynthesizedNode(54); - cond.whenFalse = whenFalse; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createSynthesizedNode(8); - node.text = "" + value; - return node; - } - function createPropertyAccessForDestructuringProperty(object, propName) { - var index; - var nameIsComputed = propName.kind === 140; - if (nameIsComputed) { - index = ensureIdentifier(propName.expression, false, propName); - } - else { - index = ts.createSynthesizedNode(propName.kind); - index.text = ts.unescapeIdentifier(propName.text); - } - return !nameIsComputed && index.kind === 69 - ? createPropertyAccessExpression(object, index) - : createElementAccessExpression(object, index); - } - function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(174); - var sliceIdentifier = ts.createSynthesizedNode(69); - sliceIdentifier.text = "slice"; - call.expression = createPropertyAccessExpression(value, sliceIdentifier); - call.arguments = ts.createSynthesizedNodeArray(); - call.arguments[0] = createNumericLiteral(sliceIndex); - return call; - } - function emitObjectLiteralAssignment(target, value, sourceMapNode) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value, true, sourceMapNode); - } - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var p = properties_5[_a]; - if (p.kind === 253 || p.kind === 254) { - var propName = p.name; - var target_1 = p.kind === 254 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, sourceMapNode) { - var elements = target.elements; - if (elements.length !== 1) { - value = ensureIdentifier(value, true, sourceMapNode); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 193) { - if (e.kind !== 191) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); - } - else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); - } - } - } - } - function emitDestructuringAssignment(target, value, sourceMapNode) { - if (target.kind === 254) { - if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); - } - target = target.name; - } - else if (target.kind === 187 && target.operatorToken.kind === 56) { - value = createDefaultValueCheck(value, target.right, sourceMapNode); - target = target.left; - } - if (target.kind === 171) { - emitObjectLiteralAssignment(target, value, sourceMapNode); - } - else if (target.kind === 170) { - emitArrayLiteralAssignment(target, value, sourceMapNode); - } - else { - emitAssignment(target, value, emitCount > 0, sourceMapNode); - emitCount++; - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) { - emit(value); - } - else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); - } - else { - if (root.parent.kind !== 178) { - write("("); - } - value = ensureIdentifier(value, true, root); - emitDestructuringAssignment(target, value, root); - write(", "); - emit(value); - if (root.parent.kind !== 178) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - if (target.initializer) { - value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; - } - else if (!value) { - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0, target); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (pattern.kind === 167) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); - } - else if (element.kind !== 193) { - if (!element.dotDotDotToken) { - emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); - } - else if (i === numElements - 1) { - emitBindingElement(element, createSliceCall(value, i)); - } - } - } - } - else { - emitAssignment(target.name, value, emitCount > 0, target); - emitCount++; - } - } - } - function emitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name)) { - var isExported = ts.getCombinedNodeFlags(node) & 1; - if (languageVersion >= 2 && (!isExported || modulekind === ts.ModuleKind.ES6)) { - var isTopLevelDeclarationInSystemModule = modulekind === ts.ModuleKind.System && - shouldHoistVariable(node, true); - if (isTopLevelDeclarationInSystemModule) { - write("("); - } - emit(node.name); - emitOptional(" = ", node.initializer); - if (isTopLevelDeclarationInSystemModule) { - write(")"); - } - } - else { - emitDestructuring(node, false); - } - } - else { - var initializer = node.initializer; - if (!initializer && - languageVersion < 2 && - node.name.kind === 69) { - var container = ts.getEnclosingBlockScopeContainer(node); - var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || - (isCapturedInFunction && isDeclaredInLoop && container.kind === 199 && ts.isIterationStatement(container.parent, false)); - var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 && - !emittedAsTopLevel; - var emitExplicitInitializer = emittedAsNestedLetDeclaration && - container.kind !== 207 && - container.kind !== 208 && - (!resolver.isDeclarationWithCollidingName(node) || - (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, false))); - if (emitExplicitInitializer) { - initializer = createVoidZero(); - } - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(node.name); - write("\", "); - } - emitModuleMemberName(node); - emitOptional(" = ", initializer); - if (exportChanged) { - write(")"); - } - } - } - function emitExportVariableAssignments(node) { - if (node.kind === 193) { - return; - } - var name = node.name; - if (name.kind === 69) { - emitExportMemberAssignments(name); - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, emitExportVariableAssignments); - } - } - function isES6ExportedDeclaration(node) { - return !!(node.flags & 1) && - modulekind === ts.ModuleKind.ES6 && - node.parent.kind === 256; - } - function emitVariableStatement(node) { - var startIsEmitted = false; - if (node.flags & 1) { - if (isES6ExportedDeclaration(node)) { - write("export "); - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - } - else { - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - if (startIsEmitted) { - emitCommaList(node.declarationList.declarations); - write(";"); - } - else { - var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); - if (atLeastOneItem) { - write(";"); - } - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); - } - } - function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - if (!(node.flags & 1)) { - return true; - } - if (isES6ExportedDeclaration(node)) { - return true; - } - for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { - var declaration = _b[_a]; - if (declaration.initializer) { - return true; - } - } - return false; - } - function emitParameter(node) { - if (languageVersion < 2) { - if (ts.isBindingPattern(node.name)) { - var name_29 = createTempVariable(0); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name_29); - emit(name_29); - } - else { - emit(node.name); - } - } - else { - if (node.dotDotDotToken) { - write("..."); - } - emit(node.name); - emitOptional(" = ", node.initializer); - } - } - function emitDefaultValueAssignments(node) { - if (languageVersion < 2) { - var tempIndex_1 = 0; - ts.forEach(node.parameters, function (parameter) { - if (parameter.dotDotDotToken) { - return; - } - var paramName = parameter.name, initializer = parameter.initializer; - if (ts.isBindingPattern(paramName)) { - var hasBindingElements = paramName.elements.length > 0; - if (hasBindingElements || initializer) { - writeLine(); - write("var "); - if (hasBindingElements) { - emitDestructuring(parameter, false, tempParameters[tempIndex_1]); - } - else { - emit(tempParameters[tempIndex_1]); - write(" = "); - emit(initializer); - } - write(";"); - } - tempIndex_1++; - } - else if (initializer) { - writeLine(); - emitStart(parameter); - write("if ("); - emitNodeWithoutSourceMap(paramName); - write(" === void 0)"); - emitEnd(parameter); - write(" { "); - emitStart(parameter); - emitNodeWithCommentsAndWithoutSourcemap(paramName); - write(" = "); - emitNodeWithCommentsAndWithoutSourcemap(initializer); - emitEnd(parameter); - write("; }"); - } - }); - } - } - function emitRestParameter(node) { - if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - if (ts.isBindingPattern(restParam.name)) { - return; - } - var tempName = createTempVariable(268435456).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - write(node.kind === 149 ? "get " : "set "); - emit(node.name); - emitSignatureAndBody(node); - } - function shouldEmitAsArrowFunction(node) { - return node.kind === 180 && languageVersion >= 2; - } - function emitDeclarationName(node) { - if (node.name) { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - else { - write(getGeneratedNameForNode(node)); - } - } - function shouldEmitFunctionName(node) { - if (node.kind === 179) { - return !!node.name; - } - if (node.kind === 220) { - return !!node.name || modulekind !== ts.ModuleKind.ES6; - } - } - function emitFunctionDeclaration(node) { - if (ts.nodeIsMissing(node.body)) { - return emitCommentsOnNotEmittedNode(node); - } - var kind = node.kind, parent = node.parent; - if (kind !== 147 && - kind !== 146 && - parent && - parent.kind !== 253 && - parent.kind !== 174 && - parent.kind !== 170) { - emitLeadingComments(node); - } - emitStart(node); - if (!shouldEmitAsArrowFunction(node)) { - if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512) { - write("default "); - } - } - write("function"); - if (languageVersion >= 2 && node.asteriskToken) { - write("*"); - } - write(" "); - } - if (shouldEmitFunctionName(node)) { - emitDeclarationName(node); - } - emitSignatureAndBody(node); - if (modulekind !== ts.ModuleKind.ES6 && kind === 220 && parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - emitEnd(node); - if (kind !== 147 && - kind !== 146 && - kind !== 180) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; - var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; - emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); - } - write(")"); - decreaseIndent(); - } - function emitSignatureParametersForArrow(node) { - if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { - emit(node.parameters[0]); - return; - } - emitSignatureParameters(node); - } - function emitAsyncFunctionBodyForES6(node) { - var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 180; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; - if (!isArrowFunction) { - write(" {"); - increaseIndent(); - writeLine(); - if (resolver.getNodeCheckFlags(node) & 4096) { - writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); - writeLine(); - } - else if (resolver.getNodeCheckFlags(node) & 2048) { - write("const _super = name => super[name];"); - writeLine(); - } - write("return"); - } - write(" __awaiter(this"); - if (hasLexicalArguments) { - write(", arguments, "); - } - else { - write(", void 0, "); - } - if (languageVersion >= 2 || !promiseConstructor) { - write("void 0"); - } - else { - emitEntityNameAsExpression(promiseConstructor, false); - } - write(", function* ()"); - emitFunctionBody(node); - write(")"); - if (!isArrowFunction) { - write(";"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitFunctionBody(node) { - if (!node.body) { - write(" { }"); - } - else { - if (node.body.kind === 199) { - emitBlockFunctionBody(node, node.body); - } - else { - emitExpressionFunctionBody(node, node.body); - } - } - } - function emitSignatureAndBody(node) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - if (shouldEmitAsArrowFunction(node)) { - emitSignatureParametersForArrow(node); - write(" =>"); - } - else { - emitSignatureParameters(node); - } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAsyncFunctionBodyForES6(node); - } - else { - emitFunctionBody(node); - } - if (!isES6ExportedDeclaration(node)) { - emitExportMemberAssignment(node); - } - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitFunctionBodyPreamble(node) { - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - } - function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 || node.flags & 256) { - emitDownLevelExpressionFunctionBody(node, body); - return; - } - write(" "); - var current = body; - while (current.kind === 177) { - current = current.expression; - } - emitParenthesizedIf(body, current.kind === 171); - } - function emitDownLevelExpressionFunctionBody(node, body) { - write(" {"); - increaseIndent(); - var outPos = writer.getTextPos(); - emitDetachedCommentsAndUpdateCommentsInfo(node.body); - emitFunctionBodyPreamble(node); - var preambleEmitted = writer.getTextPos() !== outPos; - decreaseIndent(); - if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) { - write(" "); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTempDeclarations(false); - write(" "); - } - else { - increaseIndent(); - writeLine(); - emitLeadingComments(node.body); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTrailingComments(node.body); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - } - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - function emitBlockFunctionBody(node, body) { - write(" {"); - var initialTextPos = writer.getTextPos(); - increaseIndent(); - emitDetachedCommentsAndUpdateCommentsInfo(body.statements); - var startIndex = emitDirectivePrologues(body.statements, true); - emitFunctionBodyPreamble(node); - decreaseIndent(); - var preambleEmitted = writer.getTextPos() !== initialTextPos; - if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { - var statement = _b[_a]; - write(" "); - emit(statement); - } - emitTempDeclarations(false); - write(" "); - emitLeadingCommentsOfPosition(body.statements.end); - } - else { - increaseIndent(); - emitLinesStartingAt(body.statements, startIndex); - emitTempDeclarations(true); - writeLine(); - emitLeadingCommentsOfPosition(body.statements.end); - decreaseIndent(); - } - emitToken(16, body.statements.end); - } - function getSuperCallAtGivenIndex(ctor, index) { - if (!ctor.body) { - return undefined; - } - var statements = ctor.body.statements; - if (!statements || index >= statements.length) { - return undefined; - } - var statement = statements[index]; - if (statement.kind === 202) { - return ts.isSuperCallExpression(statement.expression) ? statement : undefined; - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 92) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNodeWithoutSourceMap(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - if (memberName.kind === 9 || memberName.kind === 8) { - write("["); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - write("]"); - } - else if (memberName.kind === 140) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - } - } - function getInitializedProperties(node, isStatic) { - var properties = []; - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 145 && isStatic === ((member.flags & 32) !== 0) && member.initializer) { - properties.push(member); - } - } - return properties; - } - function emitPropertyDeclarations(node, properties) { - for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { - var property = properties_6[_a]; - emitPropertyDeclaration(node, property); - } - } - function emitPropertyDeclaration(node, property, receiver, isExpression) { - writeLine(); - emitLeadingComments(property); - emitStart(property); - emitStart(property.name); - if (receiver) { - write(receiver); - } - else { - if (property.flags & 32) { - emitDeclarationName(node); - } - else { - write("this"); - } - } - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - emit(property.initializer); - if (!isExpression) { - write(";"); - } - emitEnd(property); - emitTrailingComments(property); - } - function emitMemberFunctionsForES5AndLower(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 198) { - writeLine(); - write(";"); - } - else if (member.kind === 147 || node.kind === 146) { - if (!member.body) { - return emitCommentsOnNotEmittedNode(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitClassMemberPrefix(node, member); - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitFunctionDeclaration(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 149 || member.kind === 150) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitMemberFunctionsForES6AndHigher(node) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.kind === 147 || node.kind === 146) && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - else if (member.kind === 147 || - member.kind === 149 || - member.kind === 150) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - if (member.flags & 32) { - write("static "); - } - if (member.kind === 149) { - write("get "); - } - else if (member.kind === 150) { - write("set "); - } - if (member.asteriskToken) { - write("*"); - } - emit(member.name); - emitSignatureAndBody(member); - emitEnd(member); - emitTrailingComments(member); - } - else if (member.kind === 198) { - writeLine(); - write(";"); - } - } - } - function emitConstructor(node, baseTypeElement) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - emitConstructorWorker(node, baseTypeElement); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitConstructorWorker(node, baseTypeElement) { - var hasInstancePropertyWithInitializer = false; - ts.forEach(node.members, function (member) { - if (member.kind === 148 && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - if (member.kind === 145 && member.initializer && (member.flags & 32) === 0) { - hasInstancePropertyWithInitializer = true; - } - }); - var ctor = ts.getFirstConstructorWithBody(node); - if (languageVersion >= 2 && !ctor && !hasInstancePropertyWithInitializer) { - return; - } - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - if (languageVersion < 2) { - write("function "); - emitDeclarationName(node); - emitSignatureParameters(ctor); - } - else { - write("constructor"); - if (ctor) { - emitSignatureParameters(ctor); - } - else { - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } - } - } - var startIndex = 0; - write(" {"); - increaseIndent(); - if (ctor) { - startIndex = emitDirectivePrologues(ctor.body.statements, true); - emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - var superCall; - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeElement) { - superCall = getSuperCallAtGivenIndex(ctor, startIndex); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeElement) { - writeLine(); - emitStart(baseTypeElement); - if (languageVersion < 2) { - write("_super.apply(this, arguments);"); - } - else { - write("super(...args);"); - } - emitEnd(baseTypeElement); - } - } - emitPropertyDeclarations(node, getInitializedProperties(node, false)); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) { - statements = statements.slice(1); - } - emitLinesStartingAt(statements, startIndex); - } - emitTempDeclarations(true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(16, ctor ? ctor.body.statements.end : node.members.end); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - } - function emitClassExpression(node) { - return emitClassLikeDeclaration(node); - } - function emitClassDeclaration(node) { - return emitClassLikeDeclaration(node); - } - function emitClassLikeDeclaration(node) { - if (languageVersion < 2) { - emitClassLikeDeclarationBelowES6(node); - } - else { - emitClassLikeDeclarationForES6AndHigher(node); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - } - function emitClassLikeDeclarationForES6AndHigher(node) { - var decoratedClassAlias; - var isHoistedDeclarationInSystemModule = shouldHoistDeclarationInSystemJsModule(node); - var isDecorated = ts.nodeIsDecorated(node); - var rewriteAsClassExpression = isDecorated || isHoistedDeclarationInSystemModule; - if (node.kind === 221) { - if (rewriteAsClassExpression) { - if (isDecorated && resolver.getNodeCheckFlags(node) & 524288) { - decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); - decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; - } - if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) { - write("export "); - } - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } - if (decoratedClassAlias !== undefined) { - write("" + decoratedClassAlias); - } - else { - emitDeclarationName(node); - } - write(" = "); - } - else if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512) { - write("default "); - } - } - } - var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; - var generatedName; - if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); - var synthesizedNode = ts.createSynthesizedNode(69); - synthesizedNode.text = generatedName; - recordTempDeclaration(synthesizedNode); - write("("); - increaseIndent(); - emit(synthesizedNode); - write(" = "); - } - write("class"); - if (node.name || (node.flags & 512 && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !rewriteAsClassExpression)) { - write(" "); - emitDeclarationName(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write(" extends "); - emit(baseTypeNode.expression); - } - write(" {"); - increaseIndent(); - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES6AndHigher(node); - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - if (rewriteAsClassExpression) { - if (decoratedClassAlias !== undefined) { - write(";"); - writeLine(); - if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { - write("export "); - } - write("let "); - emitDeclarationName(node); - write(" = " + decoratedClassAlias); - } - decoratedClassAliases[ts.getNodeId(node)] = undefined; - write(";"); - } - if (isClassExpressionWithStaticProperties) { - for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { - var property = staticProperties_1[_a]; - write(","); - writeLine(); - emitPropertyDeclaration(node, property, generatedName, true); - } - write(","); - writeLine(); - write(generatedName); - decreaseIndent(); - write(")"); - } - else { - writeLine(); - emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node, decoratedClassAlias); - } - if (!(node.flags & 1)) { - return; - } - if (modulekind !== ts.ModuleKind.ES6) { - emitExportMemberAssignment(node); - } - else { - if (node.flags & 512) { - if (isDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - else if (node.parent.kind !== 256) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); - } - } - } - function emitClassLikeDeclarationBelowES6(node) { - var isES6ExportedClass = isES6ExportedDeclaration(node); - if (node.kind === 221) { - if (isES6ExportedClass && !(node.flags & 512)) { - write("export "); - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - write("var "); - } - emitDeclarationName(node); - write(" = "); - } - write("(function ("); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - var saveConvertedLoopState = convertedLoopState; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - computedPropertyNamesToGeneratedNames = undefined; - increaseIndent(); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emitDeclarationName(node); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, true)); - writeLine(); - emitDecoratorsOfClass(node, undefined); - writeLine(); - emitToken(16, node.members.end, function () { - write("return "); - emitDeclarationName(node); - }); - write(";"); - emitTempDeclarations(true); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames; - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - emitStart(node); - write("("); - if (baseTypeNode) { - emit(baseTypeNode.expression); - } - write("))"); - if (node.kind === 221) { - write(";"); - } - emitEnd(node); - if (node.kind === 221 && !isES6ExportedClass) { - emitExportMemberAssignment(node); - } - else if (isES6ExportedClass && (node.flags & 512)) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - function emitClassMemberPrefix(node, member) { - emitDeclarationName(node); - if (!(member.flags & 32)) { - write(".prototype"); - } - } - function emitDecoratorsOfClass(node, decoratedClassAlias) { - emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 32); - emitDecoratorsOfConstructor(node, decoratedClassAlias); - } - function emitDecoratorsOfConstructor(node, decoratedClassAlias) { - var decorators = node.decorators; - var constructor = ts.getFirstConstructorWithBody(node); - var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); - if (!decorators && !firstParameterDecorator) { - return; - } - writeLine(); - emitStart(node.decorators || firstParameterDecorator); - emitDeclarationName(node); - if (decoratedClassAlias !== undefined) { - write(" = " + decoratedClassAlias); - } - write(" = __decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); - } - emitSerializedTypeMetadata(node, argumentsWritten >= 0); - decreaseIndent(); - writeLine(); - write("], "); - emitDeclarationName(node); - write(")"); - emitEnd(node.decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - function emitDecoratorsOfMembers(node, staticFlag) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.flags & 32) !== staticFlag) { - continue; - } - if (!ts.nodeCanBeDecorated(member)) { - continue; - } - var decorators = void 0; - var functionLikeMember = void 0; - if (ts.isAccessor(member)) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member !== accessors.firstAccessor) { - continue; - } - decorators = accessors.firstAccessor.decorators; - if (!decorators && accessors.secondAccessor) { - decorators = accessors.secondAccessor.decorators; - } - functionLikeMember = accessors.setAccessor; - } - else { - decorators = member.decorators; - if (member.kind === 147) { - functionLikeMember = member; - } - } - var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); - if (!decorators && !firstParameterDecorator) { - continue; - } - writeLine(); - emitStart(decorators || firstParameterDecorator); - write("__decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); - } - emitSerializedTypeMetadata(member, argumentsWritten > 0); - decreaseIndent(); - writeLine(); - write("], "); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - if (languageVersion > 0) { - if (member.kind !== 145) { - write(", null"); - } - else { - write(", void 0"); - } - } - write(")"); - emitEnd(decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - } - function emitDecoratorsOfParameters(node, leadingComma) { - var argumentsWritten = 0; - if (node) { - var parameterIndex_1 = 0; - for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { - var parameter = _b[_a]; - if (ts.nodeIsDecorated(parameter)) { - var decorators = parameter.decorators; - argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - write("__param(" + parameterIndex_1 + ", "); - emit(decorator.expression); - write(")"); - }); - leadingComma = true; - } - parameterIndex_1++; - } - } - return argumentsWritten; - } - function shouldEmitTypeMetadata(node) { - switch (node.kind) { - case 147: - case 149: - case 150: - case 145: - return true; - } - return false; - } - function shouldEmitReturnTypeMetadata(node) { - switch (node.kind) { - case 147: - return true; - } - return false; - } - function shouldEmitParamTypesMetadata(node) { - switch (node.kind) { - case 221: - case 147: - case 150: - return true; - } - return false; - } - function emitSerializedTypeOfNode(node) { - switch (node.kind) { - case 221: - write("Function"); - return; - case 145: - emitSerializedTypeNode(node.type); - return; - case 142: - emitSerializedTypeNode(node.type); - return; - case 149: - emitSerializedTypeNode(node.type); - return; - case 150: - emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - return; - } - if (ts.isFunctionLike(node)) { - write("Function"); - return; - } - write("void 0"); - } - function emitSerializedTypeNode(node) { - if (node) { - switch (node.kind) { - case 103: - write("void 0"); - return; - case 164: - emitSerializedTypeNode(node.type); - return; - case 156: - case 157: - write("Function"); - return; - case 160: - case 161: - write("Array"); - return; - case 154: - case 120: - write("Boolean"); - return; - case 132: - case 166: - write("String"); - return; - case 130: - write("Number"); - return; - case 133: - write("Symbol"); - return; - case 155: - emitSerializedTypeReferenceNode(node); - return; - case 158: - case 159: - case 162: - case 163: - case 117: - case 165: - break; - default: - ts.Debug.fail("Cannot serialize unexpected type node."); - break; - } - } - write("Object"); - } - function emitSerializedTypeReferenceNode(node) { - var location = node.parent; - while (ts.isDeclaration(location) || ts.isTypeNode(location)) { - location = location.parent; - } - var typeName = ts.cloneEntityName(node.typeName, location); - var result = resolver.getTypeReferenceSerializationKind(typeName); - switch (result) { - case ts.TypeReferenceSerializationKind.Unknown: - var temp = createAndRecordTempVariable(0); - write("(typeof ("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(typeName, true); - write(") === 'function' && "); - emitNodeWithoutSourceMap(temp); - write(") || Object"); - break; - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - emitEntityNameAsExpression(typeName, false); - break; - case ts.TypeReferenceSerializationKind.VoidType: - write("void 0"); - break; - case ts.TypeReferenceSerializationKind.BooleanType: - write("Boolean"); - break; - case ts.TypeReferenceSerializationKind.NumberLikeType: - write("Number"); - break; - case ts.TypeReferenceSerializationKind.StringLikeType: - write("String"); - break; - case ts.TypeReferenceSerializationKind.ArrayLikeType: - write("Array"); - break; - case ts.TypeReferenceSerializationKind.ESSymbolType: - if (languageVersion < 2) { - write("typeof Symbol === 'function' ? Symbol : Object"); - } - else { - write("Symbol"); - } - break; - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - write("Function"); - break; - case ts.TypeReferenceSerializationKind.ObjectType: - write("Object"); - break; - } - } - function emitSerializedParameterTypesOfNode(node) { - if (node) { - var valueDeclaration = void 0; - if (node.kind === 221) { - valueDeclaration = ts.getFirstConstructorWithBody(node); - } - else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { - valueDeclaration = node; - } - if (valueDeclaration) { - var parameters = valueDeclaration.parameters; - var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { - write(", "); - } - if (parameters[i].dotDotDotToken) { - var parameterType = parameters[i].type; - if (parameterType && parameterType.kind === 160) { - parameterType = parameterType.elementType; - } - else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { - parameterType = parameterType.typeArguments[0]; - } - else { - parameterType = undefined; - } - emitSerializedTypeNode(parameterType); - } - else { - emitSerializedTypeOfNode(parameters[i]); - } - } - } - } - } - } - function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node)) { - if (node.type) { - emitSerializedTypeNode(node.type); - return; - } - else if (ts.isAsyncFunctionLike(node)) { - write("Promise"); - return; - } - } - write("void 0"); - } - function emitSerializedTypeMetadata(node, writeComma) { - var argumentsWritten = 0; - if (compilerOptions.emitDecoratorMetadata) { - if (shouldEmitTypeMetadata(node)) { - if (writeComma) { - write(", "); - } - writeLine(); - write("__metadata('design:type', "); - emitSerializedTypeOfNode(node); - write(")"); - argumentsWritten++; - } - if (shouldEmitParamTypesMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:paramtypes', ["); - emitSerializedParameterTypesOfNode(node); - write("])"); - argumentsWritten++; - } - if (shouldEmitReturnTypeMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:returntype', "); - emitSerializedReturnTypeOfNode(node); - write(")"); - argumentsWritten++; - } - } - return argumentsWritten; - } - function emitInterfaceDeclaration(node) { - emitCommentsOnNotEmittedNode(node); - } - function shouldEmitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; - } - function emitEnumDeclaration(node) { - if (!shouldEmitEnumDeclaration(node)) { - return; - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - var isES6ExportedEnum = isES6ExportedDeclaration(node); - if (!(node.flags & 1) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 224))) { - emitStart(node); - if (isES6ExportedEnum) { - write("export "); - } - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 && !shouldHoistDeclarationInSystemJsModule(node)) { - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function emitEnumMember(node) { - var enumParent = node.parent; - emitStart(node); - write(getGeneratedNameForNode(enumParent)); - write("["); - write(getGeneratedNameForNode(enumParent)); - write("["); - emitExpressionForPropertyName(node.name); - write("] = "); - writeEnumMemberDeclarationValue(node); - write("] = "); - emitExpressionForPropertyName(node.name); - emitEnd(node); - write(";"); - } - function writeEnumMemberDeclarationValue(member) { - var value = resolver.getConstantValue(member); - if (value !== undefined) { - write(value.toString()); - return; - } - else if (member.initializer) { - emit(member.initializer); - } - else { - write("undefined"); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); - } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 32768); - } - function isFirstDeclarationOfKind(node, declarations, kind) { - return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); - } - function emitModuleDeclaration(node) { - var shouldEmit = shouldEmitModuleDeclaration(node); - if (!shouldEmit) { - return emitCommentsOnNotEmittedNode(node); - } - var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); - var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); - if (emitVarForModule) { - var isES6ExportedNamespace = isES6ExportedDeclaration(node); - if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 225)) { - emitStart(node); - if (isES6ExportedNamespace) { - write("export "); - } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - } - } - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") "); - ts.Debug.assert(node.body !== undefined); - if (node.body.kind === 226) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - emit(node.body); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(16, moduleBlock.statements.end); - } - write(")("); - if ((node.flags & 1) && !isES6ExportedDeclaration(node)) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.name.kind === 69 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { - return "\"" + renamedDependencies[moduleName.text] + "\""; - } - return undefined; - } - function emitRequire(moduleName) { - if (moduleName.kind === 9) { - write("require("); - var text = tryRenameExternalModule(moduleName); - if (text) { - write(text); - } - else { - emitStart(moduleName); - emitLiteral(moduleName); - emitEnd(moduleName); - } - emitToken(18, moduleName.end); - } - else { - write("require()"); - } - } - function getNamespaceDeclarationNode(node) { - if (node.kind === 229) { - return node; - } - var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { - return importClause.namedBindings; - } - } - function isDefaultImport(node) { - return node.kind === 230 && node.importClause && !!node.importClause.name; - } - function emitExportImportAssignments(node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - emitExportMemberAssignments(node.name); - } - ts.forEachChild(node, emitExportImportAssignments); - } - function emitImportDeclaration(node) { - if (modulekind !== ts.ModuleKind.ES6) { - return emitExternalImportDeclaration(node); - } - if (node.importClause) { - var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, true); - if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { - write("import "); - emitStart(node.importClause); - if (shouldEmitDefaultBindings) { - emit(node.importClause.name); - if (shouldEmitNamedBindings) { - write(", "); - } - } - if (shouldEmitNamedBindings) { - emitLeadingComments(node.importClause.namedBindings); - emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 232) { - write("* as "); - emit(node.importClause.namedBindings.name); - } - else { - write("{ "); - emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration); - write(" }"); - } - emitEnd(node.importClause.namedBindings); - emitTrailingComments(node.importClause.namedBindings); - } - emitEnd(node.importClause); - write(" from "); - emit(node.moduleSpecifier); - write(";"); - } - } - else { - write("import "); - emit(node.moduleSpecifier); - write(";"); - } - } - function emitExternalImportDeclaration(node) { - if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 229 && (node.flags & 1) !== 0; - var namespaceDeclaration = getNamespaceDeclarationNode(node); - var varOrConst = (languageVersion <= 1) ? "var " : "const "; - if (modulekind !== ts.ModuleKind.AMD) { - emitLeadingComments(node); - emitStart(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - if (!isExportedImport) { - write(varOrConst); - } - ; - emitModuleMemberName(namespaceDeclaration); - write(" = "); - } - else { - var isNakedImport = 230 && !node.importClause; - if (!isNakedImport) { - write(varOrConst); - write(getGeneratedNameForNode(node)); - write(" = "); - } - } - emitRequire(ts.getExternalModuleName(node)); - if (namespaceDeclaration && isDefaultImport(node)) { - write(", "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - else { - if (isExportedImport) { - emitModuleMemberName(namespaceDeclaration); - write(" = "); - emit(namespaceDeclaration.name); - write(";"); - } - else if (namespaceDeclaration && isDefaultImport(node)) { - write(varOrConst); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - write(";"); - } - emitExportImportAssignments(node); - } - } - } - function emitImportEqualsDeclaration(node) { - if (ts.isExternalModuleImportEqualsDeclaration(node)) { - emitExternalImportDeclaration(node); - return; - } - if (resolver.isReferencedAliasDeclaration(node) || - (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { - emitLeadingComments(node); - emitStart(node); - var variableDeclarationIsHoisted = shouldHoistVariable(node, true); - var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, true); - if (!variableDeclarationIsHoisted) { - ts.Debug.assert(!isExported); - if (isES6ExportedDeclaration(node)) { - write("export "); - write("var "); - } - else if (!(node.flags & 1)) { - write("var "); - } - } - if (isExported) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.name); - write("\", "); - } - emitModuleMemberName(node); - write(" = "); - emit(node.moduleReference); - if (isExported) { - write(")"); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - } - function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== ts.ModuleKind.System); - if (modulekind !== ts.ModuleKind.ES6) { - if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { - emitStart(node); - var generatedName = getGeneratedNameForNode(node); - if (node.exportClause) { - if (modulekind !== ts.ModuleKind.AMD) { - write("var "); - write(generatedName); - write(" = "); - emitRequire(ts.getExternalModuleName(node)); - write(";"); - } - for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) { - var specifier = _b[_a]; - if (resolver.isValueAliasDeclaration(specifier)) { - writeLine(); - emitStart(specifier); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write(" = "); - write(generatedName); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name); - write(";"); - emitEnd(specifier); - } - } - } - else { - if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - writeLine(); - write("__export("); - if (modulekind !== ts.ModuleKind.AMD) { - emitRequire(ts.getExternalModuleName(node)); - } - else { - write(generatedName); - } - write(");"); - } - } - emitEnd(node); - } - } - else { - if (!node.exportClause || resolver.isValueAliasDeclaration(node)) { - write("export "); - if (node.exportClause) { - write("{ "); - emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emit(node.moduleSpecifier); - } - write(";"); - } - } - } - function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === ts.ModuleKind.ES6); - var needsComma = false; - for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { - var specifier = specifiers_1[_a]; - if (shouldEmit(specifier)) { - if (needsComma) { - write(", "); - } - if (specifier.propertyName) { - emit(specifier.propertyName); - write(" as "); - } - emit(specifier.name); - needsComma = true; - } - } - } - function emitExportAssignment(node) { - if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === ts.ModuleKind.ES6) { - writeLine(); - emitStart(node); - write("export default "); - var expression = node.expression; - emit(expression); - if (expression.kind !== 220 && - expression.kind !== 221) { - write(";"); - } - emitEnd(node); - } - else { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System) { - write(exportFunctionForFile + "(\"default\","); - emit(node.expression); - write(")"); - } - else { - emitEs6ExportDefaultCompat(node); - emitContainingModuleName(node); - if (languageVersion === 0) { - write('["default"] = '); - } - else { - write(".default = "); - } - emit(node.expression); - } - write(";"); - emitEnd(node); - } - } - } - function collectExternalModuleInfo(sourceFile) { - externalImports = []; - exportSpecifiers = {}; - exportEquals = undefined; - hasExportStarsToExportValues = false; - for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { - var node = _b[_a]; - switch (node.kind) { - case 230: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, true)) { - externalImports.push(node); - } - break; - case 229: - if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { - externalImports.push(node); - } - break; - case 236: - if (node.moduleSpecifier) { - if (!node.exportClause) { - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - externalImports.push(node); - } - } - else { - for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { - var specifier = _d[_c]; - var name_30 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_30] || (exportSpecifiers[name_30] = [])).push(specifier); - } - } - break; - case 235: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; - } - } - } - function emitExportStarHelper() { - if (hasExportStarsToExportValues) { - writeLine(); - write("function __export(m) {"); - increaseIndent(); - writeLine(); - write("for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function getLocalNameForExternalImport(node) { - var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); - } - if (node.kind === 230 && node.importClause) { - return getGeneratedNameForNode(node); - } - if (node.kind === 236 && node.moduleSpecifier) { - return getGeneratedNameForNode(node); - } - } - function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { - if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - return "\"" + name_31 + "\""; - } - } - var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 9) { - return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); - } - return undefined; - } - function emitVariableDeclarationsForImports() { - if (externalImports.length === 0) { - return; - } - writeLine(); - var started = false; - for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { - var importNode = externalImports_1[_a]; - var skipNode = importNode.kind === 236 || - (importNode.kind === 230 && !importNode.importClause); - if (skipNode) { - continue; - } - if (!started) { - write("var "); - started = true; - } - else { - write(", "); - } - write(getLocalNameForExternalImport(importNode)); - } - if (started) { - write(";"); - } - } - function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - if (!hasExportStarsToExportValues) { - return undefined; - } - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { - var hasExportDeclarationWithExportClause = false; - for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { - var externalImport = externalImports_2[_a]; - if (externalImport.kind === 236 && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - return emitExportStarFunction(undefined); - } - } - var exportedNamesStorageRef = makeUniqueName("exportedNames"); - writeLine(); - write("var " + exportedNamesStorageRef + " = {"); - increaseIndent(); - var started = false; - if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; i++) { - writeExportedName(exportedDeclarations[i]); - } - } - if (exportSpecifiers) { - for (var n in exportSpecifiers) { - for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) { - var specifier = _c[_b]; - writeExportedName(specifier.name); - } - } - } - for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { - var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 236) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - continue; - } - for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) { - var element = _f[_e]; - writeExportedName(element.name || element.propertyName); - } - } - decreaseIndent(); - writeLine(); - write("};"); - return emitExportStarFunction(exportedNamesStorageRef); - function emitExportStarFunction(localNames) { - var exportStarFunction = makeUniqueName("exportStar"); - writeLine(); - write("function " + exportStarFunction + "(m) {"); - increaseIndent(); - writeLine(); - write("var exports = {};"); - writeLine(); - write("for(var n in m) {"); - increaseIndent(); - writeLine(); - write("if (n !== \"default\""); - if (localNames) { - write("&& !" + localNames + ".hasOwnProperty(n)"); - } - write(") exports[n] = m[n];"); - decreaseIndent(); - writeLine(); - write("}"); - writeLine(); - write(exportFunctionForFile + "(exports);"); - decreaseIndent(); - writeLine(); - write("}"); - return exportStarFunction; - } - function writeExportedName(node) { - if (node.kind !== 69 && node.flags & 512) { - return; - } - if (started) { - write(","); - } - else { - started = true; - } - writeLine(); - write("'"); - if (node.kind === 69) { - emitNodeWithCommentsAndWithoutSourcemap(node); - } - else { - emitDeclarationName(node); - } - write("': true"); - } - } - function processTopLevelVariableAndFunctionDeclarations(node) { - var hoistedVars; - var hoistedFunctionDeclarations; - var exportedDeclarations; - visit(node); - if (hoistedVars) { - writeLine(); - write("var "); - var seen = {}; - for (var i = 0; i < hoistedVars.length; i++) { - var local = hoistedVars[i]; - var name_32 = local.kind === 69 - ? local - : local.name; - if (name_32) { - var text = ts.unescapeIdentifier(name_32.text); - if (ts.hasProperty(seen, text)) { - continue; - } - else { - seen[text] = text; - } - } - if (i !== 0) { - write(", "); - } - if (local.kind === 221 || local.kind === 225 || local.kind === 224) { - emitDeclarationName(local); - } - else { - emit(local); - } - var flags = ts.getCombinedNodeFlags(local.kind === 69 ? local.parent : local); - if (flags & 1) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(local); - } - } - write(";"); - } - if (hoistedFunctionDeclarations) { - for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { - var f = hoistedFunctionDeclarations_1[_a]; - writeLine(); - emit(f); - if (f.flags & 1) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(f); - } - } - } - return exportedDeclarations; - function visit(node) { - if (node.flags & 2) { - return; - } - if (node.kind === 220) { - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = []; - } - hoistedFunctionDeclarations.push(node); - return; - } - if (node.kind === 221) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - return; - } - if (node.kind === 224) { - if (shouldEmitEnumDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 225) { - if (shouldEmitModuleDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 218 || node.kind === 169) { - if (shouldHoistVariable(node, false)) { - var name_33 = node.name; - if (name_33.kind === 69) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(name_33); - } - else { - ts.forEachChild(name_33, visit); - } - } - return; - } - if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node.name); - return; - } - if (ts.isBindingPattern(node)) { - ts.forEach(node.elements, visit); - return; - } - if (!ts.isDeclaration(node)) { - ts.forEachChild(node, visit); - } - } - } - function shouldHoistVariable(node, checkIfSourceFileLevelDecl) { - if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { - return false; - } - return (ts.getCombinedNodeFlags(node) & 3072) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 256; - } - function isCurrentFileSystemExternalModule() { - return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; - } - function emitSystemModuleBody(node, dependencyGroups, startIndex) { - emitVariableDeclarationsForImports(); - writeLine(); - var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); - writeLine(); - write("return {"); - increaseIndent(); - writeLine(); - emitSetters(exportStarFunction, dependencyGroups); - writeLine(); - emitExecute(node, startIndex); - decreaseIndent(); - writeLine(); - write("}"); - emitTempDeclarations(true); - } - function emitSetters(exportStarFunction, dependencyGroups) { - write("setters:["); - for (var i = 0; i < dependencyGroups.length; i++) { - if (i !== 0) { - write(","); - } - writeLine(); - increaseIndent(); - var group = dependencyGroups[i]; - var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); - write("function (" + parameterName + ") {"); - increaseIndent(); - for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { - var entry = group_1[_a]; - var importVariableName = getLocalNameForExternalImport(entry) || ""; - switch (entry.kind) { - case 230: - if (!entry.importClause) { - break; - } - case 229: - ts.Debug.assert(importVariableName !== ""); - writeLine(); - write(importVariableName + " = " + parameterName + ";"); - writeLine(); - break; - case 236: - ts.Debug.assert(importVariableName !== ""); - if (entry.exportClause) { - writeLine(); - write(exportFunctionForFile + "({"); - writeLine(); - increaseIndent(); - for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { - if (i_1 !== 0) { - write(","); - writeLine(); - } - var e = entry.exportClause.elements[i_1]; - write("\""); - emitNodeWithCommentsAndWithoutSourcemap(e.name); - write("\": " + parameterName + "[\""); - emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name); - write("\"]"); - } - decreaseIndent(); - writeLine(); - write("});"); - } - else { - writeLine(); - write(exportStarFunction + "(" + parameterName + ");"); - } - writeLine(); - break; - } - } - decreaseIndent(); - write("}"); - decreaseIndent(); - } - write("],"); - } - function emitExecute(node, startIndex) { - write("execute: function() {"); - increaseIndent(); - writeLine(); - for (var i = startIndex; i < node.statements.length; i++) { - var statement = node.statements[i]; - switch (statement.kind) { - case 220: - case 230: - continue; - case 236: - if (!statement.moduleSpecifier) { - for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { - var element = _b[_a]; - emitExportSpecifierInSystemModule(element); - } - } - continue; - case 229: - if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { - continue; - } - default: - writeLine(); - emit(statement); - } - } - decreaseIndent(); - writeLine(); - write("}"); - } - function writeModuleName(node, emitRelativePathAsModuleName) { - var moduleName = node.moduleName; - if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { - write("\"" + moduleName + "\", "); - } - } - function emitSystemModule(node, emitRelativePathAsModuleName) { - collectExternalModuleInfo(node); - ts.Debug.assert(!exportFunctionForFile); - exportFunctionForFile = makeUniqueName("exports"); - contextObjectForFile = makeUniqueName("context"); - writeLine(); - write("System.register("); - writeModuleName(node, emitRelativePathAsModuleName); - write("["); - var groupIndices = {}; - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); - if (text === undefined) { - continue; - } - var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { - var groupIndex = groupIndices[key]; - dependencyGroups[groupIndex].push(externalImports[i]); - continue; - } - else { - groupIndices[key] = dependencyGroups.length; - dependencyGroups.push([externalImports[i]]); - } - if (i !== 0) { - write(", "); - } - write(text); - } - write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); - writeLine(); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - writeLine(); - write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); - writeLine(); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitSystemModuleBody(node, dependencyGroups, startIndex); - decreaseIndent(); - writeLine(); - write("});"); - } - function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - var aliasedModuleNames = []; - var unaliasedModuleNames = []; - var importAliasNames = []; - for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) { - var amdDependency = _b[_a]; - if (amdDependency.name) { - aliasedModuleNames.push('"' + amdDependency.path + '"'); - importAliasNames.push(amdDependency.name); - } - else { - unaliasedModuleNames.push('"' + amdDependency.path + '"'); - } - } - for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { - var importNode = externalImports_4[_c]; - var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); - var importAliasName = getLocalNameForExternalImport(importNode); - if (includeNonAmdDependencies && importAliasName) { - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(importAliasName); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); - emitAMDDependencyList(dependencyNames); - write(", "); - emitAMDFactoryHeader(dependencyNames); - } - function emitAMDDependencyList(_a) { - var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames; - write('["require", "exports"'); - if (aliasedModuleNames.length) { - write(", "); - write(aliasedModuleNames.join(", ")); - } - if (unaliasedModuleNames.length) { - write(", "); - write(unaliasedModuleNames.join(", ")); - } - write("]"); - } - function emitAMDFactoryHeader(_a) { - var importAliasNames = _a.importAliasNames; - write("function (require, exports"); - if (importAliasNames.length) { - write(", "); - write(importAliasNames.join(", ")); - } - write(") {"); - } - function emitAMDModule(node, emitRelativePathAsModuleName) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - writeLine(); - write("define("); - writeModuleName(node, emitRelativePathAsModuleName); - emitAMDDependencies(node, true, emitRelativePathAsModuleName); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(true); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, false, !compilerOptions.noImplicitUseStrict); - emitEmitHelpers(node); - collectExternalModuleInfo(node); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(false); - emitTempDeclarations(true); - } - function emitUMDModule(node) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - var dependencyNames = getAMDDependencyNames(node, false); - writeLines("(function (factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define("); - emitAMDDependencyList(dependencyNames); - write(", factory);"); - writeLines(" }\n})("); - emitAMDFactoryHeader(dependencyNames); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(true); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitES6Module(node) { - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - var startIndex = emitDirectivePrologues(node.statements, false); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - } - function emitExportEquals(emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - writeLine(); - emitStart(exportEquals); - write(emitAsReturn ? "return " : "module.exports = "); - emit(exportEquals.expression); - write(";"); - emitEnd(exportEquals); - } - } - function emitJsxElement(node) { - switch (compilerOptions.jsx) { - case 2: - jsxEmitReact(node); - break; - case 1: - default: - jsxEmitPreserve(node); - break; - } - } - function trimReactWhitespaceAndApplyEntities(node) { - var result = undefined; - var text = ts.getTextOfNode(node, true); - var firstNonWhitespace = 0; - var lastNonWhitespace = -1; - for (var i = 0; i < text.length; i++) { - var c = text.charCodeAt(i); - if (ts.isLineBreak(c)) { - if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { - var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - firstNonWhitespace = -1; - } - else if (!ts.isWhiteSpaceSingleLine(c)) { - lastNonWhitespace = i; - if (firstNonWhitespace === -1) { - firstNonWhitespace = i; - } - } - } - if (firstNonWhitespace !== -1) { - var part = text.substr(firstNonWhitespace); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - if (result) { - result = result.replace(/&(\w+);/g, function (s, m) { - if (entities[m] !== undefined) { - var ch = String.fromCharCode(entities[m]); - return ch === '"' ? "\\\"" : ch; - } - else { - return s; - } - }); - } - return result; - } - function isJsxChildEmittable(child) { - if (child.kind === 248) { - return !!child.expression; - } - else if (child.kind === 244) { - return !!getTextToEmit(child); - } - return true; - } - ; - function getTextToEmit(node) { - switch (compilerOptions.jsx) { - case 2: - var text = trimReactWhitespaceAndApplyEntities(node); - if (text === undefined || text.length === 0) { - return undefined; - } - else { - return text; - } - case 1: - default: - return ts.getTextOfNode(node, true); - } - } - function emitJsxText(node) { - switch (compilerOptions.jsx) { - case 2: - write('"'); - write(trimReactWhitespaceAndApplyEntities(node)); - write('"'); - break; - case 1: - default: - writer.writeLiteral(ts.getTextOfNode(node, true)); - break; - } - } - function emitJsxExpression(node) { - if (node.expression) { - switch (compilerOptions.jsx) { - case 1: - default: - write("{"); - emit(node.expression); - write("}"); - break; - case 2: - emit(node.expression); - break; - } - } - } - function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; - } - function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { - if (writeUseStrict) { - if (startWithNewLine) { - writeLine(); - } - write("\"use strict\";"); - } - } - function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { - var foundUseStrict = false; - for (var i = 0; i < statements.length; i++) { - if (ts.isPrologueDirective(statements[i])) { - if (isUseStrictPrologue(statements[i])) { - foundUseStrict = true; - } - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); - return i; - } - } - ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); - return statements.length; - } - function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line.length) { - writeLine(); - write(line); - } - } - } - function emitEmitHelpers(node) { - if (!compilerOptions.noEmitHelpers) { - if (languageVersion < 2 && !extendsEmitted && node.flags & 262144) { - writeLines(extendsHelper); - extendsEmitted = true; - } - if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 1073741824)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 524288) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); - } - decorateEmitted = true; - } - if (!paramEmitted && node.flags & 1048576) { - writeLines(paramHelper); - paramEmitted = true; - } - if (!awaiterEmitted && node.flags & 2097152) { - writeLines(awaiterHelper); - awaiterEmitted = true; - } - } - } - function emitSourceFileNode(node) { - writeLine(); - emitShebang(); - emitDetachedCommentsAndUpdateCommentsInfo(node); - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; - emitModule(node); - } - else { - bundleEmitDelegates[modulekind](node, true); - } - } - else { - var startIndex = emitDirectivePrologues(node.statements, false); - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - } - emitLeadingComments(node.endOfFileToken); - } - function emit(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - function emitNodeWithCommentsAndWithoutSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); - } - function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { - if (node) { - if (node.flags & 2) { - return emitCommentsOnNotEmittedNode(node); - } - if (isSpecializedCommentHandling(node)) { - return emitNodeWithoutSourceMap(node); - } - var emitComments_1 = shouldEmitLeadingAndTrailingComments(node); - if (emitComments_1) { - emitLeadingComments(node); - } - emitNodeConsideringSourcemap(node); - if (emitComments_1) { - emitTrailingComments(node); - } - } - } - function emitNodeWithSourceMap(node) { - if (node) { - emitStart(node); - emitNodeWithoutSourceMap(node); - emitEnd(node); - } - } - function emitNodeWithoutSourceMap(node) { - if (node) { - emitJavaScriptWorker(node); - } - } - function changeSourceMapEmit(writer) { - sourceMap = writer; - emitStart = writer.emitStart; - emitEnd = writer.emitEnd; - emitPos = writer.emitPos; - setSourceFile = writer.setSourceFile; - } - function withTemporaryNoSourceMap(callback) { - var prevSourceMap = sourceMap; - setSourceMapWriterEmit(ts.getNullSourceMapWriter()); - callback(); - setSourceMapWriterEmit(prevSourceMap); - } - function isSpecializedCommentHandling(node) { - switch (node.kind) { - case 222: - case 220: - case 230: - case 229: - case 223: - case 235: - return true; - } - } - function shouldEmitLeadingAndTrailingComments(node) { - switch (node.kind) { - case 200: - return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 225: - return shouldEmitModuleDeclaration(node); - case 224: - return shouldEmitEnumDeclaration(node); - } - ts.Debug.assert(!isSpecializedCommentHandling(node)); - if (node.kind !== 199 && - node.parent && - node.parent.kind === 180 && - node.parent.body === node && - languageVersion <= 1) { - return false; - } - return true; - } - function emitJavaScriptWorker(node) { - switch (node.kind) { - case 69: - return emitIdentifier(node); - case 142: - return emitParameter(node); - case 147: - case 146: - return emitMethod(node); - case 149: - case 150: - return emitAccessor(node); - case 97: - return emitThis(node); - case 95: - return emitSuper(node); - case 93: - return write("null"); - case 99: - return write("true"); - case 84: - return write("false"); - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - return emitLiteral(node); - case 189: - return emitTemplateExpression(node); - case 197: - return emitTemplateSpan(node); - case 241: - case 242: - return emitJsxElement(node); - case 244: - return emitJsxText(node); - case 248: - return emitJsxExpression(node); - case 139: - return emitQualifiedName(node); - case 167: - return emitObjectBindingPattern(node); - case 168: - return emitArrayBindingPattern(node); - case 169: - return emitBindingElement(node); - case 170: - return emitArrayLiteral(node); - case 171: - return emitObjectLiteral(node); - case 253: - return emitPropertyAssignment(node); - case 254: - return emitShorthandPropertyAssignment(node); - case 140: - return emitComputedPropertyName(node); - case 172: - return emitPropertyAccess(node); - case 173: - return emitIndexedAccess(node); - case 174: - return emitCallExpression(node); - case 175: - return emitNewExpression(node); - case 176: - return emitTaggedTemplateExpression(node); - case 177: - case 195: - case 196: - return emit(node.expression); - case 178: - return emitParenExpression(node); - case 220: - case 179: - case 180: - return emitFunctionDeclaration(node); - case 181: - return emitDeleteExpression(node); - case 182: - return emitTypeOfExpression(node); - case 183: - return emitVoidExpression(node); - case 184: - return emitAwaitExpression(node); - case 185: - return emitPrefixUnaryExpression(node); - case 186: - return emitPostfixUnaryExpression(node); - case 187: - return emitBinaryExpression(node); - case 188: - return emitConditionalExpression(node); - case 191: - return emitSpreadElementExpression(node); - case 190: - return emitYieldExpression(node); - case 193: - return; - case 199: - case 226: - return emitBlock(node); - case 200: - return emitVariableStatement(node); - case 201: - return write(";"); - case 202: - return emitExpressionStatement(node); - case 203: - return emitIfStatement(node); - case 204: - return emitDoStatement(node); - case 205: - return emitWhileStatement(node); - case 206: - return emitForStatement(node); - case 208: - case 207: - return emitForInOrForOfStatement(node); - case 209: - case 210: - return emitBreakOrContinueStatement(node); - case 211: - return emitReturnStatement(node); - case 212: - return emitWithStatement(node); - case 213: - return emitSwitchStatement(node); - case 249: - case 250: - return emitCaseOrDefaultClause(node); - case 214: - return emitLabeledStatement(node); - case 215: - return emitThrowStatement(node); - case 216: - return emitTryStatement(node); - case 252: - return emitCatchClause(node); - case 217: - return emitDebuggerStatement(node); - case 218: - return emitVariableDeclaration(node); - case 192: - return emitClassExpression(node); - case 221: - return emitClassDeclaration(node); - case 222: - return emitInterfaceDeclaration(node); - case 224: - return emitEnumDeclaration(node); - case 255: - return emitEnumMember(node); - case 225: - return emitModuleDeclaration(node); - case 230: - return emitImportDeclaration(node); - case 229: - return emitImportEqualsDeclaration(node); - case 236: - return emitExportDeclaration(node); - case 235: - return emitExportAssignment(node); - case 256: - return emitSourceFileNode(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - function isTripleSlashComment(comment) { - if (currentText.charCodeAt(comment.pos + 1) === 47 && - comment.pos + 2 < comment.end && - currentText.charCodeAt(comment.pos + 2) === 47) { - var textSubStr = currentText.substring(comment.pos, comment.end); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; - } - function getLeadingCommentsToEmit(node) { - if (node.parent) { - if (node.parent.kind === 256 || node.pos !== node.parent.pos) { - if (hasDetachedComments(node.pos)) { - return getLeadingCommentsWithoutDetachedComments(); - } - else { - return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); - } - } - } - } - function getTrailingCommentsToEmit(node) { - if (node.parent) { - if (node.parent.kind === 256 || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentText, node.end); - } - } - } - function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, false); - } - function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, true); - } - function emitLeadingCommentsWorker(node, isEmittedNode) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (isEmittedNode) { - leadingComments = getLeadingCommentsToEmit(node); - } - else { - if (node.pos === 0) { - leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); - } - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); - ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); - } - function emitTrailingComments(node) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = getTrailingCommentsToEmit(node); - ts.emitComments(currentText, currentLineMap, writer, trailingComments, false, newLine, writeComment); - } - function emitTrailingCommentsOfPosition(pos) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = ts.getTrailingCommentRanges(currentText, pos); - ts.emitComments(currentText, currentLineMap, writer, trailingComments, true, newLine, writeComment); - } - function emitLeadingCommentsOfPositionWorker(pos) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (hasDetachedComments(pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - leadingComments = ts.getLeadingCommentRanges(currentText, pos); - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); - ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); - } - function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, comment, newLine) { - emitPos(comment.pos); - ts.writeCommentRange(text, lineMap, writer, comment, newLine); - emitPos(comment.end); - } - function emitShebang() { - var shebang = ts.getShebang(currentText); - if (shebang) { - write(shebang); - writeLine(); - } - } - var _a, _b; - } - function emitFile(_a, sourceFiles, isBundledEmit) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { emittedFilesList.push(jsFilePath); @@ -35787,21 +43324,2015 @@ var ts; } } } + function printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNameSet = ts.createMap(); + isOwnFileEmit = !isBundledEmit; + if (isBundledEmit && moduleKind) { + for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { + var sourceFile = sourceFiles_4[_a]; + emitEmitHelpers(sourceFile); + } + } + ts.forEach(sourceFiles, printSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + } + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); + } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); + } + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + sourceMap.reset(); + comments.reset(); + writer.reset(); + tempFlags = 0; + currentSourceFile = undefined; + currentText = undefined; + extendsEmitted = false; + assignEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + isOwnFileEmit = false; + } + function printSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + currentFileIdentifiers = node.identifiers; + sourceMap.setSourceFile(node); + comments.setSourceFile(node); + emitNodeWithNotification(node, emitWorker); + } + function emit(node) { + emitNodeWithNotification(node, emitWithComments); + } + function emitWithComments(node) { + emitNodeWithComments(node, emitWithSourceMap); + } + function emitWithSourceMap(node) { + emitNodeWithSourceMap(node, emitWorker); + } + function emitIdentifierName(node) { + if (node) { + emitNodeWithNotification(node, emitIdentifierNameWithComments); + } + } + function emitIdentifierNameWithComments(node) { + emitNodeWithComments(node, emitWorker); + } + function emitExpression(node) { + emitNodeWithNotification(node, emitExpressionWithComments); + } + function emitExpressionWithComments(node) { + emitNodeWithComments(node, emitExpressionWithSourceMap); + } + function emitExpressionWithSourceMap(node) { + emitNodeWithSourceMap(node, emitExpressionWorker); + } + function emitNodeWithNotification(node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(node, emitCallback); + } + else { + emitCallback(node); + } + } + } + function emitNodeWithSourceMap(node, emitCallback) { + if (node) { + emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + emitCallback(node); + emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + function shouldSkipLeadingCommentsForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 16384) !== 0; + } + function shouldSkipLeadingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 512) !== 0; + } + function shouldSkipTrailingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 1024) !== 0; + } + function shouldSkipSourceMapForChildren(node) { + return (node.emitFlags & 2048) !== 0; + } + function emitWorker(node) { + if (tryEmitSubstitute(node, emitWorker, false)) { + return; + } + var kind = node.kind; + switch (kind) { + case 12: + case 13: + case 14: + return emitLiteral(node); + case 69: + return emitIdentifier(node); + case 74: + case 77: + case 82: + case 103: + case 110: + case 111: + case 112: + case 113: + case 115: + case 117: + case 118: + case 120: + case 122: + case 130: + case 128: + case 132: + case 133: + case 137: + return writeTokenNode(node); + case 139: + return emitQualifiedName(node); + case 140: + return emitComputedPropertyName(node); + case 141: + return emitTypeParameter(node); + case 142: + return emitParameter(node); + case 143: + return emitDecorator(node); + case 144: + return emitPropertySignature(node); + case 145: + return emitPropertyDeclaration(node); + case 146: + return emitMethodSignature(node); + case 147: + return emitMethodDeclaration(node); + case 148: + return emitConstructor(node); + case 149: + case 150: + return emitAccessorDeclaration(node); + case 151: + return emitCallSignature(node); + case 152: + return emitConstructSignature(node); + case 153: + return emitIndexSignature(node); + case 154: + return emitTypePredicate(node); + case 155: + return emitTypeReference(node); + case 156: + return emitFunctionType(node); + case 157: + return emitConstructorType(node); + case 158: + return emitTypeQuery(node); + case 159: + return emitTypeLiteral(node); + case 160: + return emitArrayType(node); + case 161: + return emitTupleType(node); + case 162: + return emitUnionType(node); + case 163: + return emitIntersectionType(node); + case 164: + return emitParenthesizedType(node); + case 194: + return emitExpressionWithTypeArguments(node); + case 165: + return emitThisType(node); + case 166: + return emitLiteralType(node); + case 167: + return emitObjectBindingPattern(node); + case 168: + return emitArrayBindingPattern(node); + case 169: + return emitBindingElement(node); + case 197: + return emitTemplateSpan(node); + case 198: + return emitSemicolonClassElement(node); + case 199: + return emitBlock(node); + case 200: + return emitVariableStatement(node); + case 201: + return emitEmptyStatement(node); + case 202: + return emitExpressionStatement(node); + case 203: + return emitIfStatement(node); + case 204: + return emitDoStatement(node); + case 205: + return emitWhileStatement(node); + case 206: + return emitForStatement(node); + case 207: + return emitForInStatement(node); + case 208: + return emitForOfStatement(node); + case 209: + return emitContinueStatement(node); + case 210: + return emitBreakStatement(node); + case 211: + return emitReturnStatement(node); + case 212: + return emitWithStatement(node); + case 213: + return emitSwitchStatement(node); + case 214: + return emitLabeledStatement(node); + case 215: + return emitThrowStatement(node); + case 216: + return emitTryStatement(node); + case 217: + return emitDebuggerStatement(node); + case 218: + return emitVariableDeclaration(node); + case 219: + return emitVariableDeclarationList(node); + case 220: + return emitFunctionDeclaration(node); + case 221: + return emitClassDeclaration(node); + case 222: + return emitInterfaceDeclaration(node); + case 223: + return emitTypeAliasDeclaration(node); + case 224: + return emitEnumDeclaration(node); + case 225: + return emitModuleDeclaration(node); + case 226: + return emitModuleBlock(node); + case 227: + return emitCaseBlock(node); + case 229: + return emitImportEqualsDeclaration(node); + case 230: + return emitImportDeclaration(node); + case 231: + return emitImportClause(node); + case 232: + return emitNamespaceImport(node); + case 233: + return emitNamedImports(node); + case 234: + return emitImportSpecifier(node); + case 235: + return emitExportAssignment(node); + case 236: + return emitExportDeclaration(node); + case 237: + return emitNamedExports(node); + case 238: + return emitExportSpecifier(node); + case 239: + return; + case 240: + return emitExternalModuleReference(node); + case 244: + return emitJsxText(node); + case 243: + return emitJsxOpeningElement(node); + case 245: + return emitJsxClosingElement(node); + case 246: + return emitJsxAttribute(node); + case 247: + return emitJsxSpreadAttribute(node); + case 248: + return emitJsxExpression(node); + case 249: + return emitCaseClause(node); + case 250: + return emitDefaultClause(node); + case 251: + return emitHeritageClause(node); + case 252: + return emitCatchClause(node); + case 253: + return emitPropertyAssignment(node); + case 254: + return emitShorthandPropertyAssignment(node); + case 255: + return emitEnumMember(node); + case 256: + return emitSourceFile(node); + } + if (ts.isExpression(node)) { + return emitExpressionWorker(node); + } + } + function emitExpressionWorker(node) { + if (tryEmitSubstitute(node, emitExpressionWorker, true)) { + return; + } + var kind = node.kind; + switch (kind) { + case 8: + return emitNumericLiteral(node); + case 9: + case 10: + case 11: + return emitLiteral(node); + case 69: + return emitIdentifier(node); + case 84: + case 93: + case 95: + case 99: + case 97: + return writeTokenNode(node); + case 170: + return emitArrayLiteralExpression(node); + case 171: + return emitObjectLiteralExpression(node); + case 172: + return emitPropertyAccessExpression(node); + case 173: + return emitElementAccessExpression(node); + case 174: + return emitCallExpression(node); + case 175: + return emitNewExpression(node); + case 176: + return emitTaggedTemplateExpression(node); + case 177: + return emitTypeAssertionExpression(node); + case 178: + return emitParenthesizedExpression(node); + case 179: + return emitFunctionExpression(node); + case 180: + return emitArrowFunction(node); + case 181: + return emitDeleteExpression(node); + case 182: + return emitTypeOfExpression(node); + case 183: + return emitVoidExpression(node); + case 184: + return emitAwaitExpression(node); + case 185: + return emitPrefixUnaryExpression(node); + case 186: + return emitPostfixUnaryExpression(node); + case 187: + return emitBinaryExpression(node); + case 188: + return emitConditionalExpression(node); + case 189: + return emitTemplateExpression(node); + case 190: + return emitYieldExpression(node); + case 191: + return emitSpreadElementExpression(node); + case 192: + return emitClassExpression(node); + case 193: + return; + case 195: + return emitAsExpression(node); + case 196: + return emitNonNullExpression(node); + case 241: + return emitJsxElement(node); + case 242: + return emitJsxSelfClosingElement(node); + case 288: + return emitPartiallyEmittedExpression(node); + } + } + function emitNumericLiteral(node) { + emitLiteral(node); + if (node.trailingComment) { + write(" /*" + node.trailingComment + "*/"); + } + } + function emitLiteral(node) { + var text = getLiteralTextOfNode(node); + if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) + && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else { + write(text); + } + } + function emitIdentifier(node) { + if (node.emitFlags & 16) { + writeLines(umdHelper); + } + else { + write(getTextOfNode(node, false)); + } + } + function emitQualifiedName(node) { + emitEntityName(node.left); + write("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + write("["); + emitExpression(node.expression); + write("]"); + } + function emitTypeParameter(node) { + emit(node.name); + emitWithPrefix(" extends ", node.constraint); + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitExpressionWithPrefix(" = ", node.initializer); + emitWithPrefix(": ", node.type); + } + function emitDecorator(decorator) { + write("@"); + emitExpression(decorator.expression); + } + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emitWithPrefix(": ", node.type); + emitExpressionWithPrefix(" = ", node.initializer); + write(";"); + } + function emitMethodSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.asteriskToken, "*"); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + write("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.kind === 149 ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitConstructSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitSemicolonClassElement(node) { + write(";"); + } + function emitTypePredicate(node) { + emit(node.parameterName); + write(" is "); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitConstructorType(node) { + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitTypeQuery(node) { + write("typeof "); + emit(node.exprName); + } + function emitTypeLiteral(node) { + write("{"); + emitList(node, node.members, 65); + write("}"); + } + function emitArrayType(node) { + emit(node.elementType); + write("[]"); + } + function emitTupleType(node) { + write("["); + emitList(node, node.elementTypes, 336); + write("]"); + } + function emitUnionType(node) { + emitList(node, node.types, 260); + } + function emitIntersectionType(node) { + emitList(node, node.types, 264); + } + function emitParenthesizedType(node) { + write("("); + emit(node.type); + write(")"); + } + function emitThisType(node) { + write("this"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitObjectBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("{}"); + } + else { + write("{"); + emitList(node, elements, 432); + write("}"); + } + } + function emitArrayBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + write("["); + emitList(node, node.elements, 304); + write("]"); + } + } + function emitBindingElement(node) { + emitWithSuffix(node.propertyName, ": "); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitArrayLiteralExpression(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + var preferNewLine = node.multiLine ? 32768 : 0; + emitExpressionList(node, elements, 4466 | preferNewLine); + } + } + function emitObjectLiteralExpression(node) { + var properties = node.properties; + if (properties.length === 0) { + write("{}"); + } + else { + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 32768 : 0; + var allowTrailingComma = languageVersion >= 1 ? 32 : 0; + emitList(node, properties, 978 | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + } + function emitPropertyAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(node.emitFlags & 1048576)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot); + write(shouldEmitDotDot ? ".." : "."); + increaseIndentIf(indentAfterDot); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + function needsDotDotForPropertyAccess(expression) { + if (expression.kind === 8) { + var text = getLiteralTextOfNode(expression); + return text.indexOf(ts.tokenToString(21)) < 0; + } + else { + var constantValue = tryGetConstEnumValue(expression); + return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + function emitElementAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + emitExpression(node.expression); + write("["); + emitExpression(node.argumentExpression); + write("]"); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 1296); + } + function emitNewExpression(node) { + write("new "); + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 9488); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + write(" "); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + if (node.type) { + write("<"); + emit(node.type); + write(">"); + } + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + write("("); + emitExpression(node.expression); + write(")"); + } + function emitFunctionExpression(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitWithPrefix(": ", node.type); + write(" =>"); + } + function emitDeleteExpression(node) { + write("delete "); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + write("typeof "); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + write("void "); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + write("await "); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + write(" "); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + var operand = node.operand; + return operand.kind === 185 + && ((node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) + || (node.operator === 36 && (operand.operator === 36 || operand.operator === 42))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 24; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + writeTokenText(node.operatorToken.kind); + increaseIndentIf(indentAfterOperator, " "); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, " "); + write("?"); + increaseIndentIf(indentAfterQuestion, " "); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, " "); + write(":"); + increaseIndentIf(indentAfterColon, " "); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 131072); + } + function emitYieldExpression(node) { + write(node.asteriskToken ? "yield*" : "yield"); + emitExpressionWithPrefix(" ", node.expression); + } + function emitSpreadElementExpression(node) { + write("..."); + emitExpression(node.expression); + } + function emitClassExpression(node) { + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + write(" as "); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + write("!"); + } + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + function emitBlock(node, format) { + if (isSingleLineEmptyBlock(node)) { + writeToken(15, node.pos, node); + write(" "); + writeToken(16, node.statements.end, node); + } + else { + writeToken(15, node.pos, node); + emitBlockStatements(node); + writeToken(16, node.statements.end, node); + } + } + function emitBlockStatements(node) { + if (node.emitFlags & 32) { + emitList(node, node.statements, 384); + } + else { + emitList(node, node.statements, 65); + } + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + write(";"); + } + function emitEmptyStatement(node) { + write(";"); + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + write(";"); + } + function emitIfStatement(node) { + var openParenPos = writeToken(88, node.pos, node); + write(" "); + writeToken(17, openParenPos, node); + emitExpression(node.expression); + writeToken(18, node.expression.end, node); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + writeToken(80, node.thenStatement.end, node); + if (node.elseStatement.kind === 203) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (ts.isBlock(node.statement)) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emitExpression(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos, node); + emitForBinding(node.initializer); + write(";"); + emitExpressionWithPrefix(" ", node.condition); + write(";"); + emitExpressionWithPrefix(" ", node.incrementor); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos); + emitForBinding(node.initializer); + write(" in "); + emitExpression(node.expression); + writeToken(18, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForOfStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos); + emitForBinding(node.initializer); + write(" of "); + emitExpression(node.expression); + writeToken(18, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 219) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + writeToken(75, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitBreakStatement(node) { + writeToken(70, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + writeToken(94, node.pos, node); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitWithStatement(node) { + write("with ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = writeToken(96, node.pos); + write(" "); + writeToken(17, openParenPos); + emitExpression(node.expression); + writeToken(18, node.expression.end); + write(" "); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function emitThrowStatement(node) { + write("throw"); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(76, node.pos); + write(";"); + } + function emitVariableDeclaration(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitVariableDeclarationList(node) { + write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + emitList(node, node.declarations, 272); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.asteriskToken ? "function* " : "function "); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + if (node.emitFlags & 4194304) { + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + tempFlags = savedTempFlags; + } + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + write(" "); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + write(";"); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { + if (body.emitFlags & 32) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2) + || shouldWriteClosingLineTerminator(body, body.statements, 2)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(parentNode, body) { + write(" {"); + increaseIndent(); + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker); + decreaseIndent(); + writeToken(16, body.statements.end, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + var statementOffset = emitPrologueDirectives(body.statements, true); + var helpersEmitted = emitHelpers(body); + if (statementOffset === 0 && !helpersEmitted && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 384); + increaseIndent(); + } + else { + emitList(body, body.statements, 1, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("class"); + emitNodeWithPrefix(" ", node.name, emitIdentifierName); + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 65); + write("}"); + if (indentedFlag) { + decreaseIndent(); + } + tempFlags = savedTempFlags; + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("interface "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256); + write(" {"); + emitList(node, node.members, 65); + write("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("type "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + write(" = "); + emit(node.type); + write(";"); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + write("enum "); + emit(node.name); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 81); + write("}"); + tempFlags = savedTempFlags; + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + write(node.flags & 16 ? "namespace " : "module "); + emit(node.name); + var body = node.body; + while (body.kind === 225) { + write("."); + emit(body.name); + body = body.body; + } + write(" "); + emit(body); + } + function emitModuleBlock(node) { + if (isSingleLineEmptyBlock(node)) { + write("{ }"); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + write("{"); + increaseIndent(); + emitBlockStatements(node); + write("}"); + tempFlags = savedTempFlags; + } + } + function emitCaseBlock(node) { + writeToken(15, node.pos); + emitList(node, node.clauses, 65); + writeToken(16, node.clauses.end); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + emit(node.name); + write(" = "); + emitModuleReference(node.moduleReference); + write(";"); + } + function emitModuleReference(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + if (node.importClause) { + emit(node.importClause); + write(" from "); + } + emitExpression(node.moduleSpecifier); + write(";"); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + write(", "); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + write("* as "); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + write(node.isExportEquals ? "export = " : "export default "); + emitExpression(node.expression); + write(";"); + } + function emitExportDeclaration(node) { + write("export "); + if (node.exportClause) { + emit(node.exportClause); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + emitExpression(node.moduleSpecifier); + } + write(";"); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + write("{"); + emitList(node, node.elements, 432); + write("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + write(" as "); + } + emit(node.name); + } + function emitExternalModuleReference(node) { + write("require("); + emitExpression(node.expression); + write(")"); + } + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 131072); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + write("<"); + emitJsxTagName(node.tagName); + write(" "); + emitList(node, node.attributes, 131328); + write("/>"); + } + function emitJsxOpeningElement(node) { + write("<"); + emitJsxTagName(node.tagName); + writeIfAny(node.attributes, " "); + emitList(node, node.attributes, 131328); + write(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, true)); + } + function emitJsxClosingElement(node) { + write(""); + } + function emitJsxAttribute(node) { + emit(node.name); + emitWithPrefix("=", node.initializer); + } + function emitJsxSpreadAttribute(node) { + write("{..."); + emitExpression(node.expression); + write("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + write("{"); + emitExpression(node.expression); + write("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitCaseClause(node) { + write("case "); + emitExpression(node.expression); + write(":"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitDefaultClause(node) { + write("default:"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitCaseOrDefaultClauseStatements(parentNode, statements) { + var emitAsSingleStatement = statements.length === 1 && + (ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (emitAsSingleStatement) { + write(" "); + emit(statements[0]); + } + else { + emitList(parentNode, statements, 81985); + } + } + function emitHeritageClause(node) { + write(" "); + writeTokenText(node.token); + write(" "); + emitList(node, node.types, 272); + } + function emitCatchClause(node) { + writeLine(); + var openParenPos = writeToken(72, node.pos); + write(" "); + writeToken(17, openParenPos); + emit(node.variableDeclaration); + writeToken(18, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + write(" "); + emit(node.block); + } + function emitPropertyAssignment(node) { + emit(node.name); + write(": "); + var initializer = node.initializer; + if (!shouldSkipLeadingCommentsForNode(initializer)) { + var commentRange = initializer.commentRange || initializer; + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + write(" = "); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitEnumMember(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitSourceFile(node) { + writeLine(); + emitShebang(); + emitBodyWithDetachedComments(node, node.statements, emitSourceFileWorker); + } + function emitSourceFileWorker(node) { + var statements = node.statements; + var statementOffset = emitPrologueDirectives(statements); + var savedTempFlags = tempFlags; + tempFlags = 0; + emitHelpers(node); + emitList(node, statements, 1, statementOffset); + tempFlags = savedTempFlags; + } + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitPrologueDirectives(statements, startWithNewLine) { + for (var i = 0; i < statements.length; i++) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + return i; + } + } + return statements.length; + } + function emitHelpers(node) { + var emitFlags = node.emitFlags; + var helpersEmitted = false; + if (emitFlags & 1) { + helpersEmitted = emitEmitHelpers(currentSourceFile); + } + if (emitFlags & 2) { + writeLines(exportStarHelper); + helpersEmitted = true; + } + if (emitFlags & 4) { + writeLines(superHelper); + helpersEmitted = true; + } + if (emitFlags & 8) { + writeLines(advancedSuperHelper); + helpersEmitted = true; + } + return helpersEmitted; + } + function emitEmitHelpers(node) { + if (compilerOptions.noEmitHelpers) { + return false; + } + if (compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + return false; + } + var helpersEmitted = false; + if ((languageVersion < 2) && (!extendsEmitted && node.flags & 1024)) { + writeLines(extendsHelper); + extendsEmitted = true; + helpersEmitted = true; + } + if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 16384)) { + writeLines(assignHelper); + assignEmitted = true; + } + if (!decorateEmitted && node.flags & 2048) { + writeLines(decorateHelper); + if (compilerOptions.emitDecoratorMetadata) { + writeLines(metadataHelper); + } + decorateEmitted = true; + helpersEmitted = true; + } + if (!paramEmitted && node.flags & 4096) { + writeLines(paramHelper); + paramEmitted = true; + helpersEmitted = true; + } + if (!awaiterEmitted && node.flags & 8192) { + writeLines(awaiterHelper); + if (languageVersion < 2) { + writeLines(generatorHelper); + } + awaiterEmitted = true; + helpersEmitted = true; + } + if (helpersEmitted) { + writeLine(); + } + return helpersEmitted; + } + function writeLines(text) { + var lines = text.split(/\r\n|\r|\n/g); + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line.length) { + if (i > 0) { + writeLine(); + } + write(line); + } + } + } + function emitShebang() { + var shebang = ts.getShebang(currentText); + if (shebang) { + write(shebang); + writeLine(); + } + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 256); + write(" "); + } + } + function emitWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emit); + } + function emitExpressionWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emitExpression); + } + function emitNodeWithPrefix(prefix, node, emit) { + if (node) { + write(prefix); + emit(node); + } + } + function emitWithSuffix(node, suffix) { + if (node) { + emit(node); + write(suffix); + } + } + function tryEmitSubstitute(node, emitNode, isExpression) { + if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { + var substitute = onSubstituteNode(node, isExpression); + if (substitute !== node) { + substitute.emitFlags |= 128; + emitNode(substitute); + return true; + } + } + return false; + } + function tryEmitConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + write(String(constantValue)); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : getTextOfNode(node.argumentExpression); + write(" /* " + propertyName + " */"); + } + return true; + } + return false; + } + function emitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + write(" "); + emit(node); + } + else { + writeLine(); + increaseIndent(); + emit(node); + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 24577); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 26960); + } + function emitTypeParameters(parentNode, typeParameters) { + emitList(parentNode, typeParameters, 26960); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 1360); + } + function emitParametersForArrow(parentNode, parameters) { + if (parameters && + parameters.length === 1 && + parameters[0].type === undefined && + parameters[0].pos === parentNode.pos) { + emit(parameters[0]); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 4432); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 8192) { + return; + } + var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + if (isEmpty && format & 16384) { + return; + } + if (format & 7680) { + write(getOpeningBracket(format)); + } + if (isEmpty) { + if (format & 1) { + writeLine(); + } + else if (format & 128) { + write(" "); + } + } + else { + var mayEmitInterveningComments = (format & 131072) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 128) { + write(" "); + } + if (format & 64) { + increaseIndent(); + } + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = void 0; + var delimiter = getDelimiter(format); + for (var i = 0; i < count; i++) { + var child = children[start + i]; + if (previousSibling) { + write(delimiter); + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + if ((format & (3 | 64)) === 0) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 256) { + write(" "); + } + } + if (shouldEmitInterveningComments) { + var commentRange = child.commentRange || child; + emitTrailingCommentsOfPosition(commentRange.pos); + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + var hasTrailingComma = (format & 32) && children.hasTrailingComma; + if (format & 16 && hasTrailingComma) { + write(","); + } + if (format & 64) { + decreaseIndent(); + } + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 128) { + write(" "); + } + } + if (format & 7680) { + write(getClosingBracket(format)); + } + } + function writeIfAny(nodes, text) { + if (nodes && nodes.length > 0) { + write(text); + } + } + function writeIfPresent(node, text) { + if (node !== undefined) { + write(text); + } + } + function writeToken(token, pos, contextNode) { + var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); + var tokenEndPos = writeTokenText(token, tokenStartPos); + return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); + } + function shouldSkipLeadingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 4096) !== 0; + } + function shouldSkipTrailingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 8192) !== 0; + } + function writeTokenText(token, pos) { + var tokenString = ts.tokenToString(token); + write(tokenString); + return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; + } + function writeTokenNode(node) { + if (node) { + emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + writeTokenText(node.kind); + emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (valueToWriteWhenNotIndenting) { + write(valueToWriteWhenNotIndenting); + } + } + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1) { + return true; + } + if (format & 2) { + if (format & 32768) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1) { + return true; + } + else if (format & 2) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return nextNode.startsOnNewLine; + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1) { + return (format & 65536) === 0; + } + else if (format & 2) { + if (format & 32768) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = node.startsOnNewLine; + if (startsOnNewLine === undefined) { + return (format & 32768) !== 0; + } + return startsOnNewLine; + } + return (format & 32768) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + if (node2.startsOnNewLine) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 178 && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return getGeneratedIdentifier(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return ts.unescapeIdentifier(node.text); + } + else if (node.kind === 9 && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node) { + if (node.kind === 9 && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode); + } + } + return ts.getLiteralText(node, currentSourceFile, languageVersion); + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } + function isSingleLineEmptyBlock(block) { + return !block.multiLine + && block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function isUniqueName(name) { + return !resolver.hasGlobalName(name) && + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); + } + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals && ts.hasProperty(node.locals, name)) { + if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { + return false; + } + } + } + return true; + } + function makeTempVariableName(flags) { + if (flags && !(tempFlags & flags)) { + var name_41 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_41)) { + tempFlags |= flags; + return name_41; + } + } + while (true) { + var count = tempFlags & 268435455; + tempFlags++; + if (count !== 8 && count !== 13) { + var name_42 = count < 26 + ? "_" + String.fromCharCode(97 + count) + : "_" + (count - 26); + if (isUniqueName(name_42)) { + return name_42; + } + } + } + } + function makeUniqueName(baseName) { + if (baseName.charCodeAt(baseName.length - 1) !== 95) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (isUniqueName(generatedName)) { + return generatedNameSet[generatedName] = generatedName; + } + i++; + } + } + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); + var baseName = expr.kind === 9 ? + ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + return makeUniqueName(baseName); + } + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForNode(node) { + switch (node.kind) { + case 69: + return makeUniqueName(getTextOfNode(node)); + case 225: + case 224: + return generateNameForModuleOrEnum(node); + case 230: + case 236: + return generateNameForImportOrExportDeclaration(node); + case 220: + case 221: + case 235: + return generateNameForExportDefault(); + case 192: + return generateNameForClassExpression(); + default: + return makeTempVariableName(0); + } + } + function generateName(name) { + switch (name.autoGenerateKind) { + case 1: + return makeTempVariableName(0); + case 2: + return makeTempVariableName(268435456); + case 3: + return makeUniqueName(name.text); + } + ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + if (ts.isIdentifier(node) + && node.autoGenerateKind === 4 + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + return node; + } + function getGeneratedIdentifier(name) { + if (name.autoGenerateKind === 4) { + var node = getNodeForGeneratedName(name); + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + } + else { + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(generateName(name))); + } + } + function createDelimiterMap() { + var delimiters = []; + delimiters[0] = ""; + delimiters[16] = ","; + delimiters[4] = " |"; + delimiters[8] = " &"; + return delimiters; + } + function getDelimiter(format) { + return delimiters[format & 28]; + } + function createBracketsMap() { + var brackets = []; + brackets[512] = ["{", "}"]; + brackets[1024] = ["(", ")"]; + brackets[2048] = ["<", ">"]; + brackets[4096] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 7680][0]; + } + function getClosingBracket(format) { + return brackets[format & 7680][1]; + } } ts.emitFiles = emitFiles; })(ts || (ts = {})); var ts; (function (ts) { - ts.programTime = 0; - ts.emitTime = 0; - ts.ioReadTime = 0; - ts.ioWriteTime = 0; - ts.version = "2.0.0"; + ts.version = "2.1.0"; var emptyArray = []; - var defaultTypeRoots = ["node_modules/@types"]; - function findConfigFile(searchPath, fileExists) { + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } while (true) { - var fileName = ts.combinePaths(searchPath, "tsconfig.json"); + var fileName = ts.combinePaths(searchPath, configName); if (fileExists(fileName)) { return fileName; } @@ -35876,51 +45407,29 @@ var ts; return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; } function moduleHasNonRelativeName(moduleName) { - if (ts.isRootedDiskPath(moduleName)) { - return false; - } - var i = moduleName.lastIndexOf("./", 1); - var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); - return !startsWithDotSlashOrDotDotSlash; + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent; - try { - var jsonText = state.host.readFile(packageJsonPath); - jsonContent = jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - jsonContent = {}; - } - var typesFile; - var fieldName; - if (jsonContent.typings) { - if (typeof jsonContent.typings === "string") { - fieldName = "typings"; - typesFile = jsonContent.typings; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } } } } - if (!typesFile && jsonContent.types) { - if (typeof jsonContent.types === "string") { - fieldName = "types"; - typesFile = jsonContent.types; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); - } - } - } - if (typesFile) { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { return typesFilePath; } if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { @@ -35932,6 +45441,15 @@ var ts; } return undefined; } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -35944,11 +45462,28 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - if (!currentDirectory) { - return undefined; - } - return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); + return currentDirectory && getDefaultTypeRoots(currentDirectory, host); } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_15 = ts.getDirectoryPath(currentDirectory); + if (parent_15 === currentDirectory) { + break; + } + currentDirectory = parent_15; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -36154,7 +45689,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); @@ -36270,7 +45805,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } function directoryProbablyExists(directoryName, host) { @@ -36278,9 +45813,9 @@ var ts; } ts.directoryProbablyExists = directoryProbablyExists; function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingOrKeepingExtension) { - return resolvedByAddingOrKeepingExtension; + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; } if (ts.hasJavaScriptFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); @@ -36288,39 +45823,37 @@ var ts; var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); } } - function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } - return ts.forEach(extensions, tryLoad); - function tryLoad(ext) { - if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { - return undefined; + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } - var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } + failedLookupLocation.push(fileName); + return undefined; } } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var packageJsonPath = pathToPackageJson(candidate); var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { @@ -36328,7 +45861,9 @@ var ts; } var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); if (typesFile) { - var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); if (result) { return result; } @@ -36347,6 +45882,9 @@ var ts; } return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); @@ -36419,14 +45957,8 @@ var ts; : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } ts.classicNameResolver = classicNameResolver; - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1, - noImplicitAny: false, - sourceMap: false - }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = {}; + var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } @@ -36434,9 +45966,10 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - var start = new Date().getTime(); + ts.performance.mark("beforeIORead"); text = ts.sys.readFile(fileName, options.charset); - ts.ioReadTime += new Date().getTime() - start; + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } catch (e) { if (onError) { @@ -36449,7 +45982,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (ts.hasProperty(existingDirectories, directoryPath)) { + if (directoryPath in existingDirectories) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -36468,11 +46001,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = {}; + outputFingerprints = ts.createMap(); } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { + if (mtimeBefore && fileName in outputFingerprints) { var fingerprint = outputFingerprints[fileName]; if (fingerprint.byteOrderMark === writeByteOrderMark && fingerprint.hash === hash && @@ -36490,7 +46023,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - var start = new Date().getTime(); + ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -36498,7 +46031,8 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.ioWriteTime += new Date().getTime() - start; + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } catch (e) { if (onError) { @@ -36524,6 +46058,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -36537,6 +46072,22 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; + } + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -36565,25 +46116,17 @@ var ts; return []; } var resolutions = []; - var cache = {}; - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_34 = names_1[_i]; - var result = void 0; - if (ts.hasProperty(cache, name_34)) { - result = cache[name_34]; - } - else { - result = loader(name_34, containingFile); - cache[name_34] = result; - } + var cache = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_43 = names_2[_i]; + var result = name_43 in cache + ? cache[name_43] + : cache[name_43] = loader(name_43, containingFile); resolutions.push(result); } return resolutions; } - function getInferredTypesRoot(options, rootFiles, host) { - return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - } - function getAutomaticTypeDirectiveNames(options, rootFiles, host) { + function getAutomaticTypeDirectiveNames(options, host) { if (options.types) { return options.types; } @@ -36594,7 +46137,15 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - result = result.concat(host.getDirectories(root)); + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } } } } @@ -36609,13 +46160,13 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; - var currentNodeModulesJsDepth = 0; - var modulesWithElidedImports = {}; - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + var modulesWithElidedImports = ts.createMap(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -36642,10 +46193,9 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, host); if (typeReferences) { - var inferredRoot = getInferredTypesRoot(options, rootNames, host); - var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -36689,7 +46239,8 @@ var ts; getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.programTime += new Date().getTime() - start; + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -36708,10 +46259,10 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = {}; + classifiableNames = ts.createMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyMap(sourceFile.classifiableNames, classifiableNames); + ts.copyProperties(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -36734,7 +46285,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { + !ts.equalOwnProperties(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -36824,7 +46375,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, + isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -36836,8 +46387,7 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } function emit(sourceFile, writeFileCallback, cancellationToken) { - var _this = this; - return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); @@ -36862,9 +46412,10 @@ var ts; } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - var start = new Date().getTime(); + ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); - ts.emitTime += new Date().getTime() - start; + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; } function getSourceFile(fileName) { @@ -37003,16 +46554,16 @@ var ts; case 175: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start_2 = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142: var parameter = node; if (parameter.modifiers) { - var start_3 = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -37056,8 +46607,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start_4 = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -37137,6 +46688,14 @@ var ts; var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + var externalHelpersModuleReference = ts.createNode(9); + externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; + externalHelpersModuleReference.parent = file; + imports = [externalHelpersModuleReference]; + } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, false); @@ -37164,7 +46723,7 @@ var ts; } break; case 225: - if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); @@ -37244,8 +46803,17 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { - if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { + sourceFilesFoundSearchingNodeModules[file_1.path] = false; + if (!options.noResolve) { + processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processTypeReferenceDirectives(file_1); + } + modulesWithElidedImports[file_1.path] = false; + processImportedModules(file_1, ts.getDirectoryPath(fileName)); + } + else if (file_1 && modulesWithElidedImports[file_1.path]) { + if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -37262,6 +46830,7 @@ var ts; }); filesByName.set(path, file); if (file) { + sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -37295,13 +46864,14 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; - ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -37318,7 +46888,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } saveResolution = false; } @@ -37352,7 +46922,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = {}; + file.resolvedModules = ts.createMap(); var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -37362,12 +46932,9 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - sourceFilesFoundSearchingNodeModules[resolvedPath] = true; + currentNodeModulesDepth++; } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth++; - } - var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -37375,8 +46942,8 @@ var ts; else if (shouldAddFile) { findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth--; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; } } } @@ -37387,8 +46954,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var file = sourceFiles_5[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -37399,8 +46966,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -37447,6 +47014,9 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { + if (options.paths[key].length === 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; @@ -37492,28 +47062,28 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -37531,7 +47101,7 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } if (!options.noEmit && !options.suppressOutputPathCheck) { @@ -37587,6 +47157,11 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean", + experimental: true + }, { name: "emitBOM", type: "boolean" @@ -37617,10 +47192,10 @@ var ts; }, { name: "jsx", - type: { + type: ts.createMap({ "preserve": 1, "react": 2 - }, + }), paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -37647,7 +47222,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -37655,16 +47230,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }, + }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: { + type: ts.createMap({ "crlf": 0, "lf": 1 - }, + }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -37682,6 +47257,10 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, + { + name: "noErrorTruncation", + type: "boolean" + }, { name: "noImplicitAny", type: "boolean", @@ -37695,12 +47274,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Locals + description: ts.Diagnostics.Report_errors_on_unused_locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters }, { name: "noLib", @@ -37805,12 +47384,12 @@ var ts; { name: "target", shortName: "t", - type: { + type: ts.createMap({ "es3": 0, "es5": 1, "es6": 2, "es2015": 2 - }, + }), description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -37839,11 +47418,12 @@ var ts; }, { name: "moduleResolution", - type: { + type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }, - description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 + }), + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + paramType: ts.Diagnostics.STRATEGY }, { name: "allowUnusedLabels", @@ -37943,7 +47523,7 @@ var ts; type: "list", element: { name: "lib", - type: { + type: ts.createMap({ "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", "es2015": "lib.es2015.d.ts", @@ -37951,6 +47531,7 @@ var ts; "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", "dom": "lib.dom.d.ts", + "dom.iterable": "lib.dom.iterable.d.ts", "webworker": "lib.webworker.d.ts", "scripthost": "lib.scripthost.d.ts", "es2015.core": "lib.es2015.core.d.ts", @@ -37965,7 +47546,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - } + }) }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -37977,6 +47558,11 @@ var ts; name: "strictNullChecks", type: "boolean", description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "importHelpers", + type: "boolean", + description: ts.Diagnostics.Import_emit_helpers_from_tslib } ]; ts.typingOptionDeclarations = [ @@ -38001,13 +47587,19 @@ var ts; } } ]; + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1, + noImplicitAny: false, + sourceMap: false + }; var optionNameMapCache; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = {}; - var shortOptionNames = {}; + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -38020,16 +47612,16 @@ var ts; ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - ts.forEachKey(opt.type, function (key) { + for (var key in opt.type) { namesOfType.push(" '" + key + "'"); - }); + } return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (ts.hasProperty(map, key)) { + if (key in map) { return map[key]; } else { @@ -38078,10 +47670,10 @@ var ts; } else if (s.charCodeAt(0) === 45) { s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - if (ts.hasProperty(shortOptionNames, s)) { + if (s in shortOptionNames) { s = shortOptionNames[s]; } - if (ts.hasProperty(optionNameMap, s)) { + if (s in optionNameMap) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -38182,6 +47774,76 @@ var ts; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function generateTSConfig(options, fileNames) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var configurations = { + compilerOptions: serializeCompilerOptions(compilerOptions) + }; + if (fileNames && fileNames.length) { + configurations.files = fileNames; + } + return configurations; + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + for (var key in customTypeMap) { + if (customTypeMap[key] === value) { + return key; + } + } + return undefined; + } + function serializeCompilerOptions(options) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name_44 in options) { + if (ts.hasProperty(options, name_44)) { + switch (name_44) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_44]; + var optionDefinition = optionsNameMap[name_44.toLowerCase()]; + if (optionDefinition) { + var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + result[name_44] = value; + } + else { + if (optionDefinition.type === "list") { + var convertedValue = []; + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); + } + result[name_44] = convertedValue; + } + else { + result[name_44] = getNameOfCompilerOptionValue(value, customTypeMap); + } + } + } + break; + } + } + } + return result; + } + } + ts.generateTSConfig = generateTSConfig; function removeComments(jsonText) { var output = ""; var scanner = ts.createScanner(1, false, 0, jsonText); @@ -38199,15 +47861,46 @@ var ts; } return output; } - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } var errors = []; - var compilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var options = ts.extend(existingOptions, compilerOptions); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + return { + options: {}, + fileNames: [], + typingOptions: {}, + raw: json, + errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], + wildcardDirectories: {} + }; + } + var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + if (json["extends"]) { + var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; + if (typeof json["extends"] === "string") { + _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseOptions = _b[3]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + if (include && !json["include"]) { + json["include"] = include; + } + if (exclude && !json["exclude"]) { + json["exclude"] = exclude; + } + if (files && !json["files"]) { + json["files"] = files; + } + options = ts.assign({}, baseOptions, options); + } + options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; return { options: options, fileNames: fileNames, @@ -38216,6 +47909,36 @@ var ts; errors: errors, wildcardDirectories: wildcardDirectories }; + function tryExtendsName(extendedConfig) { + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + return; + } + var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = (extendedConfigPath + ".json"); + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); + errors.push.apply(errors, result.errors); + var _a = ts.map(["include", "exclude", "files"], function (key) { + if (!json[key] && extendedResult.config[key]) { + return ts.map(extendedResult.config[key], updatePath); + } + }), include = _a[0], exclude = _a[1], files = _a[2]; + return [include, exclude, files, result.options]; + } function getFileNames(errors) { var fileNames; if (ts.hasProperty(json, "files")) { @@ -38249,16 +47972,17 @@ var ts; } else { excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - excludeSpecs.push(outDir); + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } + var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { @@ -38274,7 +47998,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -38291,7 +48015,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (ts.hasProperty(optionNameMap, id)) { + if (id in optionNameMap) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -38326,7 +48050,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (ts.hasProperty(opt.type, key)) { + if (key in opt.type) { return opt.type[key]; } else { @@ -38347,8 +48071,8 @@ var ts; function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; - var literalFileMap = {}; - var wildcardFileMap = {}; + var literalFileMap = ts.createMap(); + var wildcardFileMap = ts.createMap(); if (include) { include = validateSpecs(include, errors, false); } @@ -38370,12 +48094,9 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } - if (ignoreFileNamePattern.test(file)) { - continue; - } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + if (!(key in literalFileMap) && !(key in wildcardFileMap)) { wildcardFileMap[key] = file; } } @@ -38410,20 +48131,20 @@ var ts; function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = {}; + var wildcardDirectories = ts.createMap(); if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_35 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_35)) { + var name_45 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_45)) { continue; } - var match = wildcardDirectoryPattern.exec(name_35); + var match = wildcardDirectoryPattern.exec(name_45); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_35) ? 1 : 0; - var existingFlags = ts.getProperty(wildcardDirectories, key); + var flags = watchRecursivePattern.test(name_45) ? 1 : 0; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1) { @@ -38433,12 +48154,10 @@ var ts; } } for (var key in wildcardDirectories) { - if (ts.hasProperty(wildcardDirectories, key)) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; - } + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; } } } @@ -38451,7 +48170,7 @@ var ts; for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { return true; } } @@ -38479,10 +48198,18 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var reportDiagnostic = reportDiagnosticSimply; + var defaultFormatDiagnosticsHost = { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + }; + var reportDiagnosticWorker = reportDiagnosticSimply; + function reportDiagnostic(diagnostic, host) { + reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); + } function reportDiagnostics(diagnostics, host) { - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; reportDiagnostic(diagnostic, host); } } @@ -38553,19 +48280,8 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - function getRelativeFileName(fileName, host) { - return host ? ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : fileName; - } function reportDiagnosticSimply(diagnostic, host) { - var output = ""; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var relativeFileName = getRelativeFileName(diagnostic.file.fileName, host); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine; - ts.sys.write(output); + ts.sys.write(ts.formatDiagnostics([diagnostic], host)); } var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; @@ -38574,23 +48290,23 @@ var ts; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; - var categoryFormatMap = (_a = {}, + var categoryFormatMap = ts.createMap((_a = {}, _a[ts.DiagnosticCategory.Warning] = yellowForegroundEscapeSequence, _a[ts.DiagnosticCategory.Error] = redForegroundEscapeSequence, _a[ts.DiagnosticCategory.Message] = blueForegroundEscapeSequence, _a - ); + )); function formatAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } function reportDiagnosticWithColorAndContext(diagnostic, host) { var output = ""; if (diagnostic.file) { - var start = diagnostic.start, length_3 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = getRelativeFileName(file.fileName, host); + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; var gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { @@ -38655,15 +48371,6 @@ var ts; } return s; } - function reportStatisticalValue(name, value) { - ts.sys.write(padRight(name + ":", 12) + padLeft(value.toString(), 10) + ts.sys.newLine); - } - function reportCountStatistic(name, count) { - reportStatisticalValue(name, "" + count); - } - function reportTimeStatistic(name, time) { - reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); - } function isJSONSupported() { return typeof JSON === "object" && typeof JSON.parse === "function"; } @@ -38779,7 +48486,8 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); return; } - var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), ts.sys.getCurrentDirectory()), commandLine.options, configFileName); + var cwd = ts.sys.getCurrentDirectory(); + var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd)); if (configParseResult.errors.length > 0) { reportDiagnostics(configParseResult.errors, undefined); ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); @@ -38816,9 +48524,9 @@ var ts; compilerHost.fileExists = cachedFileExists; } if (compilerOptions.pretty) { - reportDiagnostic = reportDiagnosticWithColorAndContext; + reportDiagnosticWorker = reportDiagnosticWithColorAndContext; } - cachedExistingFiles = {}; + cachedExistingFiles = ts.createMap(); var compileResult = compile(rootFileNames, compilerOptions, compilerHost); if (!ts.isWatchSet(compilerOptions)) { return ts.sys.exit(compileResult.exitStatus); @@ -38827,10 +48535,9 @@ var ts; reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); } function cachedFileExists(fileName) { - if (ts.hasProperty(cachedExistingFiles, fileName)) { - return cachedExistingFiles[fileName]; - } - return cachedExistingFiles[fileName] = hostFileExists(fileName); + return fileName in cachedExistingFiles + ? cachedExistingFiles[fileName] + : cachedExistingFiles[fileName] = hostFileExists(fileName); } function getSourceFile(fileName, languageVersion, onError) { if (cachedProgram) { @@ -38863,10 +48570,7 @@ var ts; sourceFile.fileWatcher.close(); sourceFile.fileWatcher = undefined; if (removed) { - var index = rootFileNames.indexOf(sourceFile.fileName); - if (index >= 0) { - rootFileNames.splice(index, 1); - } + ts.unorderedRemoveItem(rootFileNames, sourceFile.fileName); } startTimerForRecompilation(); } @@ -38910,12 +48614,12 @@ var ts; } ts.executeCommandLine = executeCommandLine; function compile(fileNames, compilerOptions, compilerHost) { - ts.ioReadTime = 0; - ts.ioWriteTime = 0; - ts.programTime = 0; - ts.bindTime = 0; - ts.checkTime = 0; - ts.emitTime = 0; + var hasDiagnostics = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics; + var statistics; + if (hasDiagnostics) { + ts.performance.enable(); + statistics = []; + } var program = ts.createProgram(fileNames, compilerOptions, compilerHost); var exitStatus = compileProgram(); if (compilerOptions.listFiles) { @@ -38923,7 +48627,7 @@ var ts; ts.sys.write(file.fileName + ts.sys.newLine); }); } - if (compilerOptions.diagnostics) { + if (hasDiagnostics) { var memoryUsed = ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); @@ -38934,13 +48638,24 @@ var ts; if (memoryUsed >= 0) { reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K"); } - reportTimeStatistic("I/O read", ts.ioReadTime); - reportTimeStatistic("I/O write", ts.ioWriteTime); - reportTimeStatistic("Parse time", ts.programTime); - reportTimeStatistic("Bind time", ts.bindTime); - reportTimeStatistic("Check time", ts.checkTime); - reportTimeStatistic("Emit time", ts.emitTime); - reportTimeStatistic("Total time", ts.programTime + ts.bindTime + ts.checkTime + ts.emitTime); + var programTime = ts.performance.getDuration("Program"); + var bindTime = ts.performance.getDuration("Bind"); + var checkTime = ts.performance.getDuration("Check"); + var emitTime = ts.performance.getDuration("Emit"); + if (compilerOptions.extendedDiagnostics) { + ts.performance.forEachMeasure(function (name, duration) { return reportTimeStatistic(name + " time", duration); }); + } + else { + reportTimeStatistic("I/O read", ts.performance.getDuration("I/O Read")); + reportTimeStatistic("I/O write", ts.performance.getDuration("I/O Write")); + reportTimeStatistic("Parse time", programTime); + reportTimeStatistic("Bind time", bindTime); + reportTimeStatistic("Check time", checkTime); + reportTimeStatistic("Emit time", emitTime); + } + reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime); + reportStatistics(); + ts.performance.disable(); } return { program: program, exitStatus: exitStatus }; function compileProgram() { @@ -38964,35 +48679,61 @@ var ts; } return ts.ExitStatus.Success; } + function reportStatistics() { + var nameSize = 0; + var valueSize = 0; + for (var _i = 0, statistics_1 = statistics; _i < statistics_1.length; _i++) { + var _a = statistics_1[_i], name_46 = _a.name, value = _a.value; + if (name_46.length > nameSize) { + nameSize = name_46.length; + } + if (value.length > valueSize) { + valueSize = value.length; + } + } + for (var _b = 0, statistics_2 = statistics; _b < statistics_2.length; _b++) { + var _c = statistics_2[_b], name_47 = _c.name, value = _c.value; + ts.sys.write(padRight(name_47 + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + ts.sys.newLine); + } + } + function reportStatisticalValue(name, value) { + statistics.push({ name: name, value: value }); + } + function reportCountStatistic(name, count) { + reportStatisticalValue(name, "" + count); + } + function reportTimeStatistic(name, time) { + reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); + } } function printVersion() { ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); } function printHelp() { - var output = ""; + var output = []; var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; var marginLength = Math.max(syntaxLength, examplesLength); var syntax = makePadding(marginLength - syntaxLength); syntax += "tsc [" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + " ...]"; - output += getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax); - output += ts.sys.newLine + ts.sys.newLine; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); var padding = makePadding(marginLength); - output += getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine; - output += padding + "tsc --out file.js file.ts" + ts.sys.newLine; - output += padding + "tsc @args.txt" + ts.sys.newLine; - output += ts.sys.newLine; - output += getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine; + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); var optsList = ts.filter(ts.optionDeclarations.slice(), function (v) { return !v.experimental; }); optsList.sort(function (a, b) { return ts.compareValues(a.name.toLowerCase(), b.name.toLowerCase()); }); marginLength = 0; var usageColumn = []; var descriptionColumn = []; - var optionsDescriptionMap = {}; - var _loop_3 = function(i) { + var optionsDescriptionMap = ts.createMap(); + for (var i = 0; i < optsList.length; i++) { var option = optsList[i]; if (!option.description) { - return "continue"; + continue; } var usageText_1 = " "; if (option.shortName) { @@ -39006,21 +48747,19 @@ var ts; var description = void 0; if (option.name === "lib") { description = getDiagnosticText(option.description); - var options_1 = []; + var options = []; var element = option.element; - ts.forEachKey(element.type, function (key) { - options_1.push("'" + key + "'"); - }); - optionsDescriptionMap[description] = options_1; + var typeMap = element.type; + for (var key in typeMap) { + options.push("'" + key + "'"); + } + optionsDescriptionMap[description] = options; } else { description = getDiagnosticText(option.description); } descriptionColumn.push(description); marginLength = Math.max(usageText_1.length, marginLength); - }; - for (var i = 0; i < optsList.length; i++) { - _loop_3(i); } var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; usageColumn.push(usageText); @@ -39030,17 +48769,20 @@ var ts; var usage = usageColumn[i]; var description = descriptionColumn[i]; var kindsList = optionsDescriptionMap[description]; - output += usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine; + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); if (kindsList) { - output += makePadding(marginLength + 4); + output.push(makePadding(marginLength + 4)); for (var _i = 0, kindsList_1 = kindsList; _i < kindsList_1.length; _i++) { var kind = kindsList_1[_i]; - output += kind + " "; + output.push(kind + " "); } - output += ts.sys.newLine; + output.push(ts.sys.newLine); } } - ts.sys.write(output); + for (var _a = 0, output_1 = output; _a < output_1.length; _a++) { + var line = output_1[_a]; + ts.sys.write(line); + } return; function getParamType(option) { if (option.paramType !== undefined) { @@ -39059,59 +48801,14 @@ var ts; reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), undefined); } else { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } - else { - configurations.exclude = ["node_modules"]; - if (compilerOptions.outDir) { - configurations.exclude.push(compilerOptions.outDir); - } - } - ts.sys.writeFile(file, JSON.stringify(configurations, undefined, 4)); + ts.sys.writeFile(file, JSON.stringify(ts.generateTSConfig(options, fileNames), undefined, 4)); reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file), undefined); } return; - function serializeCompilerOptions(options) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name_36 in options) { - if (ts.hasProperty(options, name_36)) { - var value = options[name_36]; - switch (name_36) { - case "init": - case "watch": - case "version": - case "help": - case "project": - break; - default: - var optionDefinition = optionsNameMap[name_36.toLowerCase()]; - if (optionDefinition) { - if (typeof optionDefinition.type === "string") { - result[name_36] = value; - } - else { - var typeMap = optionDefinition.type; - for (var key in typeMap) { - if (ts.hasProperty(typeMap, key)) { - if (typeMap[key] === value) - result[name_36] = key; - } - } - } - } - break; - } - } - } - return result; - } } var _a; })(ts || (ts = {})); +if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { + ts.sys.tryEnableSourceMapsForHost(); +} ts.executeCommandLine(ts.sys.args); diff --git a/lib/tsserver.js b/lib/tsserver.js index af6ee897902..8bb071cf4a1 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -35,14 +35,15 @@ var ts; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidType"] = 2] = "VoidType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 8] = "TypeWithCallSignature"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 9] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; (function (DiagnosticCategory) { @@ -69,8 +70,80 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var performance; + (function (performance) { + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true + ? onProfilerEvent + : function (markName) { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function mark(markName) { + if (enabled) { + marks[markName] = ts.timestamp(); + counts[markName] = (counts[markName] || 0) + 1; + profilerEvent(markName); + } + } + performance.mark = mark; + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks[endMarkName] || ts.timestamp(); + var start = startMarkName && marks[startMarkName] || profilerStart; + measures[measureName] = (measures[measureName] || 0) + (end - start); + } + } + performance.measure = measure; + function getCount(markName) { + return counts && counts[markName] || 0; + } + performance.getCount = getCount; + function getDuration(measureName) { + return measures && measures[measureName] || 0; + } + performance.getDuration = getDuration; + function forEachMeasure(cb) { + for (var key in measures) { + cb(key, measures[key]); + } + } + performance.forEachMeasure = forEachMeasure; + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var createObject = Object.create; + function createMap(template) { + var map = createObject(null); + map["__"] = undefined; + delete map["__"]; + for (var key in template) + if (hasOwnProperty.call(template, key)) { + map[key] = template[key]; + } + return map; + } + ts.createMap = createMap; function createFileMap(keyMapper) { - var files = {}; + var files = createMap(); return { get: get, set: set, @@ -91,14 +164,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return hasProperty(files, toKey(path)); + return toKey(path) in files; } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = {}; + files = createMap(); } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -124,11 +197,42 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + function every(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0, len = array.length; i < len; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findMap(array, callback) { + for (var i = 0, len = array.length; i < len; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (areEqual ? areEqual(v, value) : v === value) { + if (v === value) { return true; } } @@ -159,9 +263,9 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var v = array_2[_i]; - if (predicate(v)) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { count++; } } @@ -170,23 +274,47 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { - var result; if (array) { - result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - result.push(item); + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; } + return result; } } - return result; + return array; } ts.filter = filter; + function removeWhere(array, f) { + var outIndex = 0; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var item = array_2[_i]; + if (!f(item)) { + array[outIndex] = item; + outIndex++; + } + } + if (outIndex !== array.length) { + array.length = outIndex; + return true; + } + return false; + } + ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var item = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { array[outIndex] = item; outIndex++; @@ -199,14 +327,114 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; - result.push(f(v)); + for (var i = 0; i < array.length; i++) { + var v = array[i]; + result.push(f(v, i)); } } return result; } ts.map = map; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + function flatMap(array, mapfn) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMap = flatMap; + function span(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!f(array[i], i)) { + return [array.slice(0, i), array.slice(i)]; + } + } + return [array.slice(0), []]; + } + return undefined; + } + ts.span = span; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapObject(object, f) { + var result; + if (object) { + result = {}; + for (var _i = 0, _a = getOwnKeys(object); _i < _a.length; _i++) { + var v = _a[_i]; + var _b = f(v, object[v]) || [undefined, undefined], key = _b[0], value = _b[1]; + if (key !== undefined) { + result[key] = value; + } + } + } + return result; + } + ts.mapObject = mapObject; function concatenate(array1, array2) { if (!array2 || !array2.length) return array1; @@ -219,20 +447,42 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; - if (!contains(result, item, areEqual)) { - result.push(item); + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; + for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { + var res = result_1[_a]; + if (areEqual ? areEqual(res, item) : res === item) { + continue loop; + } } + result.push(item); } } return result; } ts.deduplicate = deduplicate; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -242,7 +492,9 @@ var ts; if (to && from) { for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { var v = from_1[_i]; - to.push(v); + if (v !== undefined) { + to.push(v); + } } } } @@ -257,11 +509,28 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function firstOrUndefined(array) { + return array && array.length > 0 + ? array[0] + : undefined; + } + ts.firstOrUndefined = firstOrUndefined; + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; function lastOrUndefined(array) { - if (array.length === 0) { - return undefined; - } - return array[array.length - 1]; + return array && array.length > 0 + ? array[array.length - 1] + : undefined; } ts.lastOrUndefined = lastOrUndefined; function binarySearch(array, value) { @@ -283,11 +552,12 @@ var ts; return ~low; } ts.binarySearch = binarySearch; - function reduceLeft(array, f, initial) { - if (array) { - var count = array.length; - if (count > 0) { - var pos = 0; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -296,8 +566,8 @@ var ts; else { result = initial; } - while (pos < count) { - result = f(result, array[pos]); + while (pos <= end) { + result = f(result, array[pos], pos); pos++; } return result; @@ -306,10 +576,12 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial) { + function reduceRight(array, f, initial, start, count) { if (array) { - var pos = array.length - 1; - if (pos >= 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start > size - 1 ? size - 1 : start; + var end = count === undefined || pos - count < 0 ? 0 : pos - count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -318,8 +590,8 @@ var ts; else { result = initial; } - while (pos >= 0) { - result = f(result, array[pos]); + while (pos >= end) { + result = f(result, array[pos], pos); pos--; } return result; @@ -333,18 +605,103 @@ var ts; return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; - function getKeys(map) { - var keys = []; - for (var key in map) { - keys.push(key); - } - return keys; - } - ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; + function getOwnKeys(map) { + var keys = []; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function forEachProperty(map, callback) { + var result; + for (var key in map) { + if (result = callback(map[key], key)) + break; + } + return result; + } + ts.forEachProperty = forEachProperty; + function someProperties(map, predicate) { + for (var key in map) { + if (!predicate || predicate(map[key], key)) + return true; + } + return false; + } + ts.someProperties = someProperties; + function copyProperties(source, target) { + for (var key in source) { + target[key] = source[key]; + } + } + ts.copyProperties = copyProperties; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var _b = 0, _c = getOwnKeys(arg); _b < _c.length; _b++) { + var p = _c[_b]; + t[p] = arg[p]; + } + } + return t; + } + ts.assign = assign; + function reduceProperties(map, callback, initial) { + var result = initial; + for (var key in map) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceProperties = reduceProperties; + function reduceOwnProperties(map, callback, initial) { + var result = initial; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceOwnProperties = reduceOwnProperties; + function equalOwnProperties(left, right, equalityComparer) { + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key) === undefined) + return false; + if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + return false; + } + for (var key in right) + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; function isEmpty(map) { for (var id in map) { if (hasProperty(map, id)) { @@ -354,75 +711,56 @@ var ts; return true; } ts.isEmpty = isEmpty; + function cloneMap(map) { + var clone = createMap(); + copyProperties(map, clone); + return clone; + } + ts.cloneMap = cloneMap; function clone(object) { var result = {}; for (var id in object) { - result[id] = object[id]; + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in first) { - result[id] = first[id]; - } - for (var id in second) { - if (!hasProperty(result, id)) { + for (var id in second) + if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - } + for (var id in first) + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } return result; } ts.extend = extend; - function forEachValue(map, callback) { - var result; - for (var id in map) { - if (result = callback(map[id])) - break; + function multiMapAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + return values; } - return result; - } - ts.forEachValue = forEachValue; - function forEachKey(map, callback) { - var result; - for (var id in map) { - if (result = callback(id)) - break; - } - return result; - } - ts.forEachKey = forEachKey; - function lookUp(map, key) { - return hasProperty(map, key) ? map[key] : undefined; - } - ts.lookUp = lookUp; - function copyMap(source, target) { - for (var p in source) { - target[p] = source[p]; + else { + return map[key] = [value]; } } - ts.copyMap = copyMap; - function arrayToMap(array, makeKey) { - var result = {}; - forEach(array, function (value) { - result[makeKey(value)] = value; - }); - return result; - } - ts.arrayToMap = arrayToMap; - function reduceProperties(map, callback, initial) { - var result = initial; - if (map) { - for (var key in map) { - if (hasProperty(map, key)) { - result = callback(result, map[key], String(key)); - } + ts.multiMapAdd = multiMapAdd; + function multiMapRemove(map, key, value) { + var values = map[key]; + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + delete map[key]; } } - return result; } - ts.reduceProperties = reduceProperties; + ts.multiMapRemove = multiMapRemove; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -444,9 +782,7 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] - ? ts.localizedDiagnosticMessages[message.key] - : message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -631,6 +967,7 @@ var ts; } ts.getRootLength = getRootLength; ts.directorySeparator = "/"; + var directorySeparatorCharCode = 47; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; @@ -652,10 +989,21 @@ var ts; function normalizePath(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); + var root = path.substr(0, rootLength); var normalized = getNormalizedParts(path, rootLength); - return path.substr(0, rootLength) + normalized.join(ts.directorySeparator); + if (normalized.length) { + var joinedParts = root + normalized.join(ts.directorySeparator); + return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + } + else { + return root; + } } ts.normalizePath = normalizePath; + function pathEndsWithDirectorySeparator(path) { + return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; + } + ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; function getDirectoryPath(path) { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); } @@ -830,10 +1178,17 @@ var ts; return true; } ts.containsPath = containsPath; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - var pathLen = path.length; - var extLen = extension.length; - return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; + return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -848,10 +1203,15 @@ var ts; ts.fileExtensionIsAny = fileExtensionIsAny; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; + var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; + var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } + var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; + var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; + var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -874,7 +1234,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -886,6 +1246,16 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } + if (usage !== "exclude") { + if (component.charCodeAt(0) === 42) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + subpattern += "[^./]"; + component = component.substr(1); + } + } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -906,8 +1276,14 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildcardCharacter(match) { - return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + function replaceWildCardCharacterFiles(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); + } + function replaceWildCardCharacterOther(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1006,6 +1382,7 @@ var ts; } ts.getScriptKindFromFileName = getScriptKindFromFileName; ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { @@ -1068,9 +1445,13 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; + return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -1090,14 +1471,21 @@ var ts; function Signature(checker) { } function Node(kind, pos, end) { + this.id = 0; this.kind = kind; this.pos = pos; this.end = end; this.flags = 0; + this.modifierFlagsCache = 0; + this.transformFlags = 0; this.parent = undefined; + this.original = undefined; + this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -1105,9 +1493,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel = 0; + var currentAssertionLevel; function shouldAssert(level) { - return currentAssertionLevel >= level; + return getCurrentAssertionLevel() >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1125,20 +1513,56 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; + function getCurrentAssertionLevel() { + if (currentAssertionLevel !== undefined) { + return currentAssertionLevel; + } + if (ts.sys === undefined) { + return 0; + } + var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); + currentAssertionLevel = developmentMode + ? 1 + : 0; + return currentAssertionLevel; + } })(Debug = ts.Debug || (ts.Debug = {})); - function copyListRemovingItem(item, list) { - var copiedList = []; - for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { - var e = list_1[_i]; - if (e !== item) { - copiedList.push(e); + function getEnvironmentVariable(name, host) { + if (host && host.getEnvironmentVariable) { + return host.getEnvironmentVariable(name); + } + if (ts.sys && ts.sys.getEnvironmentVariable) { + return ts.sys.getEnvironmentVariable(name); + } + return ""; + } + ts.getEnvironmentVariable = getEnvironmentVariable; + function orderedRemoveItemAt(array, index) { + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + function unorderedRemoveItem(array, item) { + unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + break; } } - return copiedList; } - ts.copyListRemovingItem = copyListRemovingItem; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? (function (fileName) { return fileName; }) : (function (fileName) { return fileName.toLowerCase(); }); } @@ -1229,7 +1653,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - return { + var wscriptSystem = { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -1248,7 +1672,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!wscriptSystem.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -1259,6 +1683,9 @@ var ts; return shell.CurrentDirectory; }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%" + name + "%"); + }, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -1268,6 +1695,7 @@ var ts; } } }; + return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -1276,13 +1704,13 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = {}; - var fileWatcherCallbacks = {}; + var dirWatchers = ts.createMap(); + var fileWatcherCallbacks = ts.createMap(); return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - if (ts.hasProperty(dirWatchers, dirName)) { - var watcher = dirWatchers[dirName]; + var watcher = dirWatchers[dirName]; + if (watcher) { watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -1291,23 +1719,18 @@ var ts; } } function addDirWatcher(dirPath) { - if (ts.hasProperty(dirWatchers, dirPath)) { - var watcher_1 = dirWatchers[dirPath]; - watcher_1.referenceCount += 1; + var watcher = dirWatchers[dirPath]; + if (watcher) { + watcher.referenceCount += 1; return; } - var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - fileWatcherCallbacks[filePath].push(callback); - } - else { - fileWatcherCallbacks[filePath] = [callback]; - } + ts.multiMapAdd(fileWatcherCallbacks, filePath, callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1319,21 +1742,13 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); - if (newCallbacks.length === 0) { - delete fileWatcherCallbacks[filePath]; - } - else { - fileWatcherCallbacks[filePath] = newCallbacks; - } - } + ts.multiMapRemove(fileWatcherCallbacks, filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { var fileName = typeof relativeFileName !== "string" ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -1438,9 +1853,9 @@ var ts; return fileSystemEntryExists(path, 1); } function getDirectories(path) { - return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - return { + var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -1490,7 +1905,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!nodeSystem.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -1501,6 +1916,9 @@ var ts; return process.cwd(); }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -1536,8 +1954,16 @@ var ts; }, realpath: function (path) { return _fs.realpathSync(path); + }, + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (e) { + } } }; + return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -1562,6 +1988,7 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), readDirectory: function (path, extensions, excludes, includes) { var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); @@ -1792,9 +2219,9 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher_1311", message: "Async functions are only available when targeting ECMAScript 2015 or higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, @@ -1849,12 +2276,11 @@ var ts; Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, - Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_2349", message: "Cannot invoke an expression whose type lacks a call signature." }, + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, @@ -1996,7 +2422,6 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_yield_expressions_2504", message: "No best common type exists among yield expressions." }, A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, @@ -2013,7 +2438,7 @@ var ts; A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, @@ -2026,6 +2451,7 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, + Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2073,6 +2499,13 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, + A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, + Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2143,7 +2576,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -2171,6 +2604,7 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2201,6 +2635,7 @@ var ts; VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, + STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, @@ -2287,10 +2722,12 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, - Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, + Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, + Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, + Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2299,7 +2736,6 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -2314,6 +2750,8 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2341,7 +2779,9 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." } + Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } }; })(ts || (ts = {})); var ts; @@ -2350,7 +2790,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115, "any": 117, "as": 116, @@ -2474,7 +2914,7 @@ var ts; "|=": 67, "^=": 68, "@": 55 - }; + }); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -2515,9 +2955,7 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - if (source.hasOwnProperty(name_4)) { - result[source[name_4]] = name_4; - } + result[source[name_4]] = name_4; } return result; } @@ -2644,7 +3082,7 @@ var ts; ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { if (stopAtComments === void 0) { stopAtComments = false; } - if (!(pos >= 0)) { + if (ts.positionIsSynthesized(pos)) { return pos; } while (true) { @@ -2767,10 +3205,15 @@ var ts; pos = pos + shebang.length; return pos; } - function getCommentRanges(text, pos, trailing) { - var result; + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; var collecting = trailing || pos === 0; - while (pos < text.length) { + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13: @@ -2780,11 +3223,11 @@ var ts; case 10: pos++; if (trailing) { - return result; + break scan; } collecting = true; - if (result && result.length) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; } continue; case 9: @@ -2819,34 +3262,67 @@ var ts; } } if (collecting) { - if (!result) { - result = []; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + return accumulator; + } + hasPendingCommentRange = false; } - result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; } continue; } - break; + break scan; default: if (ch > 127 && (isWhiteSpace(ch))) { - if (result && result.length && isLineBreak(ch)) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; } pos++; continue; } - break; + break scan; } - return result; } - return result; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + if (!comments) { + comments = []; + } + comments.push({ pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + return comments; } function getLeadingCommentRanges(text, pos) { - return getCommentRanges(text, pos, false); + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getLeadingCommentRanges = getLeadingCommentRanges; function getTrailingCommentRanges(text, pos) { - return getCommentRanges(text, pos, true); + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { @@ -2867,7 +3343,7 @@ var ts; ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; - function isIdentifier(name, languageVersion) { + function isIdentifierText(name, languageVersion) { if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { return false; } @@ -2878,7 +3354,7 @@ var ts; } return true; } - ts.isIdentifier = isIdentifier; + ts.isIdentifierText = isIdentifierText; function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } var pos; @@ -2907,6 +3383,7 @@ var ts; reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, scanJSDocToken: scanJSDocToken, @@ -2990,7 +3467,8 @@ var ts; } return value; } - function scanString() { + function scanString(allowEscapes) { + if (allowEscapes === void 0) { allowEscapes = true; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -3008,7 +3486,7 @@ var ts; pos++; break; } - if (ch === 92) { + if (ch === 92 && allowEscapes) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; @@ -3709,42 +4187,61 @@ var ts; } return token; } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34: + case 39: + tokenValue = scanString(false); + return token = 9; + default: + return scan(); + } + } function scanJSDocToken() { if (pos >= end) { return token = 1; } startPos = pos; - var ch = text.charCodeAt(pos); - while (pos < end) { - ch = text.charCodeAt(pos); - if (isWhiteSpaceSingleLine(ch)) { - pos++; - } - else { - break; - } - } tokenPos = pos; + var ch = text.charCodeAt(pos); switch (ch) { + case 9: + case 11: + case 12: + case 32: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5; case 64: - return pos += 1, token = 55; + pos++; + return token = 55; case 10: case 13: - return pos += 1, token = 4; + pos++; + return token = 4; case 42: - return pos += 1, token = 37; + pos++; + return token = 37; case 123: - return pos += 1, token = 15; + pos++; + return token = 15; case 125: - return pos += 1, token = 16; + pos++; + return token = 16; case 91: - return pos += 1, token = 19; + pos++; + return token = 19; case 93: - return pos += 1, token = 20; + pos++; + return token = 20; case 61: - return pos += 1, token = 56; + pos++; + return token = 56; case 44: - return pos += 1, token = 24; + pos++; + return token = 24; } if (isIdentifierStart(ch, 2)) { pos++; @@ -3858,6 +4355,11 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean", + experimental: true + }, { name: "emitBOM", type: "boolean" @@ -3888,10 +4390,10 @@ var ts; }, { name: "jsx", - type: { + type: ts.createMap({ "preserve": 1, "react": 2 - }, + }), paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -3918,7 +4420,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -3926,16 +4428,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }, + }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: { + type: ts.createMap({ "crlf": 0, "lf": 1 - }, + }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -3953,6 +4455,10 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, + { + name: "noErrorTruncation", + type: "boolean" + }, { name: "noImplicitAny", type: "boolean", @@ -3966,12 +4472,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Locals + description: ts.Diagnostics.Report_errors_on_unused_locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters }, { name: "noLib", @@ -4076,12 +4582,12 @@ var ts; { name: "target", shortName: "t", - type: { + type: ts.createMap({ "es3": 0, "es5": 1, "es6": 2, "es2015": 2 - }, + }), description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -4110,11 +4616,12 @@ var ts; }, { name: "moduleResolution", - type: { + type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }, - description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 + }), + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + paramType: ts.Diagnostics.STRATEGY }, { name: "allowUnusedLabels", @@ -4214,7 +4721,7 @@ var ts; type: "list", element: { name: "lib", - type: { + type: ts.createMap({ "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", "es2015": "lib.es2015.d.ts", @@ -4222,6 +4729,7 @@ var ts; "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", "dom": "lib.dom.d.ts", + "dom.iterable": "lib.dom.iterable.d.ts", "webworker": "lib.webworker.d.ts", "scripthost": "lib.scripthost.d.ts", "es2015.core": "lib.es2015.core.d.ts", @@ -4236,7 +4744,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - } + }) }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -4248,6 +4756,11 @@ var ts; name: "strictNullChecks", type: "boolean", description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "importHelpers", + type: "boolean", + description: ts.Diagnostics.Import_emit_helpers_from_tslib } ]; ts.typingOptionDeclarations = [ @@ -4272,13 +4785,19 @@ var ts; } } ]; + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1, + noImplicitAny: false, + sourceMap: false + }; var optionNameMapCache; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = {}; - var shortOptionNames = {}; + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -4291,16 +4810,16 @@ var ts; ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - ts.forEachKey(opt.type, function (key) { + for (var key in opt.type) { namesOfType.push(" '" + key + "'"); - }); + } return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (ts.hasProperty(map, key)) { + if (key in map) { return map[key]; } else { @@ -4349,10 +4868,10 @@ var ts; } else if (s.charCodeAt(0) === 45) { s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - if (ts.hasProperty(shortOptionNames, s)) { + if (s in shortOptionNames) { s = shortOptionNames[s]; } - if (ts.hasProperty(optionNameMap, s)) { + if (s in optionNameMap) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -4453,6 +4972,76 @@ var ts; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function generateTSConfig(options, fileNames) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var configurations = { + compilerOptions: serializeCompilerOptions(compilerOptions) + }; + if (fileNames && fileNames.length) { + configurations.files = fileNames; + } + return configurations; + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + for (var key in customTypeMap) { + if (customTypeMap[key] === value) { + return key; + } + } + return undefined; + } + function serializeCompilerOptions(options) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name_5 in options) { + if (ts.hasProperty(options, name_5)) { + switch (name_5) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_5]; + var optionDefinition = optionsNameMap[name_5.toLowerCase()]; + if (optionDefinition) { + var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + result[name_5] = value; + } + else { + if (optionDefinition.type === "list") { + var convertedValue = []; + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); + } + result[name_5] = convertedValue; + } + else { + result[name_5] = getNameOfCompilerOptionValue(value, customTypeMap); + } + } + } + break; + } + } + } + return result; + } + } + ts.generateTSConfig = generateTSConfig; function removeComments(jsonText) { var output = ""; var scanner = ts.createScanner(1, false, 0, jsonText); @@ -4470,15 +5059,46 @@ var ts; } return output; } - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } var errors = []; - var compilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var options = ts.extend(existingOptions, compilerOptions); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + return { + options: {}, + fileNames: [], + typingOptions: {}, + raw: json, + errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], + wildcardDirectories: {} + }; + } + var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + if (json["extends"]) { + var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; + if (typeof json["extends"] === "string") { + _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseOptions = _b[3]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + if (include && !json["include"]) { + json["include"] = include; + } + if (exclude && !json["exclude"]) { + json["exclude"] = exclude; + } + if (files && !json["files"]) { + json["files"] = files; + } + options = ts.assign({}, baseOptions, options); + } + options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; return { options: options, fileNames: fileNames, @@ -4487,6 +5107,36 @@ var ts; errors: errors, wildcardDirectories: wildcardDirectories }; + function tryExtendsName(extendedConfig) { + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + return; + } + var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); + errors.push.apply(errors, result.errors); + var _a = ts.map(["include", "exclude", "files"], function (key) { + if (!json[key] && extendedResult.config[key]) { + return ts.map(extendedResult.config[key], updatePath); + } + }), include = _a[0], exclude = _a[1], files = _a[2]; + return [include, exclude, files, result.options]; + } function getFileNames(errors) { var fileNames; if (ts.hasProperty(json, "files")) { @@ -4520,16 +5170,17 @@ var ts; } else { excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - excludeSpecs.push(outDir); + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } + var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { @@ -4545,7 +5196,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -4562,7 +5213,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (ts.hasProperty(optionNameMap, id)) { + if (id in optionNameMap) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -4597,7 +5248,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (ts.hasProperty(opt.type, key)) { + if (key in opt.type) { return opt.type[key]; } else { @@ -4618,8 +5269,8 @@ var ts; function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; - var literalFileMap = {}; - var wildcardFileMap = {}; + var literalFileMap = ts.createMap(); + var wildcardFileMap = ts.createMap(); if (include) { include = validateSpecs(include, errors, false); } @@ -4641,12 +5292,9 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } - if (ignoreFileNamePattern.test(file)) { - continue; - } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + if (!(key in literalFileMap) && !(key in wildcardFileMap)) { wildcardFileMap[key] = file; } } @@ -4681,20 +5329,20 @@ var ts; function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = {}; + var wildcardDirectories = ts.createMap(); if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_5 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_5)) { + var name_6 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_6)) { continue; } - var match = wildcardDirectoryPattern.exec(name_5); + var match = wildcardDirectoryPattern.exec(name_6); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_5) ? 1 : 0; - var existingFlags = ts.getProperty(wildcardDirectories, key); + var flags = watchRecursivePattern.test(name_6) ? 1 : 0; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1) { @@ -4704,12 +5352,10 @@ var ts; } } for (var key in wildcardDirectories) { - if (ts.hasProperty(wildcardDirectories, key)) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; - } + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; } } } @@ -4722,7 +5368,7 @@ var ts; for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { return true; } } @@ -4750,6 +5396,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -4797,24 +5444,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function mapIsEqualTo(map1, map2) { - if (!map1 || !map2) { - return map1 === map2; - } - return containsAll(map1, map2) && containsAll(map2, map1); - } - ts.mapIsEqualTo = mapIsEqualTo; - function containsAll(map, other) { - for (var key in map) { - if (!ts.hasProperty(map, key)) { - continue; - } - if (!ts.hasProperty(other, key) || map[key] !== other[key]) { - return false; - } - } - return true; - } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -4832,7 +5461,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -4841,14 +5470,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = {}; + sourceFile.resolvedModules = ts.createMap(); } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = {}; + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -4867,7 +5496,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; + var oldResolution = oldResolutions && oldResolutions[names[i]]; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -4880,17 +5509,17 @@ var ts; ts.hasChangesInResolutions = hasChangesInResolutions; function containsParseError(node) { aggregateChildData(node); - return (node.flags & 268435456) !== 0; + return (node.flags & 2097152) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 536870912)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864) !== 0) || + if (!(node.flags & 4194304)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 524288) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.flags |= 268435456; + node.flags |= 2097152; } - node.flags |= 536870912; + node.flags |= 4194304; } } function getSourceFileOfNode(node) { @@ -4927,6 +5556,10 @@ var ts; return node.pos; } ts.getStartPosOfNode = getStartPosOfNode; + function isDefined(value) { + return value !== undefined; + } + ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -4947,7 +5580,7 @@ var ts; } ts.getEndLinePosition = getEndLinePosition; function nodeIsMissing(node) { - if (!node) { + if (node === undefined) { return true; } return node.pos === node.end && node.pos >= 0 && node.kind !== 1; @@ -4967,16 +5600,20 @@ var ts; if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { return getTokenPosOfNode(node.jsDocComments[0]); } - if (node.kind === 282 && node._children.length > 0) { + if (node.kind === 286 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 281; + return node.kind >= 257 && node.kind <= 282; } ts.isJSDocNode = isJSDocNode; + function isJSDocTag(node) { + return node.kind >= 273 && node.kind <= 285; + } + ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5005,6 +5642,50 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getLiteralText(node, sourceFile, languageVersion) { + if (languageVersion < 2 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + return getQuotedEscapedLiteralText('"', node.text, '"'); + } + if (!nodeIsSynthesized(node) && node.parent) { + var text = getSourceTextOfNodeFromSourceFile(sourceFile, node); + if (languageVersion < 2 && isBinaryOrOctalIntegerLiteral(node, text)) { + return node.text; + } + return text; + } + switch (node.kind) { + case 9: + return getQuotedEscapedLiteralText('"', node.text, '"'); + case 11: + return getQuotedEscapedLiteralText("`", node.text, "`"); + case 12: + return getQuotedEscapedLiteralText("`", node.text, "${"); + case 13: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 14: + return getQuotedEscapedLiteralText("}", node.text, "`"); + case 8: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function isBinaryOrOctalIntegerLiteral(node, text) { + if (node.kind === 8 && text.length > 1) { + switch (text.charCodeAt(1)) { + case 98: + case 66: + case 111: + case 79: + return true; + } + } + return false; + } + ts.isBinaryOrOctalIntegerLiteral = isBinaryOrOctalIntegerLiteral; + function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { + return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + } function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5018,7 +5699,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 3072) !== 0 || + return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -5027,19 +5708,21 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { return node.kind === 225 && (!node.body); } - ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || - isFunctionLike(node) || - isFunctionBlock(node); + isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { - return !!(module.flags & 131072); + return !!(module.flags & 512); } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { @@ -5055,26 +5738,35 @@ var ts; return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 256: + case 227: + case 252: + case 225: + case 206: + case 207: + case 208: + case 148: + case 147: + case 149: + case 150: + case 220: + case 179: + case 180: + return true; + case 199: + return parentNode && !isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { - if (isFunctionLike(current)) { + if (isBlockScope(current, current.parent)) { return current; } - switch (current.kind) { - case 256: - case 227: - case 252: - case 225: - case 206: - case 207: - case 208: - return current; - case 199: - if (!isFunctionLike(current.parent)) { - return current; - } - } current = current.parent; } } @@ -5176,34 +5868,13 @@ var ts; return node.kind === 224 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 || isBindingPattern(node))) { - node = node.parent; - } - return node; - } - function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 218) { - node = node.parent; - } - if (node && node.kind === 219) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 200) { - flags |= node.flags; - } - return flags; - } - ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 2048); + return !!(ts.getCombinedNodeFlags(node) & 2) + || !!(ts.getCombinedModifierFlags(node) & 2048); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 1024); + return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; function isSuperCallExpression(n) { @@ -5244,7 +5915,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; - function isTypeNode(node) { + function isPartOfTypeNode(node) { if (154 <= node.kind && node.kind <= 166) { return true; } @@ -5268,7 +5939,7 @@ var ts; else if (node.parent.kind === 172 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 139: case 172: case 97: @@ -5313,7 +5984,7 @@ var ts; } return false; } - ts.isTypeNode = isTypeNode; + ts.isPartOfTypeNode = isPartOfTypeNode; function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { @@ -5359,13 +6030,13 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_6 = node.name; - if (name_6 && name_6.kind === 140) { - traverse(name_6.expression); + var name_7 = node.name; + if (name_7 && name_7.kind === 140) { + traverse(name_7.expression); return; } } - else if (!isTypeNode(node)) { + else if (!isPartOfTypeNode(node)) { ts.forEachChild(node, traverse); } } @@ -5578,18 +6249,19 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; - function isSuperPropertyOrElementAccess(node) { - return (node.kind === 172 - || node.kind === 173) + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 172 || kind === 173) && node.expression.kind === 95; } - ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; + ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { case 155: return node.typeName; case 194: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -5599,6 +6271,18 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function isCallLikeExpression(node) { + switch (node.kind) { + case 174: + case 175: + case 176: + case 143: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { if (node.kind === 176) { return node.tag; @@ -5632,14 +6316,20 @@ var ts; && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function isPropertyAccessExpression(node) { - return node.kind === 172; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isElementAccessExpression(node) { - return node.kind === 173; + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 221: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 147: + case 150: + return ts.forEach(node.parameters, nodeIsDecorated); + } } - ts.isElementAccessExpression = isElementAccessExpression; + ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; if (parent.kind === 243 || @@ -5650,7 +6340,7 @@ var ts; return false; } ts.isJSXTagName = isJSXTagName; - function isExpression(node) { + function isPartOfExpression(node) { switch (node.kind) { case 97: case 95: @@ -5745,16 +6435,16 @@ var ts; case 194: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: - if (isExpression(parent_3)) { + if (isPartOfExpression(parent_3)) { return true; } } } return false; } - ts.isExpression = isExpression; + ts.isPartOfExpression = isPartOfExpression; function isExternalModuleNameRelative(moduleName) { - return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + return /^\.\.?($|[\\/])/.test(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { @@ -5781,7 +6471,7 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 134217728); + return node && !!(node.flags & 1048576); } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression, checkArgumentIsStringLiteral) { @@ -5861,6 +6551,22 @@ var ts; } } ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + if (node.kind === 229) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { + return importClause.namedBindings; + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 230 + && node.importClause + && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { @@ -5887,31 +6593,62 @@ var ts; if (!node) { return undefined; } - var jsDocComments = getJSDocComments(node, checkParentVariableStatement); - if (!jsDocComments) { + var jsDocTags = getJSDocTags(node, checkParentVariableStatement); + if (!jsDocTags) { return undefined; } - for (var _i = 0, jsDocComments_1 = jsDocComments; _i < jsDocComments_1.length; _i++) { - var jsDocComment = jsDocComments_1[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === kind) { - return tag; - } + for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { + var tag = jsDocTags_1[_i]; + if (tag.kind === kind) { + return tag; } } } - function getJSDocComments(node, checkParentVariableStatement) { - if (node.jsDocComments) { - return node.jsDocComments; + function append(previous, additional) { + if (additional) { + if (!previous) { + previous = []; + } + for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { + var x = additional_1[_i]; + previous.push(x); + } } + return previous; + } + function getJSDocComments(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); + } + ts.getJSDocComments = getJSDocComments; + function getJSDocTags(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { + var result = []; + for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { + var doc = docs_1[_i]; + if (doc.tags) { + result.push.apply(result, doc.tags); + } + } + return result; + }, function (tags) { return tags; }); + } + function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { + var result = undefined; if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 218 && - node.parent.initializer === node && + var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && + (node.parent).initializer === node && node.parent.parent.parent.kind === 200; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + var isVariableOfVariableDeclarationStatement = isVariableLike(node) && + node.parent.parent.kind === 200; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : + isVariableOfVariableDeclarationStatement ? node.parent.parent : + undefined; if (variableStatementNode) { - return variableStatementNode.jsDocComments; + result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 225 && + node.parent && node.parent.kind === 225) { + result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } var parent_4 = node.parent; var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && @@ -5919,14 +6656,52 @@ var ts; parent_4.operatorToken.kind === 56 && parent_4.parent.kind === 202; if (isSourceOfAssignmentExpressionStatement) { - return parent_4.parent.jsDocComments; + result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); } var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; if (isPropertyAssignmentExpression) { - return parent_4.jsDocComments; + result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 142) { + var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); + if (paramTags) { + result = append(result, getTags(paramTags)); + } } } - return undefined; + if (isVariableLike(node) && node.initializer) { + result = append(result, getJSDocs(node.initializer, false, getDocs, getTags)); + } + if (node.jsDocComments) { + if (result) { + result = append(result, getDocs(node.jsDocComments)); + } + else { + return getDocs(node.jsDocComments); + } + } + return result; + } + function getJSDocParameterTag(param, checkParentVariableStatement) { + var func = param.parent; + var tags = getJSDocTags(func, checkParentVariableStatement); + if (!param.name) { + var i = func.parameters.indexOf(param); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275; }); + if (paramTags && 0 <= i && i < paramTags.length) { + return [paramTags[i]]; + } + } + else if (param.name.kind === 69) { + var name_8 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); + if (paramTags) { + return paramTags; + } + } + else { + return undefined; + } } function getJSDocTypeTag(node) { return getJSDocTag(node, 277, false); @@ -5943,19 +6718,16 @@ var ts; function getCorrespondingJSDocParameterTag(parameter) { if (parameter.name && parameter.name.kind === 69) { var parameterName = parameter.name.text; - var jsDocComments = getJSDocComments(parameter.parent, true); - if (jsDocComments) { - for (var _i = 0, jsDocComments_2 = jsDocComments; _i < jsDocComments_2.length; _i++) { - var jsDocComment = jsDocComments_2[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === 275) { - var parameterTag = tag; - var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_7.text === parameterName) { - return parameterTag; - } - } + var jsDocTags = getJSDocTags(parameter.parent, true); + if (!jsDocTags) { + return undefined; + } + for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { + var tag = jsDocTags_2[_i]; + if (tag.kind === 275) { + var parameterTag = tag; + if (parameterTag.parameterName.text === parameterName) { + return parameterTag; } } } @@ -5972,7 +6744,7 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 134217728)) { + if (node && (node.flags & 1048576)) { if (node.type && node.type.kind === 270) { return true; } @@ -5988,22 +6760,6 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isLiteralKind(kind) { - return 8 <= kind && kind <= 11; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 || kind === 11; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isTemplateLiteralKind(kind) { - return 11 <= kind && kind <= 14; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isBindingPattern(node) { - return !!node && (node.kind === 168 || node.kind === 167); - } - ts.isBindingPattern = isBindingPattern; function isAssignmentTarget(node) { while (node.parent.kind === 178) { node = node.parent; @@ -6019,14 +6775,14 @@ var ts; continue; } return parent_5.kind === 187 && - parent_5.operatorToken.kind === 56 && + isAssignmentOperator(parent_5.operatorToken.kind) && parent_5.left === node || (parent_5.kind === 207 || parent_5.kind === 208) && parent_5.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; - function isNodeDescendentOf(node, ancestor) { + function isNodeDescendantOf(node, ancestor) { while (node) { if (node === ancestor) return true; @@ -6034,10 +6790,10 @@ var ts; } return false; } - ts.isNodeDescendentOf = isNodeDescendentOf; + ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (node.flags & 2 || (node.kind === 256 && node.isDeclarationFile)) { + if (hasModifier(node, 2) || (node.kind === 256 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6045,84 +6801,6 @@ var ts; return false; } ts.isInAmbientContext = isInAmbientContext; - function isDeclaration(node) { - switch (node.kind) { - case 180: - case 169: - case 221: - case 192: - case 148: - case 224: - case 255: - case 238: - case 220: - case 179: - case 149: - case 231: - case 229: - case 234: - case 222: - case 147: - case 146: - case 225: - case 232: - case 142: - case 253: - case 145: - case 144: - case 150: - case 254: - case 223: - case 141: - case 218: - case 279: - return true; - } - return false; - } - ts.isDeclaration = isDeclaration; - function isStatement(n) { - switch (n.kind) { - case 210: - case 209: - case 217: - case 204: - case 202: - case 201: - case 207: - case 208: - case 206: - case 203: - case 214: - case 211: - case 213: - case 215: - case 216: - case 200: - case 205: - case 212: - case 235: - return true; - default: - return false; - } - } - ts.isStatement = isStatement; - function isClassElement(n) { - switch (n.kind) { - case 148: - case 145: - case 147: - case 149: - case 150: - case 146: - case 153: - return true; - default: - return false; - } - } - ts.isClassElement = isClassElement; function isDeclarationName(name) { if (name.kind !== 69 && name.kind !== 9 && name.kind !== 8) { return false; @@ -6182,9 +6860,13 @@ var ts; node.kind === 232 || node.kind === 234 || node.kind === 238 || - node.kind === 235 && node.expression.kind === 69; + node.kind === 235 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + return isEntityNameExpression(node.expression); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -6272,7 +6954,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node); + return isFunctionLike(node) && hasModifier(node, 256) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; function isStringOrNumericLiteral(kind) { @@ -6348,63 +7030,238 @@ var ts; return node; } ts.getRootDeclaration = getRootDeclaration; - function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 225 || n.kind === 256; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 148 + || kind === 179 + || kind === 220 + || kind === 180 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 225 + || kind === 256; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneNode(node, location, flags, parent) { - var clone = location !== undefined - ? ts.createNode(node.kind, location.pos, location.end) - : createSynthesizedNode(node.kind); - for (var key in node) { - if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { - continue; - } - clone[key] = node[key]; - } - if (flags !== undefined) { - clone.flags = flags; - } - if (parent !== undefined) { - clone.parent = parent; - } - return clone; - } - ts.cloneNode = cloneNode; - function cloneEntityName(node, parent) { - var clone = cloneNode(node, node, node.flags, parent); - if (isQualifiedName(clone)) { - var left = clone.left, right = clone.right; - clone.left = cloneEntityName(left, clone); - clone.right = cloneNode(right, right, right.flags, parent); - } - return clone; - } - ts.cloneEntityName = cloneEntityName; - function isQualifiedName(node) { - return node.kind === 139; - } - ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { - return node.pos === -1; + return positionIsSynthesized(node.pos) + || positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function createSynthesizedNode(kind, startsOnNewLine) { - var node = ts.createNode(kind, -1, -1); - node.startsOnNewLine = startsOnNewLine; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function getOriginalNode(node) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } return node; } - ts.createSynthesizedNode = createSynthesizedNode; - function createSynthesizedNodeArray() { - var array = []; - array.pos = -1; - array.end = -1; - return array; + ts.getOriginalNode = getOriginalNode; + function isParseTreeNode(node) { + return (node.flags & 8) === 0; } - ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function getOriginalSourceFiles(sourceFiles) { + var originalSourceFiles = []; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + var originalSourceFile = getParseTreeNode(sourceFile, isSourceFile); + if (originalSourceFile) { + originalSourceFiles.push(originalSourceFile); + } + } + return originalSourceFiles; + } + ts.getOriginalSourceFiles = getOriginalSourceFiles; + function getOriginalNodeId(node) { + node = getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 175: + return hasArguments ? 0 : 1; + case 185: + case 182: + case 183: + case 181: + case 184: + case 188: + case 190: + return 1; + case 187: + switch (operator) { + case 38: + case 56: + case 57: + case 58: + case 60: + case 59: + case 61: + case 62: + case 63: + case 64: + case 65: + case 66: + case 68: + case 67: + return 1; + } + } + return 0; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 187) { + return expression.operatorToken.kind; + } + else if (expression.kind === 185 || expression.kind === 186) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 97: + case 95: + case 69: + case 93: + case 99: + case 84: + case 8: + case 9: + case 170: + case 171: + case 179: + case 180: + case 192: + case 241: + case 242: + case 10: + case 11: + case 189: + case 178: + case 193: + return 19; + case 176: + case 172: + case 173: + return 18; + case 175: + return hasArguments ? 18 : 17; + case 174: + return 17; + case 186: + return 16; + case 185: + case 182: + case 183: + case 181: + case 184: + return 15; + case 187: + switch (operatorKind) { + case 49: + case 50: + return 15; + case 38: + case 37: + case 39: + case 40: + return 14; + case 35: + case 36: + return 13; + case 43: + case 44: + case 45: + return 12; + case 25: + case 28: + case 27: + case 29: + case 90: + case 91: + return 11; + case 30: + case 32: + case 31: + case 33: + return 10; + case 46: + return 9; + case 48: + return 8; + case 47: + return 7; + case 51: + return 6; + case 52: + return 5; + case 56: + case 57: + case 58: + case 60: + case 59: + case 61: + case 62: + case 63: + case 64: + case 65: + case 66: + case 68: + case 67: + return 3; + case 24: + return 0; + default: + return -1; + } + case 188: + return 4; + case 190: + return 2; + case 191: + return 1; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6457,9 +7314,7 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); - } + ts.forEach(fileDiagnostics[key], pushDiagnostic); } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -6470,15 +7325,13 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); - } + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } } } ts.createDiagnosticCollection = createDiagnosticCollection; var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { + var escapedCharsMap = ts.createMap({ "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -6491,7 +7344,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }; + }); function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -6594,10 +7447,23 @@ var ts; getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, reset: reset }; } ts.createTextWriter = createTextWriter; + function getResolvedExternalModuleName(host, file) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; function getExternalModuleNameFromPath(host, fileName) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); @@ -6639,6 +7505,69 @@ var ts; getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; } ts.getEmitModuleKind = getEmitModuleKind; + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + var moduleKind = getEmitModuleKind(options); + var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var sourceFiles = host.getSourceFiles(); + return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, isNonDeclarationFile); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function isNonDeclarationFile(sourceFile) { + return !isDeclarationFile(sourceFile); + } + function isBundleEmitNonExternalModule(sourceFile) { + return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + function forEachTransformedEmitFile(host, sourceFiles, action) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + onBundledEmit(host, sourceFiles); + } + else { + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var extension = ".js"; + if (options.jsx === 1) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); + } + function onBundledEmit(host, sourceFiles) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, true); + } + } + } + ts.forEachTransformedEmitFile = forEachTransformedEmitFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -6646,8 +7575,8 @@ var ts; } else { var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { onSingleFileEmit(host, sourceFile); } @@ -6688,9 +7617,6 @@ var ts; action(emitFileNames, bundledSources, true); } } - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } } ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { @@ -6752,7 +7678,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 149 || member.kind === 150) - && (member.flags & 32) === (accessor.flags & 32)) { + && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -6781,30 +7707,47 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { - if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } - ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { - var emitLeadingSpace = !trailingSeparator; - ts.forEach(comments, function (comment) { - if (emitLeadingSpace) { - writer.write(" "); - emitLeadingSpace = false; - } - writeComment(text, lineMap, writer, comment, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - else if (trailingSeparator) { + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { writer.write(" "); } - else { - emitLeadingSpace = true; + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.write(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } } - }); + if (emitInterveningSeparator && trailingSeparator) { + writer.write(" "); + } + } } ts.emitComments = emitComments; function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { @@ -6838,7 +7781,7 @@ var ts; var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments(text, lineMap, writer, detachedComments, true, newLine, writeComment); + emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } @@ -6850,18 +7793,18 @@ var ts; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(text, lineMap, writer, comment, newLine) { - if (text.charCodeAt(comment.pos + 1) === 42) { - var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); var lineCount = lineMap.length; var firstCommentLineIndent = void 0; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount ? text.length + 1 : lineMap[currentLine + 1]; - if (pos !== comment.pos) { + if (pos !== commentPos) { if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); } var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); @@ -6878,21 +7821,21 @@ var ts; writer.rawWrite(""); } } - writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { - writer.write(text.substring(comment.pos, comment.end)); + writer.write(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; - function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { writer.write(currentLineText); - if (end !== comment.end) { + if (end !== commentEnd) { writer.writeLine(); } } @@ -6912,6 +7855,32 @@ var ts; } return currentLineIndent; } + function hasModifiers(node) { + return getModifierFlags(node) !== 0; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return (getModifierFlags(node) & flags) !== 0; + } + ts.hasModifier = hasModifier; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912) { + return node.modifierFlagsCache & ~536870912; + } + var flags = 0; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4) { + flags |= 1; + } + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { case 113: return 32; @@ -6929,49 +7898,35 @@ var ts; return 0; } ts.modifierToFlag = modifierToFlag; - function isLeftHandSideExpression(expr) { - if (expr) { - switch (expr.kind) { - case 172: - case 173: - case 175: - case 174: - case 196: - case 241: - case 242: - case 176: - case 170: - case 178: - case 171: - case 192: - case 179: - case 69: - case 10: - case 8: - case 9: - case 11: - case 189: - case 84: - case 93: - case 97: - case 99: - case 95: - return true; - } - } - return false; + function isLogicalOperator(token) { + return token === 52 + || token === 51 + || token === 49; } - ts.isLeftHandSideExpression = isLeftHandSideExpression; + ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { return token >= 56 && token <= 68; } ts.isAssignmentOperator = isAssignmentOperator; - function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 194 && + function tryGetClassExtendingExpressionWithTypeArguments(node) { + if (node.kind === 194 && node.parent.token === 83 && - isClassLike(node.parent.parent); + isClassLike(node.parent.parent)) { + return node.parent.parent; + } } - ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isDestructuringAssignment(node) { + if (isBinaryExpression(node)) { + if (node.operatorToken.kind === 56) { + var kind = node.left.kind; + return kind === 171 + || kind === 170; + } + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; function isSupportedExpressionWithTypeArguments(node) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } @@ -6987,6 +7942,15 @@ var ts; return false; } } + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 69 || + node.kind === 172 && isEntityNameExpression(node.expression); + } + ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 && node.parent.right === node) || (node.parent.kind === 172 && node.parent.name === node); @@ -7004,7 +7968,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { @@ -7015,6 +7979,10 @@ var ts; return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function tryExtractTypeScriptExtension(fileName) { + return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -7071,7 +8039,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -7122,6 +8090,738 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; + function isSimpleExpression(node) { + return isSimpleExpressionWorker(node, 0); + } + ts.isSimpleExpression = isSimpleExpression; + function isSimpleExpressionWorker(node, depth) { + if (depth <= 5) { + var kind = node.kind; + if (kind === 9 + || kind === 8 + || kind === 10 + || kind === 11 + || kind === 69 + || kind === 97 + || kind === 95 + || kind === 99 + || kind === 84 + || kind === 93) { + return true; + } + else if (kind === 172) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 173) { + return isSimpleExpressionWorker(node.expression, depth + 1) + && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + } + else if (kind === 185 + || kind === 186) { + return isSimpleExpressionWorker(node.operand, depth + 1); + } + else if (kind === 187) { + return node.operatorToken.kind !== 38 + && isSimpleExpressionWorker(node.left, depth + 1) + && isSimpleExpressionWorker(node.right, depth + 1); + } + else if (kind === 188) { + return isSimpleExpressionWorker(node.condition, depth + 1) + && isSimpleExpressionWorker(node.whenTrue, depth + 1) + && isSimpleExpressionWorker(node.whenFalse, depth + 1); + } + else if (kind === 183 + || kind === 182 + || kind === 181) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 170) { + return node.elements.length === 0; + } + else if (kind === 171) { + return node.properties.length === 0; + } + else if (kind === 174) { + if (!isSimpleExpressionWorker(node.expression, depth + 1)) { + return false; + } + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (!isSimpleExpressionWorker(argument, depth + 1)) { + return false; + } + } + return true; + } + } + return false; + } + var syntaxKindCache = ts.createMap(); + function formatSyntaxKind(kind) { + var syntaxKindEnum = ts.SyntaxKind; + if (syntaxKindEnum) { + if (syntaxKindCache[kind]) { + return syntaxKindCache[kind]; + } + for (var name_9 in syntaxKindEnum) { + if (syntaxKindEnum[name_9] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")"; + } + } + } + else { + return kind.toString(); + } + } + ts.formatSyntaxKind = formatSyntaxKind; + function movePos(pos, value) { + return positionIsSynthesized(pos) ? -1 : pos + value; + } + ts.movePos = movePos; + function createRange(pos, end) { + return { pos: pos, end: end }; + } + ts.createRange = createRange; + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + function collapseRangeToStart(range) { + return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); + } + ts.collapseRangeToStart = collapseRangeToStart; + function collapseRangeToEnd(range) { + return isCollapsedRange(range) ? range : moveRangePos(range, range.end); + } + ts.collapseRangeToEnd = collapseRangeToEnd; + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function collectExternalModuleInfo(sourceFile, resolver) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 230: + if (!node.importClause || + resolver.isReferencedAliasDeclaration(node.importClause, true)) { + externalImports.push(node); + } + break; + case 229: + if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { + externalImports.push(node); + } + break; + case 236: + if (node.moduleSpecifier) { + if (!node.exportClause) { + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + } + else if (resolver.isValueAliasDeclaration(node)) { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + var name_10 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); + } + } + break; + case 235: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isMergedWithClass(node) { + if (node.symbol) { + for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 221 && declaration !== node) { + return true; + } + } + } + return false; + } + ts.isMergedWithClass = isMergedWithClass; + function isFirstDeclarationOfKind(node, kind) { + return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; + } + ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 11; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 11; + } + ts.isLiteralKind = isLiteralKind; + function isTextualLiteralKind(kind) { + return kind === 9 || kind === 11; + } + ts.isTextualLiteralKind = isTextualLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 11 <= kind && kind <= 14; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralFragmentKind(kind) { + return kind === 12 + || kind === 13 + || kind === 14; + } + function isTemplateLiteralFragment(node) { + return isTemplateLiteralFragmentKind(node.kind); + } + ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + function isIdentifier(node) { + return node.kind === 69; + } + ts.isIdentifier = isIdentifier; + function isGeneratedIdentifier(node) { + return isIdentifier(node) && node.autoGenerateKind > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isQualifiedName(node) { + return node.kind === 139; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 140; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isEntityName(node) { + var kind = node.kind; + return kind === 139 + || kind === 69; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 69 + || kind === 9 + || kind === 8 + || kind === 140; + } + ts.isPropertyName = isPropertyName; + function isModuleName(node) { + var kind = node.kind; + return kind === 69 + || kind === 9; + } + ts.isModuleName = isModuleName; + function isBindingName(node) { + var kind = node.kind; + return kind === 69 + || kind === 167 + || kind === 168; + } + ts.isBindingName = isBindingName; + function isTypeParameter(node) { + return node.kind === 141; + } + ts.isTypeParameter = isTypeParameter; + function isParameter(node) { + return node.kind === 142; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 143; + } + ts.isDecorator = isDecorator; + function isMethodDeclaration(node) { + return node.kind === 147; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isClassElement(node) { + var kind = node.kind; + return kind === 148 + || kind === 145 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 153 + || kind === 198; + } + ts.isClassElement = isClassElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 253 + || kind === 254 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 239; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNodeKind(kind) { + return (kind >= 154 && kind <= 166) + || kind === 117 + || kind === 130 + || kind === 120 + || kind === 132 + || kind === 133 + || kind === 103 + || kind === 127 + || kind === 194; + } + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 168 + || kind === 167; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isBindingElement(node) { + return node.kind === 169; + } + ts.isBindingElement = isBindingElement; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 169 + || kind === 193; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isPropertyAccessExpression(node) { + return node.kind === 172; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 173; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isBinaryExpression(node) { + return node.kind === 187; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 188; + } + ts.isConditionalExpression = isConditionalExpression; + function isCallExpression(node) { + return node.kind === 174; + } + ts.isCallExpression = isCallExpression; + function isTemplate(node) { + var kind = node.kind; + return kind === 189 + || kind === 11; + } + ts.isTemplate = isTemplate; + function isSpreadElementExpression(node) { + return node.kind === 191; + } + ts.isSpreadElementExpression = isSpreadElementExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 194; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isLeftHandSideExpressionKind(kind) { + return kind === 172 + || kind === 173 + || kind === 175 + || kind === 174 + || kind === 241 + || kind === 242 + || kind === 176 + || kind === 170 + || kind === 178 + || kind === 171 + || kind === 192 + || kind === 179 + || kind === 69 + || kind === 10 + || kind === 8 + || kind === 9 + || kind === 11 + || kind === 189 + || kind === 84 + || kind === 93 + || kind === 97 + || kind === 99 + || kind === 95 + || kind === 196; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 185 + || kind === 186 + || kind === 181 + || kind === 182 + || kind === 183 + || kind === 184 + || kind === 177 + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 188 + || kind === 190 + || kind === 180 + || kind === 187 + || kind === 191 + || kind === 195 + || kind === 193 + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 177 + || kind === 195; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isOmittedExpression(node) { + return node.kind === 193; + } + ts.isOmittedExpression = isOmittedExpression; + function isTemplateSpan(node) { + return node.kind === 197; + } + ts.isTemplateSpan = isTemplateSpan; + function isBlock(node) { + return node.kind === 199; + } + ts.isBlock = isBlock; + function isConciseBody(node) { + return isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isVariableDeclaration(node) { + return node.kind === 218; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 219; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isCaseBlock(node) { + return node.kind === 227; + } + ts.isCaseBlock = isCaseBlock; + function isModuleBody(node) { + var kind = node.kind; + return kind === 226 + || kind === 225; + } + ts.isModuleBody = isModuleBody; + function isImportEqualsDeclaration(node) { + return node.kind === 229; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportClause(node) { + return node.kind === 231; + } + ts.isImportClause = isImportClause; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 233 + || kind === 232; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isImportSpecifier(node) { + return node.kind === 234; + } + ts.isImportSpecifier = isImportSpecifier; + function isNamedExports(node) { + return node.kind === 237; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 238; + } + ts.isExportSpecifier = isExportSpecifier; + function isModuleOrEnumDeclaration(node) { + return node.kind === 225 || node.kind === 224; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 180 + || kind === 169 + || kind === 221 + || kind === 192 + || kind === 148 + || kind === 224 + || kind === 255 + || kind === 238 + || kind === 220 + || kind === 179 + || kind === 149 + || kind === 231 + || kind === 229 + || kind === 234 + || kind === 222 + || kind === 147 + || kind === 146 + || kind === 225 + || kind === 228 + || kind === 232 + || kind === 142 + || kind === 253 + || kind === 145 + || kind === 144 + || kind === 150 + || kind === 254 + || kind === 223 + || kind === 141 + || kind === 218 + || kind === 279; + } + function isDeclarationStatementKind(kind) { + return kind === 220 + || kind === 239 + || kind === 221 + || kind === 222 + || kind === 223 + || kind === 224 + || kind === 225 + || kind === 230 + || kind === 229 + || kind === 236 + || kind === 235 + || kind === 228; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 210 + || kind === 209 + || kind === 217 + || kind === 204 + || kind === 202 + || kind === 201 + || kind === 207 + || kind === 208 + || kind === 206 + || kind === 203 + || kind === 214 + || kind === 211 + || kind === 213 + || kind === 215 + || kind === 216 + || kind === 200 + || kind === 205 + || kind === 212 + || kind === 287; + } + function isDeclaration(node) { + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 199; + } + ts.isStatement = isStatement; + function isModuleReference(node) { + var kind = node.kind; + return kind === 240 + || kind === 139 + || kind === 69; + } + ts.isModuleReference = isModuleReference; + function isJsxOpeningElement(node) { + return node.kind === 243; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 245; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 97 + || kind === 69 + || kind === 172; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 241 + || kind === 248 + || kind === 242 + || kind === 244; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 246 + || kind === 247; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isJsxSpreadAttribute(node) { + return node.kind === 247; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxAttribute(node) { + return node.kind === 246; + } + ts.isJsxAttribute = isJsxAttribute; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 + || kind === 248; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 249 + || kind === 250; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isHeritageClause(node) { + return node.kind === 251; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 252; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 253; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 254; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isEnumMember(node) { + return node.kind === 255; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 256; + } + ts.isSourceFile = isSourceFile; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } @@ -7259,28 +8959,2230 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 169 || ts.isBindingPattern(node))) { + node = node.parent; + } + return node; } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return str.indexOf(suffix, expectedPos) === expectedPos; + function getCombinedModifierFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = ts.getModifierFlags(node); + if (node.kind === 218) { + node = node.parent; + } + if (node && node.kind === 219) { + flags |= ts.getModifierFlags(node); + node = node.parent; + } + if (node && node.kind === 200) { + flags |= ts.getModifierFlags(node); + } + return flags; } - ts.endsWith = endsWith; + ts.getCombinedModifierFlags = getCombinedModifierFlags; + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 218) { + node = node.parent; + } + if (node && node.kind === 219) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 200) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; })(ts || (ts = {})); var ts; (function (ts) { - ts.parseTime = 0; var NodeConstructor; var SourceFileConstructor; + function createNode(kind, location, flags) { + var ConstructorForKind = kind === 256 + ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) + : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); + var node = location + ? new ConstructorForKind(kind, location.pos, location.end) + : new ConstructorForKind(kind, -1, -1); + node.flags = flags | 8; + return node; + } + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + if (original.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + function createNodeArray(elements, location, hasTrailingComma) { + if (elements) { + if (ts.isNodeArray(elements)) { + return elements; + } + } + else { + elements = []; + } + var array = elements; + if (location) { + array.pos = location.pos; + array.end = location.end; + } + else { + array.pos = -1; + array.end = -1; + } + if (hasTrailingComma) { + array.hasTrailingComma = true; + } + return array; + } + ts.createNodeArray = createNodeArray; + function createSynthesizedNode(kind, startsOnNewLine) { + var node = createNode(kind, undefined); + node.startsOnNewLine = startsOnNewLine; + return node; + } + ts.createSynthesizedNode = createSynthesizedNode; + function createSynthesizedNodeArray(elements) { + return createNodeArray(elements, undefined); + } + ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + function getSynthesizedClone(node) { + var clone = createNode(node.kind, undefined, node.flags); + clone.original = node; + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + function createLiteral(value, location) { + if (typeof value === "number") { + var node = createNode(8, location, undefined); + node.text = value.toString(); + return node; + } + else if (typeof value === "boolean") { + return createNode(value ? 99 : 84, location, undefined); + } + else if (typeof value === "string") { + var node = createNode(9, location, undefined); + node.text = value; + return node; + } + else { + var node = createNode(9, location, undefined); + node.textSourceNode = value; + node.text = value.text; + return node; + } + } + ts.createLiteral = createLiteral; + var nextAutoGenerateId = 0; + function createIdentifier(text, location) { + var node = createNode(69, location); + node.text = ts.escapeIdentifier(text); + node.originalKeywordKind = ts.stringToToken(text); + node.autoGenerateKind = 0; + node.autoGenerateId = 0; + return node; + } + ts.createIdentifier = createIdentifier; + function createTempVariable(recordTempVariable, location) { + var name = createNode(69, location); + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 1; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + return name; + } + ts.createTempVariable = createTempVariable; + function createLoopVariable(location) { + var name = createNode(69, location); + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 2; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + function createUniqueName(text, location) { + var name = createNode(69, location); + name.text = text; + name.originalKeywordKind = 0; + name.autoGenerateKind = 3; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function getGeneratedNameForNode(node, location) { + var name = createNode(69, location); + name.original = node; + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 4; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + function createToken(token) { + return createNode(token); + } + ts.createToken = createToken; + function createSuper() { + var node = createNode(95); + return node; + } + ts.createSuper = createSuper; + function createThis(location) { + var node = createNode(97, location); + return node; + } + ts.createThis = createThis; + function createNull() { + var node = createNode(93); + return node; + } + ts.createNull = createNull; + function createComputedPropertyName(expression, location) { + var node = createNode(140, location); + node.expression = expression; + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + if (node.expression !== expression) { + return updateNode(createComputedPropertyName(expression, node), node); + } + return node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + function createParameter(name, initializer, location) { + return createParameterDeclaration(undefined, undefined, undefined, name, undefined, undefined, initializer, location); + } + ts.createParameter = createParameter; + function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(142, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameterDeclaration = createParameterDeclaration; + function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); + } + return node; + } + ts.updateParameterDeclaration = updateParameterDeclaration; + function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { + var node = createNode(145, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer, node), node); + } + return node; + } + ts.updateProperty = updateProperty; + function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(147, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createMethod(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body, location, flags) { + var node = createNode(148, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body) { + return updateNode(createConstructor(decorators, modifiers, parameters, body, node, node.flags), node); + } + return node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { + var node = createNode(149, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { + var node = createNode(150, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body) { + return updateNode(createSetAccessor(decorators, modifiers, name, parameters, body, node, node.flags), node); + } + return node; + } + ts.updateSetAccessor = updateSetAccessor; + function createObjectBindingPattern(elements, location) { + var node = createNode(167, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createObjectBindingPattern(elements, node), node); + } + return node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements, location) { + var node = createNode(168, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayBindingPattern(elements, node), node); + } + return node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { + var node = createNode(169, location); + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + } + return node; + } + ts.updateBindingElement = updateBindingElement; + function createArrayLiteral(elements, location, multiLine) { + var node = createNode(170, location); + node.elements = parenthesizeListElements(createNodeArray(elements)); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayLiteral(elements, node, node.multiLine), node); + } + return node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, location, multiLine) { + var node = createNode(171, location); + node.properties = createNodeArray(properties); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + if (node.properties !== properties) { + return updateNode(createObjectLiteral(properties, node, node.multiLine), node); + } + return node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name, location, flags) { + var node = createNode(172, location, flags); + node.expression = parenthesizeForAccess(expression); + node.emitFlags = 1048576; + node.name = typeof name === "string" ? createIdentifier(name) : name; + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + if (node.expression !== expression || node.name !== name) { + var propertyAccess = createPropertyAccess(expression, name, node, node.flags); + propertyAccess.emitFlags = node.emitFlags; + return updateNode(propertyAccess, node); + } + return node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index, location) { + var node = createNode(173, location); + node.expression = parenthesizeForAccess(expression); + node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + if (node.expression !== expression || node.argumentExpression !== argumentExpression) { + return updateNode(createElementAccess(expression, argumentExpression, node), node); + } + return node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(174, location, flags); + node.expression = parenthesizeForAccess(expression); + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + node.arguments = parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + if (expression !== node.expression || typeArguments !== node.typeArguments || argumentsArray !== node.arguments) { + return updateNode(createCall(expression, typeArguments, argumentsArray, node, node.flags), node); + } + return node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(175, location, flags); + node.expression = parenthesizeForNew(expression); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + if (node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray) { + return updateNode(createNew(expression, typeArguments, argumentsArray, node, node.flags), node); + } + return node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, template, location) { + var node = createNode(176, location); + node.tag = parenthesizeForAccess(tag); + node.template = template; + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, template) { + if (node.tag !== tag || node.template !== template) { + return updateNode(createTaggedTemplate(tag, template, node), node); + } + return node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createParen(expression, location) { + var node = createNode(178, location); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + if (node.expression !== expression) { + return updateNode(createParen(expression, node), node); + } + return node; + } + ts.updateParen = updateParen; + function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(179, location, flags); + node.modifiers = undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { + var node = createNode(180, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.body = parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + if (node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body, node, node.flags), node); + } + return node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression, location) { + var node = createNode(181, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + if (node.expression !== expression) { + return updateNode(createDelete(expression, node), expression); + } + return node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression, location) { + var node = createNode(182, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + if (node.expression !== expression) { + return updateNode(createTypeOf(expression, node), expression); + } + return node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression, location) { + var node = createNode(183, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + if (node.expression !== expression) { + return updateNode(createVoid(expression, node), node); + } + return node; + } + ts.updateVoid = updateVoid; + function createAwait(expression, location) { + var node = createNode(184, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + if (node.expression !== expression) { + return updateNode(createAwait(expression, node), node); + } + return node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand, location) { + var node = createNode(185, location); + node.operator = operator; + node.operand = parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPrefix(node.operator, operand, node), node); + } + return node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator, location) { + var node = createNode(186, location); + node.operand = parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPostfix(operand, node.operator, node), node); + } + return node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right, location) { + var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorKind = operatorToken.kind; + var node = createNode(187, location); + node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); + node.operatorToken = operatorToken; + node.right = parenthesizeBinaryOperand(operatorKind, right, false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right) { + if (node.left !== left || node.right !== right) { + return updateNode(createBinary(left, node.operatorToken, right, node), node); + } + return node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { + var node = createNode(188, location); + node.condition = condition; + node.questionToken = questionToken; + node.whenTrue = whenTrue; + node.colonToken = colonToken; + node.whenFalse = whenFalse; + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, whenTrue, whenFalse) { + if (node.condition !== condition || node.whenTrue !== whenTrue || node.whenFalse !== whenFalse) { + return updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse, node), node); + } + return node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans, location) { + var node = createNode(189, location); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + if (node.head !== head || node.templateSpans !== templateSpans) { + return updateNode(createTemplateExpression(head, templateSpans, node), node); + } + return node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createYield(asteriskToken, expression, location) { + var node = createNode(190, location); + node.asteriskToken = asteriskToken; + node.expression = expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, expression) { + if (node.expression !== expression) { + return updateNode(createYield(node.asteriskToken, expression, node), node); + } + return node; + } + ts.updateYield = updateYield; + function createSpread(expression, location) { + var node = createNode(191, location); + node.expression = parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpread(expression, node), node); + } + return node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(192, location); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + if (node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression(location) { + var node = createNode(193, location); + return node; + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression, location) { + var node = createNode(194, location); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.expression = parenthesizeForAccess(expression); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + if (node.typeArguments !== typeArguments || node.expression !== expression) { + return updateNode(createExpressionWithTypeArguments(typeArguments, expression, node), node); + } + return node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createTemplateSpan(expression, literal, location) { + var node = createNode(197, location); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + if (node.expression !== expression || node.literal !== literal) { + return updateNode(createTemplateSpan(expression, literal, node), node); + } + return node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createBlock(statements, location, multiLine, flags) { + var block = createNode(199, location, flags); + block.statements = createNodeArray(statements); + if (multiLine) { + block.multiLine = true; + } + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + if (statements !== node.statements) { + return updateNode(createBlock(statements, node, node.multiLine, node.flags), node); + } + return node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList, location, flags) { + var node = createNode(200, location, flags); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + if (node.modifiers !== modifiers || node.declarationList !== declarationList) { + return updateNode(createVariableStatement(modifiers, declarationList, node, node.flags), node); + } + return node; + } + ts.updateVariableStatement = updateVariableStatement; + function createVariableDeclarationList(declarations, location, flags) { + var node = createNode(219, location, flags); + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + if (node.declarations !== declarations) { + return updateNode(createVariableDeclarationList(declarations, node, node.flags), node); + } + return node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createVariableDeclaration(name, type, initializer, location, flags) { + var node = createNode(218, location, flags); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.type = type; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + if (node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createVariableDeclaration(name, type, initializer, node, node.flags), node); + } + return node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createEmptyStatement(location) { + return createNode(201, location); + } + ts.createEmptyStatement = createEmptyStatement; + function createStatement(expression, location, flags) { + var node = createNode(202, location, flags); + node.expression = parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createStatement = createStatement; + function updateStatement(node, expression) { + if (node.expression !== expression) { + return updateNode(createStatement(expression, node, node.flags), node); + } + return node; + } + ts.updateStatement = updateStatement; + function createIf(expression, thenStatement, elseStatement, location) { + var node = createNode(203, location); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + if (node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement) { + return updateNode(createIf(expression, thenStatement, elseStatement, node), node); + } + return node; + } + ts.updateIf = updateIf; + function createDo(statement, expression, location) { + var node = createNode(204, location); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + if (node.statement !== statement || node.expression !== expression) { + return updateNode(createDo(statement, expression, node), node); + } + return node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement, location) { + var node = createNode(205, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWhile(expression, statement, node), node); + } + return node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement, location) { + var node = createNode(206, location, undefined); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + if (node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement) { + return updateNode(createFor(initializer, condition, incrementor, statement, node), node); + } + return node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement, location) { + var node = createNode(207, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForIn(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForIn = updateForIn; + function createForOf(initializer, expression, statement, location) { + var node = createNode(208, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForOf(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForOf = updateForOf; + function createContinue(label, location) { + var node = createNode(209, location); + if (label) { + node.label = label; + } + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + if (node.label !== label) { + return updateNode(createContinue(label, node), node); + } + return node; + } + ts.updateContinue = updateContinue; + function createBreak(label, location) { + var node = createNode(210, location); + if (label) { + node.label = label; + } + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + if (node.label !== label) { + return updateNode(createBreak(label, node), node); + } + return node; + } + ts.updateBreak = updateBreak; + function createReturn(expression, location) { + var node = createNode(211, location); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + if (node.expression !== expression) { + return updateNode(createReturn(expression, node), node); + } + return node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement, location) { + var node = createNode(212, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWith(expression, statement, node), node); + } + return node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock, location) { + var node = createNode(213, location); + node.expression = parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + if (node.expression !== expression || node.caseBlock !== caseBlock) { + return updateNode(createSwitch(expression, caseBlock, node), node); + } + return node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement, location) { + var node = createNode(214, location); + node.label = typeof label === "string" ? createIdentifier(label) : label; + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + if (node.label !== label || node.statement !== statement) { + return updateNode(createLabel(label, statement, node), node); + } + return node; + } + ts.updateLabel = updateLabel; + function createThrow(expression, location) { + var node = createNode(215, location); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + if (node.expression !== expression) { + return updateNode(createThrow(expression, node), node); + } + return node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock, location) { + var node = createNode(216, location); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + if (node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock) { + return updateNode(createTry(tryBlock, catchClause, finallyBlock, node), node); + } + return node; + } + ts.updateTry = updateTry; + function createCaseBlock(clauses, location) { + var node = createNode(227, location); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + if (node.clauses !== clauses) { + return updateNode(createCaseBlock(clauses, node), node); + } + return node; + } + ts.updateCaseBlock = updateCaseBlock; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(220, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionDeclaration(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(221, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { + var node = createNode(230, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings, location) { + var node = createNode(231, location); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + if (node.name !== name || node.namedBindings !== namedBindings) { + return updateNode(createImportClause(name, namedBindings, node), node); + } + return node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name, location) { + var node = createNode(232, location); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + if (node.name !== name) { + return updateNode(createNamespaceImport(name, node), node); + } + return node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements, location) { + var node = createNode(233, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedImports(elements, node), node); + } + return node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name, location) { + var node = createNode(234, location); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + if (node.propertyName !== propertyName || node.name !== name) { + return updateNode(createImportSpecifier(propertyName, name, node), node); + } + return node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { + var node = createNode(235, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.isExportEquals = isExportEquals; + node.expression = expression; + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.expression !== expression) { + return updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression, node), node); + } + return node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { + var node = createNode(236, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements, location) { + var node = createNode(237, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedExports(elements, node), node); + } + return node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(name, propertyName, location) { + var node = createNode(238, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, name, propertyName) { + if (node.name !== name || node.propertyName !== propertyName) { + return updateNode(createExportSpecifier(name, propertyName, node), node); + } + return node; + } + ts.updateExportSpecifier = updateExportSpecifier; + function createJsxElement(openingElement, children, closingElement, location) { + var node = createNode(241, location); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + if (node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement) { + return updateNode(createJsxElement(openingElement, children, closingElement, node), node); + } + return node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, attributes, location) { + var node = createNode(242, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxSelfClosingElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, attributes, location) { + var node = createNode(243, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxOpeningElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName, location) { + var node = createNode(245, location); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + if (node.tagName !== tagName) { + return updateNode(createJsxClosingElement(tagName, node), node); + } + return node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxAttribute(name, initializer, location) { + var node = createNode(246, location); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createJsxAttribute(name, initializer, node), node); + } + return node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxSpreadAttribute(expression, location) { + var node = createNode(247, location); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxSpreadAttribute(expression, node), node); + } + return node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(expression, location) { + var node = createNode(248, location); + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxExpression(expression, node), node); + } + return node; + } + ts.updateJsxExpression = updateJsxExpression; + function createHeritageClause(token, types, location) { + var node = createNode(251, location); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + if (node.types !== types) { + return updateNode(createHeritageClause(node.token, types, node), node); + } + return node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCaseClause(expression, statements, location) { + var node = createNode(249, location); + node.expression = parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + if (node.expression !== expression || node.statements !== statements) { + return updateNode(createCaseClause(expression, statements, node), node); + } + return node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements, location) { + var node = createNode(250, location); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + if (node.statements !== statements) { + return updateNode(createDefaultClause(statements, node), node); + } + return node; + } + ts.updateDefaultClause = updateDefaultClause; + function createCatchClause(variableDeclaration, block, location) { + var node = createNode(252, location); + node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + if (node.variableDeclaration !== variableDeclaration || node.block !== block) { + return updateNode(createCatchClause(variableDeclaration, block, node), node); + } + return node; + } + ts.updateCatchClause = updateCatchClause; + function createPropertyAssignment(name, initializer, location) { + var node = createNode(253, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = undefined; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createPropertyAssignment(name, initializer, node), node); + } + return node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { + var node = createNode(254, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { + return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); + } + return node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSourceFileNode(node, statements) { + if (node.statements !== statements) { + var updated = createNode(256, node, node.flags); + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.referencedFiles !== undefined) + updated.referencedFiles = node.referencedFiles; + if (node.typeReferenceDirectives !== undefined) + updated.typeReferenceDirectives = node.typeReferenceDirectives; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.isDeclarationFile !== undefined) + updated.isDeclarationFile = node.isDeclarationFile; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.hasNoDefaultLib !== undefined) + updated.hasNoDefaultLib = node.hasNoDefaultLib; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.externalHelpersModuleName !== undefined) + updated.externalHelpersModuleName = node.externalHelpersModuleName; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + function createNotEmittedStatement(original) { + var node = createNode(287, original); + node.original = original; + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + function createPartiallyEmittedExpression(expression, original, location) { + var node = createNode(288, location || original); + node.expression = expression; + node.original = original; + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original, node), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function createComma(left, right) { + return createBinary(left, 24, right); + } + ts.createComma = createComma; + function createLessThan(left, right, location) { + return createBinary(left, 25, right, location); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right, location) { + return createBinary(left, 56, right, location); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 32, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 33, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 35, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 36, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand, location) { + return createPostfix(operand, 41, location); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 51, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 52, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(49, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return createElementAccess(target, memberName.expression, location); + } + else { + var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); + expression.emitFlags |= 2048; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createRestParameter(name) { + return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + } + ts.createRestParameter = createRestParameter; + function createFunctionCall(func, thisArg, argumentsList, location) { + return createCall(createPropertyAccess(func, "call"), undefined, [ + thisArg + ].concat(argumentsList), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return createCall(createPropertyAccess(func, "apply"), undefined, [ + thisArg, + argumentsExpression + ], location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? createLiteral(start) : start); + } + return createCall(createPropertyAccess(array, "slice"), undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return createCall(createPropertyAccess(array, "concat"), undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return createCall(createPropertyAccess(createIdentifier("Math"), "pow"), undefined, [left, right], location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + var react = createIdentifier(reactNamespace || "React"); + react.flags &= ~8; + react.parent = parent; + return react; + } + function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + child.startsOnNewLine = true; + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), undefined, argumentsList, location); + } + ts.createReactCreateElement = createReactCreateElement; + function createLetDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 1); + } + ts.createLetDeclarationList = createLetDeclarationList; + function createConstDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 2); + } + ts.createConstDeclarationList = createConstDeclarationList; + function createHelperName(externalHelpersModuleName, name) { + return externalHelpersModuleName + ? createPropertyAccess(externalHelpersModuleName, name) + : createIdentifier(name); + } + ts.createHelperName = createHelperName; + function createExtendsHelper(externalHelpersModuleName, name) { + return createCall(createHelperName(externalHelpersModuleName, "__extends"), undefined, [ + name, + createIdentifier("_super") + ]); + } + ts.createExtendsHelper = createExtendsHelper; + function createAssignHelper(externalHelpersModuleName, attributesSegments) { + return createCall(createHelperName(externalHelpersModuleName, "__assign"), undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { + return createCall(createHelperName(externalHelpersModuleName, "__param"), undefined, [ + createLiteral(parameterOffset), + expression + ], location); + } + ts.createParamHelper = createParamHelper; + function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { + return createCall(createHelperName(externalHelpersModuleName, "__metadata"), undefined, [ + createLiteral(metadataKey), + metadataValue + ]); + } + ts.createMetadataHelper = createMetadataHelper; + function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(createArrayLiteral(decoratorExpressions, undefined, true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return createCall(createHelperName(externalHelpersModuleName, "__decorate"), undefined, argumentsArray, location); + } + ts.createDecorateHelper = createDecorateHelper; + function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { + var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); + generatorFunc.emitFlags |= 2097152; + return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ + createThis(), + hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), + promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), + generatorFunc + ]); + } + ts.createAwaiterHelper = createAwaiterHelper; + function createHasOwnProperty(target, propertyName) { + return createCall(createPropertyAccess(target, "hasOwnProperty"), undefined, [propertyName]); + } + ts.createHasOwnProperty = createHasOwnProperty; + function createObjectCreate(prototype) { + return createCall(createPropertyAccess(createIdentifier("Object"), "create"), undefined, [prototype]); + } + function createGeti(target) { + return createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createElementAccess(target, createIdentifier("name"))); + } + function createSeti(target) { + return createArrowFunction(undefined, undefined, [ + createParameter("name"), + createParameter("value") + ], undefined, undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); + } + function createAdvancedAsyncSuperHelper() { + var createCache = createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("cache", undefined, createObjectCreate(createNull())) + ])); + var getter = createGetAccessor(undefined, undefined, "value", [], undefined, createBlock([ + createReturn(createCall(createIdentifier("geti"), undefined, [createIdentifier("name")])) + ])); + var setter = createSetAccessor(undefined, undefined, "value", [createParameter("v")], createBlock([ + createStatement(createCall(createIdentifier("seti"), undefined, [ + createIdentifier("name"), + createIdentifier("v") + ])) + ])); + var getOrCreateAccessorsForName = createReturn(createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ + getter, + setter + ])))))); + return createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("_super", undefined, createCall(createParen(createFunctionExpression(undefined, undefined, undefined, [ + createParameter("geti"), + createParameter("seti") + ], undefined, createBlock([ + createCache, + getOrCreateAccessorsForName + ]))), undefined, [ + createGeti(createSuper()), + createSeti(createSuper()) + ])) + ])); + } + ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; + function createSimpleAsyncSuperHelper() { + return createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("_super", undefined, createGeti(createSuper())) + ])); + } + ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = skipParentheses(node); + switch (target.kind) { + case 69: + return cacheIdentifiers; + case 97: + case 8: + case 9: + return false; + case 170: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 171: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + var callee = skipOuterExpressions(expression, 7); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = createThis(); + target = callee; + } + else if (callee.kind === 95) { + thisArg = createThis(); + target = languageVersion < 2 ? createIdentifier("_super", callee) : callee; + } + else { + switch (callee.kind) { + case 172: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createPropertyAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.name, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 173: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createElementAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.argumentExpression, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + thisArg = createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + return ts.reduceLeft(expressions, createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = getMutableClone(node.right); + return createPropertyAccess(left, right, node); + } + else { + return getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return createLiteral(memberName, undefined); + } + else if (ts.isComputedPropertyName(memberName)) { + return getMutableClone(memberName.expression); + } + else { + return getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 149: + case 150: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + case 253: + return createExpressionForPropertyAssignment(property, receiver); + case 254: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 147: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_1 = []; + if (getAccessor) { + var getterFunction = createFunctionExpression(undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); + setOriginalNode(getterFunction, getAccessor); + var getter = createPropertyAssignment("get", getterFunction); + properties_1.push(getter); + } + if (setAccessor) { + var setterFunction = createFunctionExpression(undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); + setOriginalNode(setterFunction, setAccessor); + var setter = createPropertyAssignment("set", setterFunction); + properties_1.push(setter); + } + properties_1.push(createPropertyAssignment("enumerable", createLiteral(true))); + properties_1.push(createPropertyAssignment("configurable", createLiteral(true))); + var expression = createCall(createPropertyAccess(createIdentifier("Object"), "defineProperty"), undefined, [ + receiver, + createExpressionForPropertyName(property.name), + createObjectLiteral(properties_1, undefined, multiLine) + ], firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), property.initializer, property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), getSynthesizedClone(property.name), property), property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); + } + function isUseStrictPrologue(node) { + return node.expression.text === "use strict"; + } + function addPrologueDirectives(target, source, ensureUseStrict, visitor) { + ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + foundUseStrict = true; + } + if (statement.emitFlags & 8388608) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + } + statementOffset++; + } + return statementOffset; + } + ts.addPrologueDirectives = addPrologueDirectives; + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = skipPartiallyEmittedExpressions(operand); + if (skipped.kind === 178) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var binaryOperatorPrecedence = ts.getOperatorPrecedence(187, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(187, binaryOperator); + var emittedOperand = skipPartiallyEmittedExpressions(operand); + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1: + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 + && operand.kind === 190) { + return false; + } + return true; + case 1: + return false; + case 0: + if (isLeftSideOfBinary) { + return binaryOperatorAssociativity === 1; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + if (binaryOperator === 35) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0; + } + } + } + function operatorHasAssociativeProperty(binaryOperator) { + return binaryOperator === 37 + || binaryOperator === 47 + || binaryOperator === 46 + || binaryOperator === 48; + } + function getLiteralKindOfBinaryPlusOperand(node) { + node = skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 187 && node.operatorToken.kind === 35) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0; + } + function parenthesizeForNew(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + switch (emittedExpression.kind) { + case 174: + return createParen(expression); + case 175: + return emittedExpression.arguments + ? expression + : createParen(expression); + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + function parenthesizeForAccess(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 175 || emittedExpression.arguments) + && emittedExpression.kind !== 8) { + return expression; + } + return createParen(expression, expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : createParen(operand, operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : createParen(operand, operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return createNodeArray(result, elements, elements.hasTrailingComma); + } + return elements; + } + function parenthesizeExpressionForList(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(187, 24); + return expressionPrecedence > commaPrecedence + ? expression + : createParen(expression, expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = skipPartiallyEmittedExpressions(callee).kind; + if (kind === 179 || kind === 180) { + var mutableCall = getMutableClone(emittedExpression); + mutableCall.expression = createParen(callee, callee); + return recreatePartiallyEmittedExpressions(expression, mutableCall); + } + } + else { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 171 || leftmostExpressionKind === 179) { + return createParen(expression, expression); + } + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { + if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { + var clone_1 = getMutableClone(originalOuterExpression); + clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); + return clone_1; + } + return newInnerExpression; + } + function getLeftmostExpression(node) { + while (true) { + switch (node.kind) { + case 186: + node = node.operand; + continue; + case 187: + node = node.left; + continue; + case 188: + node = node.condition; + continue; + case 174: + case 173: + case 172: + node = node.expression; + continue; + case 288: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + var emittedBody = skipPartiallyEmittedExpressions(body); + if (emittedBody.kind === 171) { + return createParen(body, body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7; } + var previousNode; + do { + previousNode = node; + if (kinds & 1) { + node = skipParentheses(node); + } + if (kinds & 2) { + node = skipAssertions(node); + } + if (kinds & 4) { + node = skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipParentheses(node) { + while (node.kind === 178) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipAssertions(node) { + while (ts.isAssertionExpression(node)) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function startOnNewLine(node) { + node.startsOnNewLine = true; + return node; + } + ts.startOnNewLine = startOnNewLine; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; + if (emitFlags) + node.emitFlags = emitFlags; + if (commentRange) + node.commentRange = commentRange; + if (sourceMapRange) + node.sourceMapRange = sourceMapRange; + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function setTextRange(node, location) { + if (location) { + node.pos = location.pos; + node.end = location.end; + } + return node; + } + ts.setTextRange = setTextRange; + function setNodeFlags(node, flags) { + node.flags = flags; + return node; + } + ts.setNodeFlags = setNodeFlags; + function setMultiLine(node, multiLine) { + node.multiLine = multiLine; + return node; + } + ts.setMultiLine = setMultiLine; + function setHasTrailingComma(nodes, hasTrailingComma) { + nodes.hasTrailingComma = hasTrailingComma; + return nodes; + } + ts.setHasTrailingComma = setHasTrailingComma; + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name_11 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + } + if (node.kind === 230 && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 236 && node.moduleSpecifier) { + return getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); + if (moduleName.kind === 9) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + function tryRenameExternalModule(moduleName, sourceFile) { + if (sourceFile.renamedDependencies && ts.hasProperty(sourceFile.renamedDependencies, moduleName.text)) { + return createLiteral(sourceFile.renamedDependencies[moduleName.text]); + } + return undefined; + } + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return createLiteral(file.moduleName); + } + if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + return createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } + else if (kind === 69) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (kind < 139) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -7389,6 +11291,8 @@ var ts; return visitNodes(cbNodes, node.types); case 164: return visitNode(cbNode, node.type); + case 166: + return visitNode(cbNode, node.literal); case 167: case 168: return visitNodes(cbNodes, node.elements); @@ -7628,7 +11532,7 @@ var ts; case 263: return visitNode(cbNode, node.type); case 265: - return visitNodes(cbNodes, node.members); + return visitNode(cbNode, node.literal); case 267: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); @@ -7667,14 +11571,19 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + case 288: + return visitNode(cbNode, node.expression); + case 282: + return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - var start = new Date().getTime(); + ts.performance.mark("beforeParse"); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.parseTime += new Date().getTime() - start; + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; } ts.createSourceFile = createSourceFile; @@ -7688,8 +11597,8 @@ var ts; ts.updateSourceFile = updateSourceFile; function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDocComment) { - Parser.fixupParentReferences(result.jsDocComment); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); } return result; } @@ -7701,13 +11610,15 @@ var ts; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 4194304 | 16777216; + var disallowInAndDecoratorContext = 32768 | 131072; var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -7728,15 +11639,17 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 1048576 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -7755,10 +11668,10 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; - token = nextToken(); + nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token === 1); + ts.Debug.assert(token() === 1); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -7771,20 +11684,18 @@ var ts; return sourceFile; } function addJSDocComment(node) { - if (contextFlags & 134217728) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDocComment) { - continue; - } - if (!node.jsDocComments) { - node.jsDocComments = []; - } - node.jsDocComments.push(jsDocComment); + var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; } + if (!node.jsDocComments) { + node.jsDocComments = []; + } + node.jsDocComments.push(jsDoc); } } return node; @@ -7833,16 +11744,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 4194304); + setContextFlag(val, 32768); } function setYieldContext(val) { - setContextFlag(val, 8388608); + setContextFlag(val, 65536); } function setDecoratorContext(val) { - setContextFlag(val, 16777216); + setContextFlag(val, 131072); } function setAwaitContext(val) { - setContextFlag(val, 33554432); + setContextFlag(val, 262144); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -7865,40 +11776,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(4194304, func); + return doOutsideOfContext(32768, func); } function disallowInAnd(func) { - return doInsideOfContext(4194304, func); + return doInsideOfContext(32768, func); } function doInYieldContext(func) { - return doInsideOfContext(8388608, func); + return doInsideOfContext(65536, func); } function doInDecoratorContext(func) { - return doInsideOfContext(16777216, func); + return doInsideOfContext(131072, func); } function doInAwaitContext(func) { - return doInsideOfContext(33554432, func); + return doInsideOfContext(262144, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(33554432, func); + return doOutsideOfContext(262144, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(8388608 | 33554432, func); + return doInsideOfContext(65536 | 262144, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(8388608); + return inContext(65536); } function inDisallowInContext() { - return inContext(4194304); + return inContext(32768); } function inDecoratorContext() { - return inContext(16777216); + return inContext(131072); } function inAwaitContext() { - return inContext(33554432); + return inContext(262144); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -7922,26 +11833,32 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } + function token() { + return currentToken; + } function nextToken() { - return token = scanner.scan(); + return currentToken = scanner.scan(); } function reScanGreaterToken() { - return token = scanner.reScanGreaterToken(); + return currentToken = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return token = scanner.reScanSlashToken(); + return currentToken = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return token = scanner.reScanTemplateToken(); + return currentToken = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return token = scanner.scanJsxIdentifier(); + return currentToken = scanner.scanJsxIdentifier(); } function scanJsxText() { - return token = scanner.scanJsxToken(); + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); } function speculationHelper(callback, isLookAhead) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -7950,7 +11867,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -7963,20 +11880,20 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token === 69) { + if (token() === 69) { return true; } - if (token === 114 && inYieldContext()) { + if (token() === 114 && inYieldContext()) { return false; } - if (token === 119 && inAwaitContext()) { + if (token() === 119 && inAwaitContext()) { return false; } - return token > 105; + return token() > 105; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token === kind) { + if (token() === kind) { if (shouldAdvance) { nextToken(); } @@ -7991,14 +11908,14 @@ var ts; return false; } function parseOptional(t) { - if (token === t) { + if (token() === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token === t) { + if (token() === t) { return parseTokenNode(); } return undefined; @@ -8008,19 +11925,19 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token); + var node = createNode(token()); nextToken(); return finishNode(node); } function canParseSemicolon() { - if (token === 23) { + if (token() === 23) { return true; } - return token === 16 || token === 1 || scanner.hasPrecedingLineBreak(); + return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token === 23) { + if (token() === 23) { nextToken(); } return true; @@ -8034,7 +11951,18 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new NodeConstructor(kind, pos, pos); + return kind >= 139 ? new NodeConstructor(kind, pos, pos) : + kind === 69 ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -8043,7 +11971,7 @@ var ts; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 67108864; + node.flags |= 524288; } return node; } @@ -8060,14 +11988,14 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); + return identifiers[text] || (identifiers[text] = text); } function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { var node = createNode(69); - if (token !== 69) { - node.originalKeywordKind = token; + if (token() !== 69) { + node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -8079,18 +12007,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token) || - token === 9 || - token === 8; + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token === 9 || token === 8) { + if (token() === 9 || token() === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token === 19) { + if (allowComputedPropertyNames && token() === 19) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -8102,7 +12030,7 @@ var ts; return parsePropertyNameWorker(false); } function isSimplePropertyName() { - return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { var node = createNode(140); @@ -8112,7 +12040,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8122,39 +12050,39 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token === 74) { + if (token() === 74) { return nextToken() === 81; } - if (token === 82) { + if (token() === 82) { nextToken(); - if (token === 77) { + if (token() === 77) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token !== 37 && token !== 116 && token !== 15 && canFollowModifier(); + return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); } - if (token === 77) { + if (token() === 77) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token === 113) { + if (token() === 113) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token === 19 - || token === 15 - || token === 37 - || token === 22 + return token() === 19 + || token() === 15 + || token() === 37 + || token() === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token === 73 || token === 87 || - (token === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 73 || token() === 87 || + (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -8165,21 +12093,21 @@ var ts; case 0: case 1: case 3: - return !(token === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); case 2: - return token === 71 || token === 77; + return token() === 71 || token() === 77; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); case 6: - return token === 19 || isLiteralPropertyName(); + return token() === 19 || isLiteralPropertyName(); case 12: - return token === 19 || token === 37 || isLiteralPropertyName(); + return token() === 19 || token() === 37 || isLiteralPropertyName(); case 9: - return token === 19 || isLiteralPropertyName(); + return token() === 19 || isLiteralPropertyName(); case 7: - if (token === 15) { + if (token() === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -8191,23 +12119,23 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token === 24 || token === 22 || isIdentifierOrPattern(); + return token() === 24 || token() === 22 || isIdentifierOrPattern(); case 17: return isIdentifier(); case 11: case 15: - return token === 24 || token === 22 || isStartOfExpression(); + return token() === 24 || token() === 22 || isStartOfExpression(); case 16: return isStartOfParameter(); case 18: case 19: - return token === 24 || isStartOfType(); + return token() === 24 || isStartOfType(); case 20: return isHeritageClause(); case 21: - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); case 13: - return ts.tokenIsIdentifierOrKeyword(token) || token === 15; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; case 14: return true; case 22: @@ -8220,7 +12148,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token === 15); + ts.Debug.assert(token() === 15); if (nextToken() === 16) { var next = nextToken(); return next === 24 || next === 15 || next === 83 || next === 106; @@ -8233,11 +12161,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token === 106 || - token === 83) { + if (token() === 106 || + token() === 83) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -8247,7 +12175,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token === 1) { + if (token() === 1) { return true; } switch (kind) { @@ -8259,49 +12187,49 @@ var ts; case 12: case 9: case 21: - return token === 16; + return token() === 16; case 3: - return token === 16 || token === 71 || token === 77; + return token() === 16 || token() === 71 || token() === 77; case 7: - return token === 15 || token === 83 || token === 106; + return token() === 15 || token() === 83 || token() === 106; case 8: return isVariableDeclaratorListTerminator(); case 17: - return token === 27 || token === 17 || token === 15 || token === 83 || token === 106; + return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; case 11: - return token === 18 || token === 23; + return token() === 18 || token() === 23; case 15: case 19: case 10: - return token === 20; + return token() === 20; case 16: - return token === 18 || token === 20; + return token() === 18 || token() === 20; case 18: - return token === 27 || token === 17; + return token() === 27 || token() === 17; case 20: - return token === 15 || token === 16; + return token() === 15 || token() === 16; case 13: - return token === 27 || token === 39; + return token() === 27 || token() === 39; case 14: - return token === 25 && lookAhead(nextTokenIsSlash); + return token() === 25 && lookAhead(nextTokenIsSlash); case 22: - return token === 18 || token === 54 || token === 16; + return token() === 18 || token() === 54 || token() === 16; case 23: - return token === 27 || token === 16; + return token() === 27 || token() === 16; case 25: - return token === 20 || token === 16; + return token() === 20 || token() === 16; case 24: - return token === 16; + return token() === 16; } } function isVariableDeclaratorListTerminator() { if (canParseSemicolon()) { return true; } - if (isInOrOfKeyword(token)) { + if (isInOrOfKeyword(token())) { return true; } - if (token === 34) { + if (token() === 34) { return true; } return false; @@ -8319,8 +12247,7 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); @@ -8359,7 +12286,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 197132288; + var nodeContextFlags = node.flags & 1540096; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -8541,8 +12468,7 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); var commaStart = -1; while (true) { if (isListElement(kind, false)) { @@ -8556,7 +12482,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -8576,11 +12502,7 @@ var ts; return result; } function createMissingList() { - var pos = getNodePos(); - var result = []; - result.pos = pos; - result.end = pos; - return result; + return createNodeArray(); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -8601,7 +12523,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); @@ -8613,8 +12535,7 @@ var ts; var template = createNode(189); template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); - var templateSpans = []; - templateSpans.pos = getNodePos(); + var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); } while (ts.lastOrUndefined(templateSpans).literal.kind === 13); @@ -8626,7 +12547,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16) { + if (token() === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -8636,14 +12557,11 @@ var ts; span.literal = literal; return finishNode(span); } - function parseStringLiteralTypeNode() { - return parseLiteralLikeNode(166, true); - } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token, internName); + return parseLiteralLikeNode(token(), internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token, false); + return parseLiteralLikeNode(token(), false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -8669,7 +12587,7 @@ var ts; var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); var node = createNode(155, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token === 25) { + if (!scanner.hasPrecedingLineBreak() && token() === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); @@ -8706,7 +12624,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25) { + if (token() === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -8717,26 +12635,20 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; - } - function setModifiers(node, modifiers) { - if (modifiers) { - node.flags |= modifiers.flags; - node.modifiers = modifiers; - } + return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; } function parseParameter() { var node = createNode(142); - if (token === 97) { + if (token() === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -8791,20 +12703,20 @@ var ts; } fillSignature(54, false, false, false, node); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token !== 19) { + if (token() !== 19) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token === 22 || token === 20) { + if (token() === 22 || token() === 20) { return true; } - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { nextToken(); if (isIdentifier()) { return true; @@ -8816,19 +12728,19 @@ var ts; else { nextToken(); } - if (token === 54 || token === 24) { + if (token() === 54 || token() === 24) { return true; } - if (token !== 53) { + if (token() !== 53) { return false; } nextToken(); - return token === 54 || token === 24 || token === 20; + return token() === 54 || token() === 24 || token() === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.parameters = parseBracketedList(16, parseParameter, 19, 20); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); @@ -8837,58 +12749,59 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { var method = createNode(146, fullStart); - setModifiers(method, modifiers); + method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; fillSignature(54, false, false, false, method); parseTypeMemberSemicolon(); - return finishNode(method); + return addJSDocComment(finishNode(method)); } else { var property = createNode(144, fullStart); - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56) { + if (token() === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } } function isTypeMemberStart() { var idToken; - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { return true; } - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); nextToken(); } - if (token === 19) { + if (token() === 19) { return true; } if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } if (idToken) { - return token === 17 || - token === 25 || - token === 53 || - token === 54 || + return token() === 17 || + token() === 25 || + token() === 53 || + token() === 54 || + token() === 24 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { return parseSignatureMember(151); } - if (token === 92 && lookAhead(isStartOfConstructSignature)) { + if (token() === 92 && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152); } var fullStart = getNodePos(); @@ -8900,7 +12813,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 || token === 25; + return token() === 17 || token() === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -8940,10 +12853,19 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token === 21 ? undefined : node; + return token() === 21 ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(166); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8; } function parseNonArrayType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -8954,13 +12876,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: - return parseStringLiteralTypeNode(); + case 8: + case 99: + case 84: + return parseLiteralTypeNode(); + case 36: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); case 103: case 93: return parseTokenNode(); case 97: { var thisKeyword = parseThisTypeNode(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -8980,7 +12907,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -8997,7 +12924,12 @@ var ts; case 25: case 92: case 9: + case 8: + case 99: + case 84: return true; + case 36: + return lookAhead(nextTokenIsNumericLiteral); case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); default: @@ -9006,7 +12938,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 || isStartOfParameter() || isStartOfType(); + return token() === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -9020,9 +12952,8 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { - var types = [type]; - types.pos = type.pos; + if (token() === operator) { + var types = createNodeArray([type], type.pos); while (parseOptional(operator)) { types.push(parseConstituentType()); } @@ -9040,20 +12971,20 @@ var ts; return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { - if (token === 25) { + if (token() === 25) { return true; } - return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { parseModifiers(); } - if (isIdentifier() || token === 97) { + if (isIdentifier() || token() === 97) { nextToken(); return true; } - if (token === 19 || token === 15) { + if (token() === 19 || token() === 15) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -9062,17 +12993,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token === 18 || token === 22) { + if (token() === 18 || token() === 22) { return true; } if (skipParameterStart()) { - if (token === 54 || token === 24 || - token === 53 || token === 56) { + if (token() === 54 || token() === 24 || + token() === 53 || token() === 56) { return true; } - if (token === 18) { + if (token() === 18) { nextToken(); - if (token === 34) { + if (token() === 34) { return true; } } @@ -9094,19 +13025,19 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseType() { - return doOutsideOfContext(41943040, parseTypeWorker); + return doOutsideOfContext(327680, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token === 92) { + if (token() === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -9115,7 +13046,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97: case 95: case 93: @@ -9143,7 +13074,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9165,10 +13096,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token !== 15 && - token !== 87 && - token !== 73 && - token !== 55 && + return token() !== 15 && + token() !== 87 && + token() !== 73 && + token() !== 55 && isStartOfExpression(); } function parseExpression() { @@ -9187,8 +13118,8 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15) || !isStartOfExpression()) { + if (token() !== 56) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { return undefined; } } @@ -9204,7 +13135,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token === 34) { + if (expr.kind === 69 && token() === 34) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -9213,7 +13144,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114) { + if (token() === 114) { if (inYieldContext()) { return true; } @@ -9229,7 +13160,7 @@ var ts; var node = createNode(190); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token === 37 || isStartOfExpression())) { + (token() === 37 || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -9239,11 +13170,11 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180, asyncModifier.pos); - setModifiers(node, asyncModifier); + node.modifiers = asyncModifier; } else { node = createNode(180, identifier.pos); @@ -9251,12 +13182,11 @@ var ts; var parameter = createNode(142, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = [parameter]; - node.parameters.pos = parameter.pos; + node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; node.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function tryParseParenthesizedArrowFunctionExpression() { var triState = isParenthesizedArrowFunctionExpression(); @@ -9269,34 +13199,34 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token; + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return finishNode(arrowFunction); + return addJSDocComment(finishNode(arrowFunction)); } function isParenthesizedArrowFunctionExpression() { - if (token === 17 || token === 25 || token === 118) { + if (token() === 17 || token() === 25 || token() === 118) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token === 34) { + if (token() === 34) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token === 118) { + if (token() === 118) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token !== 17 && token !== 25) { + if (token() !== 17 && token() !== 25) { return 0; } } - var first = token; + var first = token(); var second = nextToken(); if (first === 17) { if (second === 18) { @@ -9359,7 +13289,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token === 118) { + if (token() === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -9370,13 +13300,13 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token === 118) { + if (token() === 118) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token === 34) { + if (scanner.hasPrecedingLineBreak() || token() === 34) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { return 1; } } @@ -9384,24 +13314,24 @@ var ts; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(180); - setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 256); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = !!(ts.getModifierFlags(node) & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token !== 34 && token !== 15) { + if (!allowAmbiguity && token() !== 34 && token() !== 15) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token === 15) { + if (token() === 15) { return parseFunctionBlock(false, isAsync, false); } - if (token !== 23 && - token !== 87 && - token !== 73 && + if (token() !== 23 && + token() !== 87 && + token() !== 73 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -9434,16 +13364,16 @@ var ts; while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token === 38 ? + var consumeCurrentOperator = token() === 38 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token === 90 && inDisallowInContext()) { + if (token() === 90 && inDisallowInContext()) { break; } - if (token === 116) { + if (token() === 116) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -9459,13 +13389,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token === 90) { + if (inDisallowInContext() && token() === 90) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token) { + switch (token()) { case 52: return 1; case 51: @@ -9520,7 +13450,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -9544,7 +13474,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119) { + if (token() === 119) { if (inAwaitContext()) { return true; } @@ -9559,18 +13489,15 @@ var ts; return finishNode(node); } function parseUnaryExpressionOrHigher() { - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - if (isIncrementExpression()) { + if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token === 38 ? + return token() === 38 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token; + var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token === 38) { + if (token() === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -9582,7 +13509,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9596,12 +13523,16 @@ var ts; return parseVoidExpression(); case 25: return parseTypeAssertion(); + case 119: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } } - function isIncrementExpression() { - switch (token) { + function isUpdateExpression() { + switch (token()) { case 35: case 36: case 50: @@ -9609,6 +13540,7 @@ var ts; case 78: case 101: case 103: + case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -9619,29 +13551,29 @@ var ts; } } function parseIncrementExpression() { - if (token === 41 || token === 42) { + if (token() === 41 || token() === 42) { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { + if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186, expression.pos); node.operand = expression; - node.operator = token; + node.operator = token(); nextToken(); return finishNode(node); } return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token === 95 + var expression = token() === 95 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -9652,7 +13584,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token === 17 || token === 21 || token === 19) { + if (token() === 17 || token() === 21 || token() === 19) { return expression; } var node = createNode(172, expression.pos); @@ -9691,7 +13623,7 @@ var ts; ts.Debug.assert(opening.kind === 242); result = opening; } - if (inExpressionContext && token === 25) { + if (inExpressionContext && token() === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -9708,11 +13640,11 @@ var ts; } function parseJsxText() { var node = createNode(244, scanner.getStartPos()); - token = scanner.scanJsxToken(); + currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token) { + switch (token()) { case 244: return parseJsxText(); case 15: @@ -9720,19 +13652,18 @@ var ts; case 25: return parseJsxElementOrSelfClosingElement(false); } - ts.Debug.fail("Unknown JSX child kind " + token); + ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = []; - result.pos = scanner.getStartPos(); + var result = createNodeArray(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - token = scanner.reScanJsxToken(); - if (token === 26) { + currentToken = scanner.reScanJsxToken(); + if (token() === 26) { break; } - else if (token === 1) { + else if (token() === 1) { parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } @@ -9748,7 +13679,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token === 27) { + if (token() === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -9769,7 +13700,7 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token === 97 ? + var expression = token() === 97 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21)) { var propertyAccess = createNode(172, expression.pos); @@ -9782,7 +13713,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token !== 16) { + if (token() !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -9795,14 +13726,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token === 15) { + if (token() === 15) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246); node.name = parseIdentifierName(); - if (parseOptional(56)) { - switch (token) { + if (token() === 56) { + switch (scanJsxAttributeValue()) { case 9: node.initializer = parseLiteralNode(); break; @@ -9852,7 +13783,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token === 49 && !scanner.hasPrecedingLineBreak()) { + if (token() === 49 && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196, expression.pos); nonNullExpression.expression = expression; @@ -9862,7 +13793,7 @@ var ts; if (!inDecoratorContext() && parseOptional(19)) { var indexedAccess = createNode(173, expression.pos); indexedAccess.expression = expression; - if (token !== 20) { + if (token() !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; @@ -9873,10 +13804,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token === 11 || token === 12) { + if (token() === 11 || token() === 12) { var tagExpression = createNode(176, expression.pos); tagExpression.tag = expression; - tagExpression.template = token === 11 + tagExpression.template = token() === 11 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -9888,7 +13819,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token === 25) { + if (token() === 25) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; @@ -9900,7 +13831,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token === 17) { + else if (token() === 17) { var callExpr = createNode(174, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -9929,7 +13860,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17: case 21: case 18: @@ -9956,7 +13887,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8: case 9: case 11: @@ -10009,8 +13940,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token === 22 ? parseSpreadElement() : - token === 24 ? createNode(193) : + return token() === 22 ? parseSpreadElement() : + token() === 24 ? createNode(193) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -10028,7 +13959,7 @@ var ts; } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123)) { - return addJSDocComment(parseAccessorDeclaration(149, fullStart, decorators, modifiers)); + return parseAccessorDeclaration(149, fullStart, decorators, modifiers); } else if (parseContextualModifier(131)) { return parseAccessorDeclaration(150, fullStart, decorators, modifiers); @@ -10047,10 +13978,10 @@ var ts; var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token === 17 || token === 25) { + if (asteriskToken || token() === 17 || token() === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254, fullStart); shorthandDeclaration.name = propertyName; @@ -10088,11 +14019,11 @@ var ts; setDecoratorContext(false); } var node = createNode(179); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); parseExpected(87); node.asteriskToken = parseOptionalToken(37); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256); + var isAsync = !!(ts.getModifierFlags(node) & 256); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -10113,7 +14044,7 @@ var ts; parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token === 17) { + if (node.typeArguments || token() === 17) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -10121,6 +14052,9 @@ var ts; function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var node = createNode(199); if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.statements = parseList(1, parseStatement); parseExpected(16); } @@ -10186,8 +14120,8 @@ var ts; parseExpected(86); parseExpected(17); var initializer = undefined; - if (token !== 23) { - if (token === 102 || token === 108 || token === 74) { + if (token() !== 23) { + if (token() === 102 || token() === 108 || token() === 74) { initializer = parseVariableDeclarationList(true); } else { @@ -10213,11 +14147,11 @@ var ts; var forStatement = createNode(206, pos); forStatement.initializer = initializer; parseExpected(23); - if (token !== 23 && token !== 18) { + if (token() !== 23 && token() !== 18) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23); - if (token !== 18) { + if (token() !== 18) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18); @@ -10269,7 +14203,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -10295,8 +14229,8 @@ var ts; var node = createNode(216); parseExpected(100); node.tryBlock = parseBlock(false); - node.catchClause = token === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token === 85) { + node.catchClause = token() === 72 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 85) { parseExpected(85); node.finallyBlock = parseBlock(false); } @@ -10336,19 +14270,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token === 87 && !scanner.hasPrecedingLineBreak(); + return token() === 87 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token) || token === 8) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -10376,16 +14310,16 @@ var ts; continue; case 137: nextToken(); - return token === 15 || token === 69 || token === 82; + return token() === 15 || token() === 69 || token() === 82; case 89: nextToken(); - return token === 9 || token === 37 || - token === 15 || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 || token() === 37 || + token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); case 82: nextToken(); - if (token === 56 || token === 37 || - token === 15 || token === 77 || - token === 116) { + if (token() === 56 || token() === 37 || + token() === 15 || token() === 77 || + token() === 116) { return true; } continue; @@ -10401,7 +14335,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55: case 23: case 15: @@ -10449,13 +14383,13 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token === 15 || token === 19; + return isIdentifier() || token() === 15 || token() === 19; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token) { + switch (token()) { case 23: return parseEmptyStatement(); case 15: @@ -10527,7 +14461,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -10550,7 +14484,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token) { + switch (token()) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -10564,24 +14498,24 @@ var ts; var node = createMissingNode(239, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; return finishNode(node); } } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token !== 15 && canParseSemicolon()) { + if (token() !== 15 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token === 24) { + if (token() === 24) { return createNode(193); } var node = createNode(169); @@ -10594,7 +14528,7 @@ var ts; var node = createNode(169); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token !== 54) { + if (tokenIsIdentifier && token() !== 54) { node.name = propertyName; } else { @@ -10620,13 +14554,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token === 15 || token === 19 || isIdentifier(); + return token() === 15 || token() === 19 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token === 19) { + if (token() === 19) { return parseArrayBindingPattern(); } - if (token === 15) { + if (token() === 15) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -10635,27 +14569,27 @@ var ts; var node = createNode(218); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token)) { + if (!isInOrOfKeyword(token())) { node.initializer = parseInitializer(false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219); - switch (token) { + switch (token()) { case 102: break; case 108: - node.flags |= 1024; + node.flags |= 1; break; case 74: - node.flags |= 2048; + node.flags |= 2; break; default: ts.Debug.fail(); } nextToken(); - if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -10672,7 +14606,7 @@ var ts; function parseVariableStatement(fullStart, decorators, modifiers) { var node = createNode(200, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); return addJSDocComment(finishNode(node)); @@ -10680,12 +14614,12 @@ var ts; function parseFunctionDeclaration(fullStart, decorators, modifiers) { var node = createNode(220, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(87); node.asteriskToken = parseOptionalToken(37); - node.name = node.flags & 512 ? parseOptionalIdentifier() : parseIdentifier(); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256); + var isAsync = ts.hasModifier(node, 256); fillSignature(54, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); @@ -10693,7 +14627,7 @@ var ts; function parseConstructorDeclaration(pos, decorators, modifiers) { var node = createNode(148, pos); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(121); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); @@ -10702,12 +14636,12 @@ var ts; function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { var method = createNode(147, fullStart); method.decorators = decorators; - setModifiers(method, modifiers); + method.modifiers = modifiers; method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 256); + var isAsync = ts.hasModifier(method, 256); fillSignature(54, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); @@ -10715,21 +14649,21 @@ var ts; function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { var property = createNode(145, fullStart); property.decorators = decorators; - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = modifiers && modifiers.flags & 32 + property.initializer = ts.hasModifier(property, 32) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(8388608 | 4194304, parseNonParameterInitializer); + : doOutsideOfContext(65536 | 32768, parseNonParameterInitializer); parseSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { var asteriskToken = parseOptionalToken(37); var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token === 17 || token === 25) { + if (asteriskToken || token() === 17 || token() === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -10742,11 +14676,11 @@ var ts; function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.name = parsePropertyName(); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -10762,31 +14696,31 @@ var ts; } function isClassMemberStart() { var idToken; - if (token === 55) { + if (token() === 55) { return true; } - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); if (isClassMemberModifier(idToken)) { return true; } nextToken(); } - if (token === 37) { + if (token() === 37) { return true; } if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } - if (token === 19) { + if (token() === 19) { return true; } if (idToken !== undefined) { if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { return true; } - switch (token) { + switch (token()) { case 17: case 25: case 54: @@ -10806,13 +14740,15 @@ var ts; if (!parseOptional(55)) { break; } - if (!decorators) { - decorators = []; - decorators.pos = decoratorStart; - } var decorator = createNode(143, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - decorators.push(finishNode(decorator)); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } } if (decorators) { decorators.end = getNodeEnd(); @@ -10820,12 +14756,11 @@ var ts; return decorators; } function parseModifiers(permitInvalidConstAsModifier) { - var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; - if (token === 74 && permitInvalidConstAsModifier) { + var modifierKind = token(); + if (token() === 74 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -10835,37 +14770,33 @@ var ts; break; } } + var modifier = finishNode(createNode(modifierKind, modifierStart)); if (!modifiers) { - modifiers = []; - modifiers.pos = modifierStart; + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); } - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); } if (modifiers) { - modifiers.flags = flags; modifiers.end = scanner.getStartPos(); } return modifiers; } function parseModifiersForArrowFunction() { - var flags = 0; var modifiers; - if (token === 118) { + if (token() === 118) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; + var modifierKind = token(); nextToken(); - modifiers = []; - modifiers.pos = modifierStart; - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); - modifiers.flags = flags; + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); modifiers.end = scanner.getStartPos(); } return modifiers; } function parseClassElement() { - if (token === 23) { + if (token() === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -10877,22 +14808,22 @@ var ts; if (accessor) { return accessor; } - if (token === 121) { + if (token() === 121) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); } - if (ts.tokenIsIdentifierOrKeyword(token) || - token === 9 || - token === 8 || - token === 37 || - token === 19) { + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8 || + token() === 37 || + token() === 19) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); + var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10905,7 +14836,7 @@ var ts; function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(73); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -10917,7 +14848,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseNameOfClassDeclarationOrExpression() { return isIdentifier() && !isImplementsClause() @@ -10925,7 +14856,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -10934,9 +14865,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token === 83 || token === 106) { + if (token() === 83 || token() === 106) { var node = createNode(251); - node.token = token; + node.token = token(); nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); @@ -10946,13 +14877,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token === 25) { + if (token() === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } function isHeritageClause() { - return token === 83 || token === 106; + return token() === 83 || token() === 106; } function parseClassMembers() { return parseList(5, parseClassElement); @@ -10960,18 +14891,18 @@ var ts; function parseInterfaceDeclaration(fullStart, decorators, modifiers) { var node = createNode(222, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(107); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(false); node.members = parseObjectTypeMembers(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { var node = createNode(223, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(134); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -10984,12 +14915,12 @@ var ts; var node = createNode(255, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { var node = createNode(224, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(81); node.name = parseIdentifier(); if (parseExpected(15)) { @@ -10999,7 +14930,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseModuleBlock() { var node = createNode(226, scanner.getStartPos()); @@ -11014,28 +14945,28 @@ var ts; } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { var node = createNode(225, fullStart); - var namespaceFlag = flags & 4096; + var namespaceFlag = flags & 16; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 1 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) : parseModuleBlock(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { var node = createNode(225, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); - if (token === 137) { + node.modifiers = modifiers; + if (token() === 137) { node.name = parseIdentifier(); - node.flags |= 131072; + node.flags |= 512; } else { node.name = parseLiteralNode(true); } - if (token === 15) { + if (token() === 15) { node.body = parseModuleBlock(); } else { @@ -11044,23 +14975,23 @@ var ts; return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = modifiers ? modifiers.flags : 0; - if (token === 137) { + var flags = 0; + if (token() === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { - flags |= 4096; + flags |= 16; } else { parseExpected(125); - if (token === 9) { + if (token() === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 129 && + return token() === 129 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -11085,23 +15016,23 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 && token !== 136) { + if (token() !== 24 && token() !== 136) { var importEqualsDeclaration = createNode(229, fullStart); importEqualsDeclaration.decorators = decorators; - setModifiers(importEqualsDeclaration, modifiers); + importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; parseExpected(56); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); - return finishNode(importEqualsDeclaration); + return addJSDocComment(finishNode(importEqualsDeclaration)); } } var importDeclaration = createNode(230, fullStart); importDeclaration.decorators = decorators; - setModifiers(importDeclaration, modifiers); + importDeclaration.modifiers = modifiers; if (identifier || - token === 37 || - token === 15) { + token() === 37 || + token() === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -11116,7 +15047,7 @@ var ts; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); } return finishNode(importClause); } @@ -11134,7 +15065,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9) { + if (token() === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -11163,14 +15094,14 @@ var ts; } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token === 116) { + if (token() === 116) { node.propertyName = identifierName; parseExpected(116); - checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -11186,14 +15117,14 @@ var ts; function parseExportDeclaration(fullStart, decorators, modifiers) { var node = createNode(236, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(37)) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } else { node.exportClause = parseNamedImportsOrExports(237); - if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -11204,7 +15135,7 @@ var ts; function parseExportAssignment(fullStart, decorators, modifiers) { var node = createNode(235, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(56)) { node.isExportEquals = true; } @@ -11280,7 +15211,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 + return ts.hasModifier(node, 1) || node.kind === 229 && node.moduleReference.kind === 240 || node.kind === 230 || node.kind === 235 @@ -11292,7 +15223,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37: case 53: case 17: @@ -11305,13 +15236,14 @@ var ts; case 97: return true; } - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2, undefined, 1); + sourceFile = createSourceFile("file.js", 2, 1); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -11329,12 +15261,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token === 47) { + if (token() === 47) { var unionType = createNode(261, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token === 56) { + if (token() === 56) { var optionalType = createNode(268, type.pos); nextToken(); optionalType.type = type; @@ -11345,20 +15277,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token === 19) { + if (token() === 19) { var arrayType = createNode(260, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } - else if (token === 53) { + else if (token() === 53) { var nullableType = createNode(263, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token === 49) { + else if (token() === 49) { var nonNullableType = createNode(264, type.pos); nonNullableType.type = type; nextToken(); @@ -11371,7 +15303,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37: return parseJSDocAllType(); case 53: @@ -11398,7 +15330,15 @@ var ts; case 120: case 133: case 103: + case 93: + case 135: + case 127: return parseTokenNode(); + case 9: + case 8: + case 99: + case 84: + return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } @@ -11429,7 +15369,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -11446,12 +15386,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267); result.name = parseSimplePropertyName(); - if (token === 25) { + if (token() === 25) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21)) { - if (token === 25) { + if (token() === 25) { result.typeArguments = parseTypeArguments(); break; } @@ -11485,19 +15425,7 @@ var ts; } function parseJSDocRecordType() { var result = createNode(265); - nextToken(); - result.members = parseDelimitedList(24, parseJSDocRecordMember); - checkForTrailingComma(result.members); - parseExpected(16); - return finishNode(result); - } - function parseJSDocRecordMember() { - var result = createNode(266); - result.name = parseSimplePropertyName(); - if (token === 54) { - nextToken(); - result.type = parseJSDocType(); - } + result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { @@ -11529,9 +15457,7 @@ var ts; } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); - var types = []; - types.pos = firstType.pos; - types.push(firstType); + var types = createNodeArray([firstType], firstType.pos); while (parseOptional(47)) { types.push(parseJSDocType()); } @@ -11543,15 +15469,20 @@ var ts; nextToken(); return finishNode(result); } + function parseJSDocLiteralType() { + var result = createNode(282); + result.literal = parseLiteralTypeNode(); + return finishNode(result); + } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token === 24 || - token === 16 || - token === 18 || - token === 27 || - token === 56 || - token === 47) { + if (token() === 24 || + token() === 16 || + token() === 18 || + token() === 27 || + token() === 56 || + token() === 47) { var result = createNode(259, pos); return finishNode(result); } @@ -11564,21 +15495,21 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { initializeState("file.js", content, 2, undefined, 1); sourceFile = { languageVariant: 0, text: content }; - var jsDocComment = parseJSDocCommentWorker(start, length); + var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); - return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -11593,125 +15524,254 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var comments = []; var result; - if (content.charCodeAt(start) === 47 && - content.charCodeAt(start + 1) === 42 && - content.charCodeAt(start + 2) === 42 && - content.charCodeAt(start + 3) !== 42) { - scanner.scanRange(start + 3, length - 5, function () { - var canParseTag = true; - var seenAsterisk = true; + if (!isJsDocStart(content, start)) { + return result; + } + scanner.scanRange(start + 3, length - 5, function () { + var advanceToken = true; + var state = 1; + var margin = undefined; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5) { nextJSDocToken(); - while (token !== 1) { - switch (token) { - case 55: - if (canParseTag) { - parseTag(); - } - seenAsterisk = false; - break; - case 4: - canParseTag = true; - seenAsterisk = false; - break; - case 37: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 69: - canParseTag = false; - break; - case 1: - break; - } + } + if (token() === 4) { + state = 0; + nextJSDocToken(); + } + while (token() !== 1) { + switch (token()) { + case 55: + if (state === 0 || state === 1) { + removeTrailingNewlines(comments); + parseTag(indent); + state = 0; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 37: + var asterisk = scanner.getTokenText(); + if (state === 1) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 69: + pushComment(scanner.getTokenText()); + state = 2; + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break; + default: + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { nextJSDocToken(); } - result = createJSDocComment(); - }); - } - return result; - function createJSDocComment() { - if (!tags) { - return undefined; + else { + advanceToken = true; + } } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42; + } + function createJSDocComment() { var result = createNode(273, start); result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 || token === 4) { + while (token() === 5 || token() === 4) { nextJSDocToken(); } } - function parseTag() { - ts.Debug.assert(token === 55); + function parseTag(indent) { + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return; } - var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); - addTag(tag); - } - function handleTag(atToken, tagName) { + var tag; if (tagName) { switch (tagName.text) { case "param": - return handleParamTag(atToken, tagName); + tag = parseParamTag(atToken, tagName); + break; case "return": case "returns": - return handleReturnTag(atToken, tagName); + tag = parseReturnTag(atToken, tagName); + break; case "template": - return handleTemplateTag(atToken, tagName); + tag = parseTemplateTag(atToken, tagName); + break; case "type": - return handleTypeTag(atToken, tagName); + tag = parseTypeTag(atToken, tagName); + break; case "typedef": - return handleTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; } } - return undefined; + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); } - function handleUnknownTag(atToken, tagName) { + function parseTagComments(indent) { + var comments = []; + var state = 1; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 55 && token() !== 1) { + switch (token()) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 55: + break; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 37: + if (state === 0) { + state = 1; + indent += scanner.getTokenText().length; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (token() === 55) { + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { var result = createNode(274, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } - function addTag(tag) { - if (tag) { - if (!tags) { - tags = []; - tags.pos = tag.pos; - } - tags.push(tag); - tags.end = tag.end; + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); } + else { + tags.push(tag); + } + tags.end = tag.end; } function tryParseTypeExpression() { - if (token !== 15) { - return undefined; - } - var typeExpression = parseJSDocTypeExpression(); - return typeExpression; + return tryParse(function () { + skipWhitespace(); + if (token() !== 15) { + return undefined; + } + return parseJSDocTypeExpression(); + }); } - function handleParamTag(atToken, tagName) { + function parseParamTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name; var isBracketed; if (parseOptionalToken(19)) { name = parseJSDocIdentifierName(); + skipWhitespace(); isBracketed = true; if (parseOptionalToken(56)) { parseExpression(); } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -11734,10 +15794,11 @@ var ts; result.preParameterName = preName; result.typeExpression = typeExpression; result.postParameterName = postName; + result.parameterName = postName || preName; result.isBracketed = isBracketed; return finishNode(result); } - function handleReturnTag(atToken, tagName) { + function parseReturnTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 276; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -11747,7 +15808,7 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handleTypeTag(atToken, tagName) { + function parseTypeTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 277; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -11757,10 +15818,11 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handlePropertyTag(atToken, tagName) { + function parsePropertyTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name = parseJSDocIdentifierName(); + skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; @@ -11772,7 +15834,7 @@ var ts; result.typeExpression = typeExpression; return finishNode(result); } - function handleTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var typedefTag = createNode(279, atToken.pos); @@ -11780,12 +15842,13 @@ var ts; typedefTag.tagName = tagName; typedefTag.name = parseJSDocIdentifierName(); typedefTag.typeExpression = typeExpression; + skipWhitespace(); if (typeExpression) { if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_9 = jsDocTypeReference.name; - if (name_9.text === "Object") { + var name_13 = jsDocTypeReference.name; + if (name_13.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11804,12 +15867,15 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token !== 1 && !parentTagTerminated) { + while (token() !== 1 && !parentTagTerminated) { nextJSDocToken(); - switch (token) { + switch (token()) { case 55: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); + if (!parentTagTerminated) { + resumePos = scanner.getStartPos(); + } } seenAsterisk = false; break; @@ -11835,11 +15901,12 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token === 55); + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return false; } @@ -11848,37 +15915,38 @@ var ts; if (parentTag.jsDocTypeTag) { return false; } - parentTag.jsDocTypeTag = handleTypeTag(atToken, tagName); + parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); return true; case "prop": case "property": if (!parentTag.jsDocPropertyTags) { parentTag.jsDocPropertyTags = []; } - var propertyTag = handlePropertyTag(atToken, tagName); + var propertyTag = parsePropertyTag(atToken, tagName); parentTag.jsDocPropertyTags.push(propertyTag); return true; } return false; } - function handleTemplateTag(atToken, tagName) { + function parseTemplateTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 278; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var typeParameters = []; - typeParameters.pos = scanner.getStartPos(); + var typeParameters = createNodeArray(); while (true) { - var name_10 = parseJSDocIdentifierName(); - if (!name_10) { + var name_14 = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name_14) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_10.pos); - typeParameter.name = name_10; + var typeParameter = createNode(141, name_14.pos); + typeParameter.name = name_14; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24) { + if (token() === 24) { nextJSDocToken(); + skipWhitespace(); } else { break; @@ -11893,10 +15961,10 @@ var ts; return result; } function nextJSDocToken() { - return token = scanner.scanJSDocToken(); + return currentToken = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -12202,7 +16270,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -12210,7 +16277,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 230 || node.kind === 229) && !(node.flags & 1)) { + else if ((node.kind === 230 || node.kind === 229) && !(ts.hasModifier(node, 1))) { return 0; } else if (node.kind === 226) { @@ -12240,9 +16307,10 @@ var ts; ts.getModuleInstanceState = getModuleInstanceState; var binder = createBinder(); function bindSourceFile(file, options) { - var start = new Date().getTime(); + ts.performance.mark("beforeBind"); binder(file, options); - ts.bindTime += new Date().getTime() - start; + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -12270,13 +16338,16 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 }; var reportedUnreachableFlow = { flags: 1 }; + var subtreeTransformFlags = 0; + var skipTransformFlagAggregation; function bindSourceFile(f, opts) { file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; + skipTransformFlagAggregation = ts.isDeclarationFile(file); Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -12300,6 +16371,7 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0; + subtreeTransformFlags = 0; } return bindSourceFile; function createSymbol(flags, name) { @@ -12314,10 +16386,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = {}; + symbol.exports = ts.createMap(); } if (symbolFlags & 6240 && !symbol.members) { - symbol.members = {}; + symbol.members = ts.createMap(); } if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; @@ -12371,14 +16443,14 @@ var ts; break; case 220: case 221: - return node.flags & 512 ? "default" : undefined; + return ts.hasModifier(node, 512) ? "default" : undefined; case 269: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; case 142: ts.Debug.assert(node.parent.kind === 269); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); - return "p" + index; + return "arg" + index; case 279: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; @@ -12398,44 +16470,47 @@ var ts; } function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512; + var isDefaultExport = ts.hasModifier(node, 512); var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name !== undefined) { - symbol = ts.hasProperty(symbolTable, name) - ? symbolTable[name] - : (symbolTable[name] = createSymbol(0, name)); + if (name === undefined) { + symbol = createSymbol(0, "__missing"); + } + else { + symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0, name)); if (name && (includes & 788448)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (node.name) { - node.name.parent = node; + if (symbol.isReplaceableByMethod) { + symbol = symbolTable[name] = createSymbol(0, name); } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + else { + if (node.name) { + node.name.parent = node; } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (ts.hasModifier(declaration, 512)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); + } } } - else { - symbol = createSymbol(0, "__missing"); - } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 8388608) { if (node.kind === 238 || (node.kind === 229 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -12445,10 +16520,10 @@ var ts; } } else { - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793056 ? 2097152 : 0) | - (symbolFlags & 1536 ? 4194304 : 0); + (symbolFlags & 793064 ? 2097152 : 0) | + (symbolFlags & 1920 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -12465,7 +16540,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -12496,11 +16571,11 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); - node.flags &= ~4030464; + node.flags &= ~32128; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { - node.flags |= 32768; + node.flags |= 128; if (hasExplicitReturn) - node.flags |= 65536; + node.flags |= 256; } if (node.kind === 256) { node.flags |= emitFlags; @@ -12521,7 +16596,7 @@ var ts; else if (containerFlags & 64) { seenThisKeyword = false; bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 16384 : node.flags & ~16384; + node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; } else { bindChildren(node); @@ -12530,11 +16605,24 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindChildrenWorker(node) { if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - bind(jsDocComment); - } + ts.forEach(node.jsDocComments, bind); } if (checkUnreachable(node)) { ts.forEachChild(node, bind); @@ -12583,6 +16671,9 @@ var ts; case 185: bindPrefixUnaryExpressionFlow(node); break; + case 186: + bindPostfixUnaryExpressionFlow(node); + break; case 187: bindBinaryExpressionFlow(node); break; @@ -12640,15 +16731,9 @@ var ts; } return false; } - function isNarrowingNullCheckOperands(expr1, expr2) { - return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); - } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } - function isNarrowingDiscriminant(expr) { - return expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -12657,9 +16742,8 @@ var ts; case 31: case 32: case 33: - return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || - isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 91: return isNarrowableOperand(expr.left); case 24: @@ -12681,10 +16765,6 @@ var ts; } return isNarrowableReference(expr); } - function isNarrowingSwitchStatement(switchStatement) { - var expr = switchStatement.expression; - return expr.kind === 172 && isNarrowableReference(expr.expression); - } function createBranchLabel() { return { flags: 4, @@ -12728,7 +16808,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -13069,6 +17149,15 @@ var ts; } else { ts.forEachChild(node, bind); + if (node.operator === 57 || node.operator === 42) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + ts.forEachChild(node, bind); + if (node.operator === 41 || node.operator === 42) { + bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { @@ -13110,7 +17199,7 @@ var ts; currentFlow = finishFlowLabel(postExpressionLabel); } function bindInitializedVariableFlow(node) { - var name = node.name; + var name = !ts.isOmittedExpression(node) ? node.name : undefined; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var child = _a[_i]; @@ -13234,7 +17323,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 32 + return ts.hasModifier(node, 32) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -13257,16 +17346,16 @@ var ts; } function setExportContextFlag(node) { if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 8192; + node.flags |= 32; } else { - node.flags &= ~8192; + node.flags &= ~32; } } function bindModuleDeclaration(node) { setExportContextFlag(node); if (ts.isAmbientModule(node)) { - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (ts.isExternalModuleAugmentation(node)) { @@ -13316,12 +17405,12 @@ var ts; addDeclarationToSymbol(symbol, node, 131072); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; + typeLiteralSymbol.members = ts.createMap(); + typeLiteralSymbol.members[symbol.name] = symbol; } function bindObjectLiteralExpression(node) { if (inStrictMode) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69) { @@ -13337,8 +17426,8 @@ var ts; continue; } if (currentKind === 1 && existingKind === 1) { - var span = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -13360,7 +17449,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -13401,8 +17490,8 @@ var ts; } function checkStrictModeDeleteExpression(node) { if (inStrictMode && node.expression.kind === 69) { - var span = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -13413,8 +17502,8 @@ var ts; if (name && name.kind === 69) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { - var span = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } } } @@ -13499,6 +17588,9 @@ var ts; } parent = saveParent; } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } inStrictMode = saveInStrictMode; } function updateStrictModeStatementList(statements) { @@ -13573,7 +17665,7 @@ var ts; case 154: return checkTypePredicate(node); case 141: - return declareSymbolAndAddToSymbolTable(node, 262144, 530912); + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); case 142: return bindParameter(node); case 218: @@ -13589,9 +17681,9 @@ var ts; case 254: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 107455); + return bindPropertyOrMethodOrAccessor(node, 8, 900095); case 247: - emitFlags |= 1073741824; + emitFlags |= 16384; return; case 151: case 152: @@ -13631,10 +17723,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222: - return bindBlockScopedDeclaration(node, 64, 792960); + return bindBlockScopedDeclaration(node, 64, 792968); case 279: case 223: - return bindBlockScopedDeclaration(node, 524288, 793056); + return bindBlockScopedDeclaration(node, 524288, 793064); case 224: return bindEnumDeclaration(node); case 225: @@ -13683,15 +17775,14 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 235 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } - else if (boundExpression.kind === 69 && node.kind === 235) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); - } else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); + var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) + ? 8388608 + : 4; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); } } function bindNamespaceExportDeclaration(node) { @@ -13713,7 +17804,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || {}; + file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); } function bindExportDeclaration(node) { @@ -13744,18 +17835,20 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); } function bindThisPropertyAssignment(node) { - var assignee; - if (container.kind === 220 || container.kind === 220) { - assignee = container; + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (container.kind === 220 || container.kind === 179) { + container.symbol.members = container.symbol.members || ts.createMap(); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } else if (container.kind === 148) { - assignee = container.parent; + var saveContainer = container; + container = container.parent; + var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); + if (symbol) { + symbol.isReplaceableByMethod = true; + } + container = saveContainer; } - else { - return; - } - assignee.symbol.members = assignee.symbol.members || {}; - declareSymbol(assignee.symbol.members, assignee.symbol, node, 4, 0 & ~4); } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; @@ -13769,7 +17862,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -13781,10 +17874,10 @@ var ts; function bindClassLikeDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 262144; + emitFlags |= 1024; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288; + emitFlags |= 2048; } } if (node.kind === 221) { @@ -13799,7 +17892,7 @@ var ts; } var symbol = node.symbol; var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (symbol.exports[prototypeSymbol.name]) { if (node.name) { node.name.parent = node; } @@ -13833,7 +17926,7 @@ var ts; if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node) && ts.nodeIsDecorated(node)) { - emitFlags |= (524288 | 1048576); + emitFlags |= (2048 | 4096); } if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); @@ -13852,7 +17945,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } } checkStrictModeFunctionName(node); @@ -13867,7 +17960,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } } if (currentFlow) { @@ -13880,10 +17973,10 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288; + emitFlags |= 2048; } } return ts.hasDynamicName(node) @@ -13902,7 +17995,7 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatement(node) && node.kind !== 201) || + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 201) || node.kind === 221 || (node.kind === 225 && shouldReportErrorOnModuleDeclaration(node)) || (node.kind === 224 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); @@ -13911,7 +18004,7 @@ var ts; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && (node.kind !== 200 || - ts.getCombinedNodeFlags(node.declarationList) & 3072 || + ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); @@ -13921,9 +18014,517 @@ var ts; return true; } } + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 174: + return computeCallExpression(node, subtreeFlags); + case 225: + return computeModuleDeclaration(node, subtreeFlags); + case 178: + return computeParenthesizedExpression(node, subtreeFlags); + case 187: + return computeBinaryExpression(node, subtreeFlags); + case 202: + return computeExpressionStatement(node, subtreeFlags); + case 142: + return computeParameter(node, subtreeFlags); + case 180: + return computeArrowFunction(node, subtreeFlags); + case 179: + return computeFunctionExpression(node, subtreeFlags); + case 220: + return computeFunctionDeclaration(node, subtreeFlags); + case 218: + return computeVariableDeclaration(node, subtreeFlags); + case 219: + return computeVariableDeclarationList(node, subtreeFlags); + case 200: + return computeVariableStatement(node, subtreeFlags); + case 214: + return computeLabeledStatement(node, subtreeFlags); + case 221: + return computeClassDeclaration(node, subtreeFlags); + case 192: + return computeClassExpression(node, subtreeFlags); + case 251: + return computeHeritageClause(node, subtreeFlags); + case 194: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 148: + return computeConstructor(node, subtreeFlags); + case 145: + return computePropertyDeclaration(node, subtreeFlags); + case 147: + return computeMethod(node, subtreeFlags); + case 149: + case 150: + return computeAccessor(node, subtreeFlags); + case 229: + return computeImportEquals(node, subtreeFlags); + case 172: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (subtreeFlags & 262144 + || isSuperOrSuperProperty(expression, expressionKind)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537133909; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 95: + return true; + case 172: + case 173: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 95; + } + return false; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 56 + && (leftKind === 171 + || leftKind === 170)) { + transformFlags |= 192 | 256; + } + else if (operatorTokenKind === 38 + || operatorTokenKind === 60) { + transformFlags |= 48; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + if (node.questionToken) { + transformFlags |= 3; + } + if (subtreeFlags & 2048 + || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + transformFlags |= 3; + } + if (modifierFlags & 92) { + transformFlags |= 3 | 131072; + } + if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { + transformFlags |= 192 | 65536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~538968917; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + if (expressionKind === 195 + || expressionKind === 177) { + transformFlags |= 3; + } + if (expressionTransformFlags & 256) { + transformFlags |= 256; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 192; + if ((subtreeFlags & 137216) + || (modifierFlags & 1)) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537590613; + } + function computeClassExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (subtreeFlags & 137216) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537590613; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 83: + transformFlags |= 192; + break; + case 106: + transformFlags |= 3; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.typeArguments) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var body = node.body; + if (body === undefined) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computeMethod(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var typeParameters = node.typeParameters; + var asteriskToken = node.asteriskToken; + if (!body + || typeParameters + || (modifierFlags & (256 | 128)) + || (subtreeFlags & 2048)) { + transformFlags |= 3; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body + || (modifierFlags & (256 | 128)) + || (subtreeFlags & 2048)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computePropertyDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags | 3; + if (node.initializer) { + transformFlags |= 4096; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var asteriskToken = node.asteriskToken; + if (!body || (modifierFlags & 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 8388608; + if (modifierFlags & 1) { + transformFlags |= 3 | 192; + } + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550726485; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var asteriskToken = node.asteriskToken; + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550726485; + } + function computeArrowFunction(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 8192) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550710101; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (expressionKind === 95) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var nameKind = node.name.kind; + if (nameKind === 167 || nameKind === 168) { + transformFlags |= 192 | 2097152; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags; + if (modifierFlags & 1) { + transformFlags |= 192 | 3; + } + if (declarationListTransformFlags & 2097152) { + transformFlags |= 192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (subtreeFlags & 1048576 + && ts.isIterationStatement(node, true)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.expression.transformFlags & 256) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~546335573; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (node.flags & 3) { + transformFlags |= 192 | 1048576; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~538968917; + } + function computeOther(node, kind, subtreeFlags) { + var transformFlags = subtreeFlags; + var excludeFlags = 536871765; + switch (kind) { + case 112: + case 110: + case 111: + case 115: + case 122: + case 118: + case 74: + case 184: + case 224: + case 255: + case 177: + case 195: + case 196: + case 128: + transformFlags |= 3; + break; + case 241: + case 242: + case 243: + case 244: + case 245: + case 246: + case 247: + case 248: + transformFlags |= 12; + break; + case 82: + transformFlags |= 192 | 3; + break; + case 77: + case 11: + case 12: + case 13: + case 14: + case 189: + case 176: + case 254: + case 208: + transformFlags |= 192; + break; + case 190: + transformFlags |= 192 | 4194304; + break; + case 117: + case 130: + case 127: + case 132: + case 120: + case 133: + case 103: + case 141: + case 144: + case 146: + case 151: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 161: + case 162: + case 163: + case 164: + case 222: + case 223: + case 165: + case 166: + transformFlags = 3; + excludeFlags = -3; + break; + case 140: + transformFlags |= 524288; + if (subtreeFlags & 8192) { + transformFlags |= 32768; + } + break; + case 191: + transformFlags |= 262144; + break; + case 95: + transformFlags |= 192; + break; + case 97: + transformFlags |= 8192; + break; + case 167: + case 168: + transformFlags |= 192 | 2097152; + break; + case 143: + transformFlags |= 3 | 2048; + break; + case 171: + excludeFlags = 537430869; + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + break; + case 170: + case 175: + excludeFlags = 537133909; + if (subtreeFlags & 262144) { + transformFlags |= 192; + } + break; + case 204: + case 205: + case 206: + case 207: + if (subtreeFlags & 1048576) { + transformFlags |= 192; + } + break; + case 256: + if (subtreeFlags & 16384) { + transformFlags |= 192; + } + break; + case 211: + case 209: + case 210: + transformFlags |= 8388608; + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~excludeFlags; + } })(ts || (ts = {})); var ts; (function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -13936,7 +18537,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -13953,7 +18553,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = {}; + var emptySymbols = ts.createMap(); var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -14005,37 +18605,49 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, + getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var stringLiteralTypes = ts.createMap(); + var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var unknownType = createIntrinsicType(1, "unknown"); + var undefinedType = createIntrinsicType(2048, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); + var nullType = createIntrinsicType(4096, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); - var booleanType = createIntrinsicType(8, "boolean"); - var esSymbolType = createIntrinsicType(16777216, "symbol"); - var voidType = createIntrinsicType(16, "void"); - var undefinedType = createIntrinsicType(32, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 | 2097152, "undefined"); - var nullType = createIntrinsicType(64, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 | 2097152, "null"); - var unknownType = createIntrinsicType(1, "unknown"); - var neverType = createIntrinsicType(134217728, "never"); + var trueType = createIntrinsicType(128, "true"); + var falseType = createIntrinsicType(128, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512, "symbol"); + var voidType = createIntrinsicType(1024, "void"); + var neverType = createIntrinsicType(8192, "never"); + var silentNeverType = createIntrinsicType(8192, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = {}; + emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; + anyFunctionType.flags |= 134217728; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, undefined, 0, false, false); var enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = {}; + var globals = ts.createMap(); var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; + var tryGetGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; @@ -14068,10 +18680,8 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var tupleTypes = {}; - var unionTypes = {}; - var intersectionTypes = {}; - var stringLiteralTypes = {}; + var emptyStringType = getLiteralTypeForText(32, ""); + var zeroType = getLiteralTypeForText(64, "0"); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -14087,7 +18697,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1, "number": 2, "boolean": 4, @@ -14095,8 +18705,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128, "number": 256, "boolean": 512, @@ -14104,16 +18714,16 @@ var ts; "undefined": 131072, "object": 2048, "function": 4096 - }; - var typeofTypesByName = { + }); + var typeofTypesByName = ts.createMap({ "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }; + }); var jsxElementType; - var jsxTypes = {}; + var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -14123,15 +18733,14 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = {}; - var assignableRelation = {}; - var comparableRelation = {}; - var identityRelation = {}; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); var _displayBuilder; - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -14157,13 +18766,13 @@ var ts; if (flags & 4) result |= 0; if (flags & 8) - result |= 107455; + result |= 900095; if (flags & 16) result |= 106927; if (flags & 32) result |= 899519; if (flags & 64) - result |= 792960; + result |= 792968; if (flags & 256) result |= 899327; if (flags & 128) @@ -14177,9 +18786,9 @@ var ts; if (flags & 65536) result |= 74687; if (flags & 262144) - result |= 530912; + result |= 530920; if (flags & 524288) - result |= 793056; + result |= 793064; if (flags & 8388608) result |= 8388608; return result; @@ -14200,9 +18809,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = cloneSymbolTable(symbol.members); + result.members = ts.cloneMap(symbol.members); if (symbol.exports) - result.exports = cloneSymbolTable(symbol.exports); + result.exports = ts.cloneMap(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -14222,12 +18831,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = {}; + target.members = ts.createMap(); mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = {}; + target.exports = ts.createMap(); mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -14243,28 +18852,17 @@ var ts; }); } } - function cloneSymbolTable(symbolTable) { - var result = {}; - for (var id in symbolTable) { - if (ts.hasProperty(symbolTable, id)) { - result[id] = symbolTable[id]; - } - } - return result; - } function mergeSymbolTable(target, source) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (!ts.hasProperty(target, id)) { - target[id] = source[id]; - } - else { - var symbol = target[id]; - if (!(symbol.flags & 33554432)) { - target[id] = symbol = cloneSymbol(symbol); - } - mergeSymbol(symbol, source[id]); + var targetSymbol = target[id]; + if (!targetSymbol) { + target[id] = source[id]; + } + else { + if (!(targetSymbol.flags & 33554432)) { + target[id] = targetSymbol = cloneSymbol(targetSymbol); } + mergeSymbol(targetSymbol, source[id]); } } } @@ -14286,7 +18884,7 @@ var ts; return; } mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1536) { + if (mainModule.flags & 1920) { mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } @@ -14297,13 +18895,11 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (ts.hasProperty(target, id)) { - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; - } + if (target[id]) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; } } function addDeclarationDiagnostic(id, message) { @@ -14318,23 +18914,25 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning && ts.hasProperty(symbols, name)) { + if (meaning) { var symbol = symbols[name]; - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { + if (symbol) { + ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { return symbol; } + if (symbol.flags & 8388608) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } } } } @@ -14396,7 +18994,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 145 && - (current.parent.flags & 32) === 0 && + (ts.getModifierFlags(current.parent) & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -14418,7 +19016,7 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793056 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 142 || @@ -14455,7 +19053,7 @@ var ts; } result = undefined; } - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -14472,7 +19070,7 @@ var ts; break; case 145: case 144: - if (ts.isClassLike(location.parent) && !(location.flags & 32)) { + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -14484,8 +19082,8 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { - if (lastLocation && lastLocation.flags & 32) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -14502,7 +19100,7 @@ var ts; case 140: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -14553,8 +19151,10 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14572,7 +19172,7 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule) { + if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -14582,7 +19182,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -14598,7 +19198,7 @@ var ts; error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); return true; } - if (location === container && !(location.flags & 32)) { + if (location === container && !(ts.getModifierFlags(location) & 32)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); @@ -14611,25 +19211,32 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var parentClassExpression = errorLocation; - while (parentClassExpression) { - var kind = parentClassExpression.kind; - if (kind === 69 || kind === 172) { - parentClassExpression = parentClassExpression.parent; - continue; - } - if (kind === 194) { - break; - } - return false; - } - if (!parentClassExpression) { - return false; - } - var expression = parentClassExpression.expression; - if (resolveEntityName(expression, 64, true)) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64, true)); + if (isError) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - return true; + } + return isError; + } + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 69: + case 172: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 194: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (107455 & ~1024)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + if (symbol && !(symbol.flags & 1024)) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } } return false; } @@ -14637,7 +19244,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -14675,7 +19282,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -14694,7 +19301,7 @@ var ts; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793056 | 1536)) { + if (valueSymbol.flags & (793064 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -14710,9 +19317,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536) { - var exports_1 = getExportsOfSymbol(symbol); - if (ts.hasProperty(exports_1, name)) { - return resolveSymbol(exports_1[name]); + var exportedSymbol = getExportsOfSymbol(symbol)[name]; + if (exportedSymbol) { + return resolveSymbol(exportedSymbol); } } } @@ -14728,25 +19335,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_11 = specifier.propertyName || specifier.name; - if (name_11.text) { - if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + var name_15 = specifier.propertyName || specifier.name; + if (name_15.text) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); + error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); } return symbol; } @@ -14761,10 +19371,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536); + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 | 793056 | 1536); + return resolveEntityName(node.expression, 107455 | 793064 | 1920); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -14785,7 +19395,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793056 | 1536)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); @@ -14793,6 +19403,7 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -14822,6 +19433,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -14838,24 +19450,24 @@ var ts; entityName = entityName.parent; } if (entityName.kind === 69 || entityName.parent.kind === 139) { - return resolveEntityName(entityName, 1536, false, dontResolveAlias); + return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { ts.Debug.assert(entityName.parent.kind === 229); - return resolveEntityName(entityName, 107455 | 793056 | 1536, false, dontResolveAlias); + return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); } - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias) { + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } var symbol; if (name.kind === 69) { - var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } @@ -14863,7 +19475,7 @@ var ts; else if (name.kind === 139 || name.kind === 172) { var left = name.kind === 139 ? name.left : name.expression; var right = name.kind === 139 ? name.right : name.name; - var namespace = resolveEntityName(left, 1536, ignoreErrors); + var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -14873,7 +19485,7 @@ var ts; symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); } return undefined; } @@ -14892,7 +19504,10 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; - var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } @@ -14903,14 +19518,14 @@ var ts; return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return getMergedSymbol(sourceFile.symbol); } if (moduleNotFoundError) { - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return undefined; } @@ -14921,7 +19536,14 @@ var ts; } } if (moduleNotFoundError) { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } return undefined; } @@ -14951,7 +19573,7 @@ var ts; } function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !ts.hasProperty(target, id)) { + if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -14959,7 +19581,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -14977,11 +19599,11 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = cloneSymbolTable(symbol.exports); + var symbols = ts.cloneMap(symbol.exports); var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = {}; - var lookupTable = {}; + var nestedSymbols = ts.createMap(); + var lookupTable = ts.createMap(); for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -14990,7 +19612,7 @@ var ts; } for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -15041,8 +19663,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount; typeCount++; + result.id = typeCount; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -15050,6 +19672,12 @@ var ts; type.intrinsicName = intrinsicName; return type; } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8; + type.intrinsicName = "boolean"; + return type; + } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -15064,14 +19692,12 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (ts.hasProperty(members, id)) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); } } } @@ -15089,7 +19715,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -15114,7 +19740,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1536; + return rightMeaning === 107455 ? 107455 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -15131,10 +19757,10 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(ts.lookUp(symbols, symbol.name))) { + if (isAccessible(symbols[symbol.name])) { return [symbol]; } - return ts.forEachValue(symbols, function (symbolFromSymbolTable) { + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { @@ -15161,10 +19787,10 @@ var ts; function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - if (!ts.hasProperty(symbolTable, symbol.name)) { + var symbolFromSymbolTable = symbolTable[symbol.name]; + if (!symbolFromSymbolTable) { return false; } - var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { return true; } @@ -15195,19 +19821,19 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined }; } return hasAccessibleDeclarations; @@ -15243,7 +19869,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -15253,16 +19879,18 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1) && + !(ts.getModifierFlags(anyImportSyntax) & 1) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -15278,14 +19906,14 @@ var ts; } else if (entityName.kind === 139 || entityName.kind === 172 || entityName.parent.kind === 229) { - meaning = 1536; + meaning = 1920; } else { - meaning = 793056; + meaning = 793064; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -15332,6 +19960,31 @@ var ts; ts.releaseStringWriter(writer); return result; } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144)) { + if (t.flags & (128 | 256)) { + var baseType = t.flags & 128 ? booleanType : t.baseType; + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } + } + result.push(t); + } + } + if (flags & 4096) + result.push(nullType); + if (flags & 2048) + result.push(undefinedType); + return result || types; + } function visibilityToString(flags) { if (flags === 8) { return "private"; @@ -15358,6 +20011,9 @@ var ts; node.parent.kind === 226 && ts.isExternalModuleAugmentation(node.parent.parent); } + function literalTypeToString(type) { + return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -15417,71 +20073,77 @@ var ts; parentSymbol = symbol; } writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning) { - if (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_7) { + walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else { - if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { - return; - } - if (symbol.flags & 2048 || symbol.flags & 4096) { - return; - } - appendParentTypeArgumentsAndSymbolName(symbol); + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } + else if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } } var isTypeParameter = symbol.flags & 262144; var typeFormatFlag = 128 & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning); - return; + walkSymbol(symbol, meaning, true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); } - return appendParentTypeArgumentsAndSymbolName(symbol); } function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - if (type.flags & 150995071) { + var nextFlags = flags & ~512; + if (type.flags & 16015) { writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 33554432) { + else if (type.flags & 268435456) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 4096) { - writeTypeReference(type, flags); - } - else if (type.flags & (1024 | 2048 | 128 | 512)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056, 0, flags); - } - else if (type.flags & 8192) { - writeTupleType(type); - } - else if (type.flags & 49152) { - writeUnionOrIntersectionType(type, flags); - } - else if (type.flags & 65536) { - writeAnonymousType(type, flags); + else if (type.flags & 131072) { + writeTypeReference(type, nextFlags); } else if (type.flags & 256) { - writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); + buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); + writePunctuation(writer, 21); + appendSymbolNameOnly(type.symbol, writer); + } + else if (type.flags & (32768 | 65536 | 16 | 16384)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); + } + else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); + } + else if (type.flags & 1572864) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (type.flags & 2097152) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96) { + writer.writeStringLiteral(literalTypeToString(type)); } else { writePunctuation(writer, 15); @@ -15505,7 +20167,7 @@ var ts; } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056, 0, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); } if (pos < end) { writePunctuation(writer, 25); @@ -15527,6 +20189,11 @@ var ts; writePunctuation(writer, 19); writePunctuation(writer, 20); } + else if (type.target.flags & 262144) { + writePunctuation(writer, 19); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); + writePunctuation(writer, 20); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -15534,12 +20201,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_7 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_7); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_7, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -15548,16 +20215,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } - function writeTupleType(type) { - writePunctuation(writer, 19); - writeTypeList(type.elementTypes, 24); - writePunctuation(writer, 20); - } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { writePunctuation(writer, 17); } - writeTypeList(type.types, type.flags & 16384 ? 47 : 46); + if (type.flags & 524288) { + writeTypeList(formatUnionTypes(type.types), 47); + } + else { + writeTypeList(type.types, 46); + } if (flags & 64) { writePunctuation(writer, 18); } @@ -15574,7 +20241,7 @@ var ts; else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); } else { writeKeyword(writer, 117); @@ -15594,7 +20261,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32; })); + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -15780,7 +20447,7 @@ var ts; } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingElement.kind === 193) { + if (ts.isOmittedExpression(bindingElement)) { return; } ts.Debug.assert(bindingElement.kind === 169); @@ -15928,19 +20595,19 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_8 = getDeclarationContainer(node); - if (!(ts.getCombinedNodeFlags(node) & 1) && - !(node.kind !== 229 && parent_8.kind !== 256 && ts.isInAmbientContext(parent_8))) { - return isGlobalSourceFile(parent_8); + var parent_9 = getDeclarationContainer(node); + if (!(ts.getCombinedModifierFlags(node) & 1) && + !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { + return isGlobalSourceFile(parent_9); } - return isDeclarationVisible(parent_8); + return isDeclarationVisible(parent_9); case 145: case 144: case 149: case 150: case 147: case 146: - if (node.flags & (8 | 16)) { + if (ts.getModifierFlags(node) & (8 | 16)) { return false; } case 148: @@ -15965,6 +20632,7 @@ var ts; return false; case 141: case 256: + case 228: return true; case 235: return false; @@ -15976,13 +20644,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793056 | 1536 | 8388608); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -15999,7 +20667,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -16040,7 +20708,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 1024)); + ts.Debug.assert(!!(target.flags & 32768)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -16082,7 +20750,7 @@ var ts; return type && (type.flags & 1) !== 0; } function isTypeNever(type) { - return type && (type.flags & 134217728) !== 0; + return type && (type.flags & 8192) !== 0; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); @@ -16113,25 +20781,25 @@ var ts; } if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { - return checkExpressionCached(declaration.initializer); + return checkDeclarationInitializer(declaration); } return parentType; } var type; if (pattern.kind === 167) { - var name_12 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_12)) { + var name_16 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_16)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_12); + var text = getTextOfPropertyName(name_16); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); + error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); return unknownType; } } @@ -16144,7 +20812,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -16156,10 +20824,12 @@ var ts; type = createArrayType(elementType); } } - if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { type = getTypeWithFacts(type, 131072); } - return type; + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -16189,10 +20859,10 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? addTypeKind(type, 32) : type; + return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -16224,40 +20894,44 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - var type = declaration.symbol.name === "this" - ? getContextuallyTypedThisType(func) - : getContextuallyTypedParameterType(declaration); + var type = void 0; + if (declaration.symbol.name === "this") { + var thisParameter = getContextualThisParameter(func); + type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + } + else { + type = getContextuallyTypedParameterType(declaration); + } if (type) { return addOptionality(type, declaration.questionToken && includeOptionality); } } if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), declaration.questionToken && includeOptionality); + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, declaration.questionToken && includeOptionality); } if (declaration.kind === 254) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false); + return getTypeFromBindingPattern(declaration.name, false, true); } return undefined; } - function getTypeFromBindingElement(element, includePatternInType) { + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - var type = checkExpressionCached(element.initializer); - reportErrorsFromWidening(element, type); - return getWidenedType(type); + return checkDeclarationInitializer(element); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType); + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } - function getTypeFromObjectBindingPattern(pattern, includePatternInType) { - var members = {}; + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createMap(); var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -16268,7 +20942,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -16277,27 +20951,28 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 67108864; + result.flags |= 536870912; } return result; } - function getTypeFromArrayBindingPattern(pattern, includePatternInType) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; - if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); if (includePatternInType) { - var result = createNewTupleType(elementTypes); + result = cloneTypeReference(result); result.pattern = pattern; - return result; } - return createTupleType(elementTypes); + return result; } - function getTypeFromBindingPattern(pattern, includePatternInType) { + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { return pattern.kind === 167 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType) - : getTypeFromArrayBindingPattern(pattern, includePatternInType); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration, true); @@ -16336,19 +21011,27 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } + if (declaration.flags & 1048576 && declaration.kind === 280 && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = undefined; - if (declaration.kind === 187) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - else if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - type = checkExpressionCached(declaration.parent.right); + var type = void 0; + if (declaration.kind === 187 || + declaration.kind === 172 && declaration.parent.kind === 187) { + if (declaration.flags & 1048576) { + var typeTag = ts.getJSDocTypeTag(declaration.parent); + if (typeTag && typeTag.typeExpression) { + return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + } } + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + checkExpressionCached(decl.right) : + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -16391,7 +21074,7 @@ var ts; if (!links.type) { var getter = ts.getDeclarationOfKind(symbol, 149); var setter = ts.getDeclarationOfKind(symbol, 150); - if (getter && getter.flags & 134217728) { + if (getter && getter.flags & 1048576) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -16416,7 +21099,13 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } type = anyType; } @@ -16436,13 +21125,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(65536, symbol); + var type = createObjectType(2097152, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + includeFalsyTypes(type, 2048) : type; } } return links.type; @@ -16450,7 +21139,7 @@ var ts; function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.type = getDeclaredTypeOfEnumMember(symbol); } return links.type; } @@ -16493,7 +21182,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 4096 ? type.target : type; + return type.flags & 131072 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -16553,7 +21242,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 80896 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -16565,7 +21254,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -16580,7 +21269,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -16596,25 +21285,28 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { - var isClass = type.symbol.flags & 32; - var isInterface = type.symbol.flags & 64; if (!type.resolvedBaseTypes) { - if (!isClass && !isInterface) { + if (type.flags & 262144) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 | 64)) { + if (type.symbol.flags & 32) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64) { + resolveBaseTypesOfInterface(type); + } + } + else { ts.Debug.fail("type must be class or interface"); } - if (isClass) { - resolveBaseTypesOfClass(type); - } - if (isInterface) { - resolveBaseTypesOfInterface(type); - } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 80896)) { + if (!(baseConstructorType.flags & 2588672)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -16635,7 +21327,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (1024 | 2048))) { + if (!(getTargetType(baseType).flags & (32768 | 65536))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -16668,7 +21360,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (1024 | 2048)) { + if (getTargetType(baseType).flags & (32768 | 65536)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -16693,15 +21385,15 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 222) { - if (declaration.flags & 16384) { + if (declaration.flags & 64) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isSupportedExpressionWithTypeArguments(node)) { - var baseSymbol = resolveEntityName(node.expression, 793056, true); + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -16715,20 +21407,20 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 1024 : 2048; + var kind = symbol.flags & 32 ? 32768 : 65536; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1024 || !isIndependentInterface(symbol)) { - type.flags |= 4096; + if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { + type.flags |= 131072; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = {}; + type.instantiations = ts.createMap(); type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(512 | 33554432); + type.thisType = createType(16384 | 268435456); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -16741,8 +21433,9 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var type = void 0; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var declaration = ts.getDeclarationOfKind(symbol, 279); + var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -16753,12 +21446,12 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type); + type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); } if (popTypeResolution()) { - links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (links.typeParameters) { - links.instantiations = {}; + links.typeParameters = typeParameters; + if (typeParameters) { + links.instantiations = ts.createMap(); links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -16770,19 +21463,84 @@ var ts; } return links.declaredType; } + function isLiteralEnumMember(symbol, member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + return expr.kind === 8 || + expr.kind === 185 && expr.operator === 36 && + expr.operand.kind === 8 || + expr.kind === 69 && !!symbol.exports[expr.text]; + } + function enumHasLiteralMembers(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (!isLiteralEnumMember(symbol, member)) { + return false; + } + } + } + } + return true; + } + function createEnumLiteralType(symbol, baseType, text) { + var type = createType(256); + type.symbol = symbol; + type.baseType = baseType; + type.text = text; + return type; + } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(128); - type.symbol = symbol; - links.declaredType = type; + var enumType = links.declaredType = createType(16); + enumType.symbol = symbol; + if (enumHasLiteralMembers(symbol)) { + var memberTypeList = []; + var memberTypes = ts.createMap(); + for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224) { + computeEnumMemberValues(declaration); + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberSymbol = getSymbolOfNode(member); + var value = getEnumMemberValue(member); + if (!memberTypes[value]) { + var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); + memberTypeList.push(memberType); + } + } + } + } + enumType.memberTypes = memberTypes; + if (memberTypeList.length > 1) { + enumType.flags |= 524288; + enumType.types = memberTypeList; + unionTypes[getTypeListId(memberTypeList)] = enumType; + } + } + } + return links.declaredType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.declaredType = enumType.flags & 524288 ? + enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : + enumType; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(512); + var type = createType(16384); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141).constraint) { type.constraint = noConstraintType; @@ -16806,11 +21564,14 @@ var ts; if (symbol.flags & 524288) { return getDeclaredTypeOfTypeAlias(symbol); } + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); + } if (symbol.flags & 384) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); + if (symbol.flags & 8) { + return getDeclaredTypeOfEnumMember(symbol); } if (symbol.flags & 8388608) { return getDeclaredTypeOfAlias(symbol); @@ -16881,7 +21642,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -16889,7 +21650,7 @@ var ts; return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -16899,7 +21660,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!ts.hasProperty(symbols, s.name)) { + if (!symbols[s.name]) { symbols[s.name] = s; } } @@ -16916,19 +21677,27 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 4096) { + if (type.flags & 131072) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper = identityMapper; - var members = source.symbol.members; - var callSignatures = source.declaredCallSignatures; - var constructSignatures = source.declaredConstructSignatures; - var stringIndexInfo = source.declaredStringIndexInfo; - var numberIndexInfo = source.declaredNumberIndexInfo; - if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -16938,7 +21707,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (members === source.symbol.members) { + if (source.symbol && members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -16964,7 +21733,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -16974,11 +21743,11 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasStringLiterals = hasStringLiterals; + sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -16987,7 +21756,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -17002,22 +21771,6 @@ var ts; } return result; } - function createTupleTypeMemberSymbols(memberTypes) { - var members = {}; - for (var i = 0; i < memberTypes.length; i++) { - var symbol = createSymbol(4 | 67108864, "" + i); - symbol.type = memberTypes[i]; - members[i] = symbol; - } - return members; - } - function resolveTupleTypeMembers(type) { - var arrayElementType = getUnionType(type.elementTypes, true); - var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); - var members = createTupleTypeMemberSymbols(type.elementTypes); - addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); - } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -17063,7 +21816,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; @@ -17088,7 +21841,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -17148,7 +21901,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -17162,41 +21915,36 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 4096) { + if (type.flags & 131072) { resolveTypeReferenceMembers(type); } - else if (type.flags & (1024 | 2048)) { + else if (type.flags & (32768 | 65536)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 65536) { + else if (type.flags & 2097152) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 8192) { - resolveTupleTypeMembers(type); - } - else if (type.flags & 16384) { + else if (type.flags & 524288) { resolveUnionTypeMembers(type); } - else if (type.flags & 32768) { + else if (type.flags & 1048576) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } } } @@ -17207,7 +21955,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 16384) { + if (type.flags & 524288) { break; } } @@ -17215,12 +21963,12 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 512) { + while (constraintType && constraintType.flags & 16384) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -17228,19 +21976,19 @@ var ts; return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 512) { + if (type.flags & 16384) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 258) { + if (type.flags & 34) { type = globalStringType; } - else if (type.flags & 132) { + else if (type.flags & 340) { type = globalNumberType; } - else if (type.flags & 8) { + else if (type.flags & 136) { type = globalBooleanType; } - else if (type.flags & 16777216) { + else if (type.flags & 512) { type = getGlobalESSymbolType(); } return type; @@ -17248,14 +21996,14 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; + var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 | 16))) { + if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16))) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -17267,7 +22015,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384) { + else if (containingType.flags & 524288) { return undefined; } } @@ -17280,11 +22028,20 @@ var ts; } var propTypes = []; var declarations = []; + var commonType = undefined; + var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + hasCommonType = false; + } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 | @@ -17292,47 +22049,46 @@ var ts; 268435456 | commonFlags, name); result.containingType = containingType; + result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = {}); - if (ts.hasProperty(properties, name)) { - return properties[name]; - } - var property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; + var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); + var property = properties[name]; + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; + } } return property; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol = getPropertyOfObjectType(globalFunctionType, name); - if (symbol) { - return symbol; + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 49152) { + if (type.flags & 1572864) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 130048) { + if (type.flags & 4161536) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -17342,7 +22098,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 130048) { + if (type.flags & 4161536) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -17367,13 +22123,13 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, true); } } return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -17401,7 +22157,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 134217728) { + if (node.flags & 1048576) { if (node.type && node.type.kind === 268) { return true; } @@ -17450,7 +22206,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasStringLiterals = false; + var hasLiteralTypes = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -17470,7 +22226,7 @@ var ts; parameters.push(paramSymbol); } if (param.type && param.type.kind === 166) { - hasStringLiterals = true; + hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -17496,6 +22252,9 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } + if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { + thisParameter = getContextualThisParameter(declaration); + } var classType = declaration.kind === 148 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -17506,7 +22265,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } @@ -17520,7 +22279,7 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -17591,7 +22350,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); } else { type = getReturnTypeFromBody(signature.declaration); @@ -17615,7 +22374,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 4096 && type.target === globalArrayType) { + if (type.flags & 131072 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -17635,7 +22394,7 @@ var ts; function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(65536 | 262144); + var type = createObjectType(2097152); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -17670,7 +22429,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); } return undefined; } @@ -17679,7 +22438,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { + while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -17711,24 +22470,27 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); } function getTypeListId(types) { + var result = ""; if (types) { - switch (types.length) { - case 1: - return "" + types[0].id; - case 2: - return types[0].id + "," + types[1].id; - default: - var result = ""; - for (var i = 0; i < types.length; i++) { - if (i > 0) { - result += ","; - } - result += types[i].id; - } - return result; + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; } } - return ""; + return result; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; @@ -17738,20 +22500,29 @@ var ts; result |= type.flags; } } - return result & 14680064; + return result & 234881024; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 4096 | propagatedFlags; + var flags = 131072 | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } + function cloneTypeReference(source) { + var type = createObjectType(source.flags, source.symbol); + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return type.target.typeParameters ? type.target.typeParameters.length : 0; + } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; @@ -17760,7 +22531,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); return unknownType; } - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -17777,7 +22548,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); var id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } @@ -17801,8 +22572,9 @@ var ts; case 267: return node.name; case 194: - if (ts.isSupportedExpressionWithTypeArguments(node)) { - return node.expression; + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; } } return undefined; @@ -17811,7 +22583,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -17837,14 +22609,14 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); - links.resolvedSymbol = symbol; - links.resolvedType = type; } else { - var typeNameOrExpression = node.kind === 155 ? node.typeName : - ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : - undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 + ? node.typeName + : ts.isEntityNameExpression(node.expression) + ? node.expression + : undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : @@ -17879,7 +22651,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 80896)) { + if (!(type.flags & 2588672)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -17893,7 +22665,7 @@ var ts; return getGlobalSymbol(name, 107455, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793056, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793064, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -17903,8 +22675,8 @@ var ts; return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); + var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } function createTypedPropertyDescriptorType(propertyType) { @@ -17932,47 +22704,115 @@ var ts; } return links.resolvedType; } - function createTupleType(elementTypes) { - var id = getTypeListId(elementTypes); - return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); - } - function createNewTupleType(elementTypes) { - var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, 0); - var type = createObjectType(8192 | propagatedFlags); - type.elementTypes = elementTypes; + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384); + typeParameters.push(typeParameter); + var property = createSymbol(4 | 67108864, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(262144 | 131072); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 | 268435456); + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; return type; } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); } return links.resolvedType; } - function addTypeToSet(typeSet, type, typeSetKind) { - if (type.flags & typeSetKind) { - addTypesToSet(typeSet, type.types, typeSetKind); + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } } - else if (type.flags & (1 | 32 | 64)) { - if (type.flags & 1) - typeSet.containsAny = true; - if (type.flags & 32) + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 524288) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144) { + if (flags & 2048) typeSet.containsUndefined = true; - if (type.flags & 64) + if (flags & 4096) typeSet.containsNull = true; - if (!(type.flags & 2097152)) + if (!(flags & 33554432)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(flags & 8192)) { + if (flags & 2) + typeSet.containsString = true; + if (flags & 4) + typeSet.containsNumber = true; + if (flags & 96) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } } } - function addTypesToSet(typeSet, types, typeSetKind) { + function addTypesToUnion(typeSet, types) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToSet(typeSet, type, typeSetKind); + addTypeToUnion(typeSet, type); } } + function containsIdenticalType(types, type) { + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -17986,11 +22826,24 @@ var ts; while (i > 0) { i--; if (isSubtypeOfAny(types[i], types)) { - types.splice(i, 1); + ts.orderedRemoveItemAt(types, i); } } } - function getUnionType(types, noSubtypeReduction) { + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 && types.containsString || + t.flags & 64 && types.containsNumber || + t.flags & 96 && t.flags & 16777216 && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -17998,96 +22851,132 @@ var ts; return types[0]; } var typeSet = []; - addTypesToSet(typeSet, types, 16384); + addTypesToUnion(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } - if (!noSubtypeReduction) { + if (subtypeReduction) { removeSubtypes(typeSet); } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - else if (typeSet.length === 1) { - return typeSet[0]; + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; } - var id = getTypeListId(typeSet); + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); - type = unionTypes[id] = createObjectType(16384 | propagatedFlags); - type.types = typeSet; + var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); + type = unionTypes[id] = createObjectType(524288 | propagatedFlags); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node) { + function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), true); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), false, aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getIntersectionType(types) { + function addTypeToIntersection(typeSet, type) { + if (type.flags & 1048576) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + addTypeToIntersection(typeSet, type); + } + } + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToSet(typeSet, types, 32768); + addTypesToIntersection(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); - type = intersectionTypes[id] = createObjectType(32768 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); + type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node) { + function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createObjectType(65536, node.symbol); + var type = createObjectType(2097152, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + links.resolvedType = type; } return links.resolvedType; } - function getStringLiteralTypeForText(text) { - if (ts.hasProperty(stringLiteralTypes, text)) { - return stringLiteralTypes[text]; - } - var type = stringLiteralTypes[text] = createType(256); + function createLiteralType(flags, text) { + var type = createType(flags); type.text = text; return type; } - function getTypeFromStringLiteralTypeNode(node) { + function getFreshTypeOfLiteralType(type) { + if (type.flags & 96 && !(type.flags & 16777216)) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags | 16777216, type.text); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 && type.flags & 16777216 ? type.regularType : type; + } + function getLiteralTypeForText(flags, text) { + var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; + return map[text] || (map[text] = createLiteralType(flags, text)); + } + function getTypeFromLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); } return links.resolvedType; } @@ -18102,7 +22991,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); + var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -18111,8 +23000,8 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 222)) { - if (!(container.flags & 32) && - (container.kind !== 148 || ts.isNodeDescendentOf(node, container.body))) { + if (!(ts.getModifierFlags(container) & 32) && + (container.kind !== 148 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -18126,7 +23015,10 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNodeNoAlias(type) { + return getTypeFromTypeNode(type, undefined, undefined); + } + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117: case 258: @@ -18148,11 +23040,19 @@ var ts; return nullType; case 127: return neverType; + case 283: + return nullType; + case 284: + return undefinedType; + case 285: + return neverType; case 165: case 97: return getTypeFromThisTypeNode(node); case 166: - return getTypeFromStringLiteralTypeNode(node); + return getTypeFromLiteralTypeNode(node); + case 282: + return getTypeFromLiteralTypeNode(node.literal); case 155: case 267: return getTypeFromTypeReference(node); @@ -18169,9 +23069,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162: case 261: - return getTypeFromUnionTypeNode(node); + return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); case 163: - return getTypeFromIntersectionTypeNode(node); + return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); case 164: case 263: case 264: @@ -18179,13 +23079,14 @@ var ts; case 272: case 268: return getTypeFromTypeNode(node.type); + case 265: + return getTypeFromTypeNode(node.literal); case 156: case 157: case 159: case 281: case 269: - case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -18231,6 +23132,7 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; + mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -18239,7 +23141,7 @@ var ts; function getInferenceMapper(context) { if (!context.mapper) { var mapper = function (t) { - var typeParameters = context.typeParameters; + var typeParameters = context.signature.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (t === typeParameters[i]) { context.inferences[i].isFixed = true; @@ -18248,7 +23150,7 @@ var ts; } return t; }; - mapper.mappedTypes = context.typeParameters; + mapper.mappedTypes = context.signature.typeParameters; mapper.context = context; context.mapper = mapper; } @@ -18263,7 +23165,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(512); + var result = createType(16384); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -18298,7 +23200,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -18329,9 +23231,11 @@ var ts; else { mapper.instantiations = []; } - var result = createObjectType(65536 | 131072, type.symbol); + var result = createObjectType(2097152 | 4194304, type.symbol); result.target = type; result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -18383,26 +23287,23 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 512) { + if (type.flags & 16384) { return mapper(type); } - if (type.flags & 65536) { + if (type.flags & 2097152) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 131072 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 4096) { + if (type.flags & 131072) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 8192) { - return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); + if (type.flags & 524288 && !(type.flags & 8190)) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); } - if (type.flags & 16384) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), true); - } - if (type.flags & 32768) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); + if (type.flags & 1048576) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); } } return type; @@ -18445,10 +23346,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(65536, type.symbol); + var result = createObjectType(2097152, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -18459,22 +23360,25 @@ var ts; return type; } function isTypeIdenticalTo(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined); + return isTypeRelatedTo(source, target, identityRelation); } function compareTypesIdentical(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; + return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; } function compareTypesAssignable(source, target) { - return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; + return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; } function isTypeSubtypeOf(source, target) { - return checkTypeSubtypeOf(source, target, undefined); + return isTypeRelatedTo(source, target, subtypeRelation); } function isTypeAssignableTo(source, target) { - return checkTypeAssignableTo(source, target, undefined); + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeInstanceOf(source, target) { + return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); } function isTypeComparableTo(source, target) { - return checkTypeComparableTo(source, target, undefined); + return isTypeRelatedTo(source, target, comparableRelation); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -18587,8 +23491,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) - || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { return isSignatureAssignableTo(erasedSource, erasedTarget, true); } return false; @@ -18614,6 +23518,94 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + var id = source.id + "," + target.id; + if (enumRelation[id] !== undefined) { + return enumRelation[id]; + } + if (source.symbol.name !== target.symbol.name || + !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || + (source.flags & 524288) !== (target.flags & 524288)) { + return enumRelation[id] = false; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + } + return enumRelation[id] = false; + } + } + } + return enumRelation[id] = true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + if (target.flags & 8192) + return false; + if (target.flags & 1 || source.flags & 8192) + return true; + if (source.flags & 34 && target.flags & 2) + return true; + if (source.flags & 340 && target.flags & 4) + return true; + if (source.flags & 136 && target.flags & 8) + return true; + if (source.flags & 256 && target.flags & 16 && source.baseType === target) + return true; + if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + return true; + if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + return true; + if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1) + return true; + if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + return true; + if (source.flags & 256 && + target.flags & 256 && + source.text === target.text && + isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + return true; + } + if (source.flags & 256 && + target.flags & 16 && + isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { + return true; + } + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 && source.flags & 16777216) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 16777216) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 2588672 && target.flags & 2588672) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation[id]; + if (related !== undefined) { + return related === 1; + } + } + if (source.flags & 4177920 || target.flags & 4177920) { + return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + } + return false; + } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; @@ -18652,85 +23644,73 @@ var ts; } reportError(message, sourceType, targetType); } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType() === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; + if (source.flags & 96 && source.flags & 16777216) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 16777216) { + target = target.regularType; + } if (source === target) return -1; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (!(target.flags & 134217728)) { - if (target.flags & 1 || source.flags & 134217728) - return -1; - if (source.flags & 32) { - if (!strictNullChecks || target.flags & (32 | 16)) - return -1; - } - if (source.flags & 64) { - if (!strictNullChecks || target.flags & 64) - return -1; - } - if (source.flags & 128 && target === numberType) - return -1; - if (source.flags & 128 && target.flags & 128) { - if (result = enumRelatedTo(source, target, reportErrors)) { - return result; - } - } - if (source.flags & 256 && target === stringType) - return -1; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return -1; - if (source === numberType && target.flags & 128) - return -1; - } - if (source.flags & 8 && target.flags & 8) { - return -1; - } - } - if (source.flags & 1048576) { + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1; + if (source.flags & 8388608 && source.flags & 16777216) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 49152) { + if (target.flags & 1572864) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 16384) { + if (source.flags & 524288) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors); + result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } else { - result = eachTypeRelatedToType(source, target, reportErrors); + result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } if (result) { return result; } } - else if (target.flags & 32768) { + else if (target.flags & 1048576) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; } } else { - if (source.flags & 32768) { + if (source.flags & 1048576) { if (result = someTypeRelatedToType(source, target, false)) { return result; } } - if (target.flags & 16384) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726))) { + if (target.flags & 524288) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { return result; } } } - if (source.flags & 512) { + if (source.flags & 16384) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1) { constraint = emptyObjectType; @@ -18743,14 +23723,14 @@ var ts; } } else { - if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); + if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -18758,22 +23738,28 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 2588672 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } reportRelationError(headMessage, source, target); } return 0; } function isIdenticalTo(source, target) { var result; - if (source.flags & 80896 && target.flags & 80896) { - if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + if (source.flags & 2588672 && target.flags & 2588672) { + if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 16384 && target.flags & 16384 || - source.flags & 32768 && target.flags & 32768) { + if (source.flags & 524288 && target.flags & 524288 || + source.flags & 1048576 && target.flags & 1048576) { if (result = eachTypeRelatedToSomeType(source, target, false)) { if (result &= eachTypeRelatedToSomeType(target, source, false)) { return result; @@ -18783,7 +23769,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -18792,7 +23778,7 @@ var ts; return true; } } - else if (type.flags & 49152) { + else if (type.flags & 1572864) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -18810,7 +23796,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { + if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -18840,14 +23826,10 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - var len = targetTypes.length; - while (len >= 2 && targetTypes[len - 1].flags & 96) { - var related = isRelatedTo(source, targetTypes[len - 1], false); - if (related) { - return related; - } - len--; + if (target.flags & 524288 && containsType(targetTypes, source)) { + return -1; } + var len = targetTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -18871,14 +23853,10 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - var len = sourceTypes.length; - while (len >= 2 && sourceTypes[len - 1].flags & 96) { - var related = isRelatedTo(sourceTypes[len - 1], target, false); - if (related) { - return related; - } - len--; + if (source.flags & 524288 && containsType(sourceTypes, target)) { + return -1; } + var len = sourceTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -18950,7 +23928,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -18982,7 +23960,7 @@ var ts; if (result) { var maybeCache = maybeStack[depth]; var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyMap(maybeCache, destinationCache); + ts.copyProperties(maybeCache, destinationCache); } else { relation[id] = reportErrors ? 3 : 2; @@ -18995,9 +23973,9 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); - for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { - var targetProp = properties_1[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -19009,8 +23987,8 @@ var ts; } } else if (!(targetProp.flags & 134217728)) { - var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -19061,7 +24039,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 80896 && target.flags & 80896)) { + if (!(source.flags & 2588672 && target.flags & 2588672)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -19174,7 +24152,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 8190))) { return -1; } var sourceInfo = getIndexInfoOfType(source, kind) || @@ -19211,33 +24189,12 @@ var ts; } return 0; } - function enumRelatedTo(source, target, reportErrors) { - if (source.symbol.name !== target.symbol.name || - source.symbol.flags & 128 || - target.symbol.flags & 128) { - return 0; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); - } - return 0; - } - } - } - return -1; - } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = sourceSignature.declaration.flags & (8 | 16); - var targetAccessibility = targetSignature.declaration.flags & (8 | 16); + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; if (targetAccessibility === 8) { return true; } @@ -19254,11 +24211,11 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 65536) { + if (type.flags & 2097152) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && declaration.flags & 128) { + if (declaration && ts.getModifierFlags(declaration) & 128) { return true; } } @@ -19266,12 +24223,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (4096 | 131072) && depth >= 5) { + if (type.flags & (131072 | 4194304) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (4096 | 131072) && t.symbol === symbol) { + if (t.flags & (131072 | 4194304) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -19287,8 +24244,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 | 16); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 | 16); + var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -19313,8 +24270,10 @@ var ts; source.hasRestParameter === target.hasRestParameter) { return true; } - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || - source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -19364,31 +24323,40 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } - function getCombinedFlagsOfTypes(types) { - var flags = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - flags |= t.flags; + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } } - return flags; + return true; + } + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } function getCommonSupertype(types) { if (!strictNullChecks) { - return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); if (!primaryTypes.length) { - return getUnionType(types); + return getUnionType(types, true); } - var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96); + var supertype = getSupertypeOrUnion(primaryTypes); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -19418,44 +24386,80 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 4096 && type.target === globalArrayType; + return type.flags & 131072 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 96) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralUnionType(type) { - return type.flags & 256 ? true : - type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : - false; + function isUnitType(type) { + return (type.flags & (480 | 2048 | 4096)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 ? true : + type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 256 ? type.baseType : + type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 32 && type.flags & 16777216 ? stringType : + type.flags & 64 && type.flags & 16777216 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 256 ? type.baseType : + type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type; } function isTupleType(type) { - return !!(type.flags & 8192); + return !!(type.flags & 131072 && type.target.flags & 262144); } - function getCombinedTypeFlags(type) { - return type.flags & 16384 ? getCombinedFlagsOfTypes(type.types) : type.flags; + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; } - function addTypeKind(type, kind) { - if ((getCombinedTypeFlags(type) & kind) === kind) { + function getFalsyFlags(type) { + return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : + type.flags & 32 ? type.text === "" ? 32 : 0 : + type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 128 ? type === falseType ? 128 : 0 : + type.flags & 7406; + } + function includeFalsyTypes(type, flags) { + if ((getFalsyFlags(type) & flags) === flags) { return type; } var types = [type]; - if (kind & 2) - types.push(stringType); - if (kind & 4) - types.push(numberType); - if (kind & 8) - types.push(booleanType); - if (kind & 16) + if (flags & 34) + types.push(emptyStringType); + if (flags & 340) + types.push(zeroType); + if (flags & 136) + types.push(falseType); + if (flags & 1024) types.push(voidType); - if (kind & 32) + if (flags & 2048) types.push(undefinedType); - if (kind & 64) + if (flags & 4096) types.push(nullType); - return getUnionType(types); + return getUnionType(types, true); + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 7392 ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : + type; } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; @@ -19477,7 +24481,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = {}; + var members = ts.createMap(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -19488,7 +24492,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576)) { + if (!(type.flags & 8388608 && type.flags & 16777216)) { return type; } var regularType = type.regularType; @@ -19498,7 +24502,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; + regularNew.flags = resolved.flags & ~16777216; type.regularType = regularNew; return regularNew; } @@ -19512,31 +24516,28 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 96 ? type : getWidenedType(type); + return type.flags & 6144 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 96) { + if (type.flags & 100663296) { + if (type.flags & 6144) { return anyType; } - if (type.flags & 524288) { + if (type.flags & 8388608) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 16384) { - return getUnionType(ts.map(type.types, getWidenedConstituentType), true); + if (type.flags & 524288) { + return getUnionType(ts.map(type.types, getWidenedConstituentType)); } - if (isArrayType(type)) { - return createArrayType(getWidenedType(type.typeArguments[0])); - } - if (isTupleType(type)) { - return createTupleType(ts.map(type.elementTypes, getWidenedType)); + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 16384) { + if (type.flags & 524288) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -19544,22 +24545,19 @@ var ts; } } } - if (isArrayType(type)) { - return reportWideningErrorsInType(type.typeArguments[0]); - } - if (isTupleType(type)) { - for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 524288) { + if (type.flags & 8388608) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { + if (t.flags & 33554432) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -19604,7 +24602,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -19630,29 +24628,46 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = ts.map(typeParameters, createTypeInferencesObject); + function createInferenceContext(signature, inferUnionTypes) { + var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); return { - typeParameters: typeParameters, + signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length) }; } function createTypeInferencesObject() { return { primary: undefined, secondary: undefined, + topLevel: true, isFixed: false }; } - function inferTypes(context, source, target) { + function couldContainTypeParameters(type) { + return !!(type.flags & 16384 || + type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || + type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || + type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); + } + function couldUnionOrIntersectionContainTypeParameters(type) { + if (type.couldContainTypeParameters === undefined) { + type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + } + return type.couldContainTypeParameters; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 1572864 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypes(context, originalSource, originalTarget) { + var typeParameters = context.signature.typeParameters; var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; - inferFromTypes(source, target); + var visited = ts.createMap(); + inferFromTypes(originalSource, originalTarget); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { if (source === sourceStack[i] && target === targetStack[i]) { @@ -19662,26 +24677,41 @@ var ts; return false; } function inferFromTypes(source, target) { - if (source.flags & 16384 && target.flags & 16384 || - source.flags & 32768 && target.flags & 32768) { + if (!couldContainTypeParameters(target)) { + return; + } + if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || + source.flags & 1048576 && target.flags & 1048576) { + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } var matchingTypes = void 0; - for (var _i = 0, _a = target.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (typeIdenticalToSomeType(t, source.types)) { + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } + else if (t.flags & (64 | 32)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } } if (matchingTypes) { source = removeTypesFromUnionOrIntersection(source, matchingTypes); target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 512) { - if (source.flags & 8388608) { + if (target.flags & 16384) { + if (source.flags & 134217728) { return; } - var typeParameters = context.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { var inferences = context.inferences[i]; @@ -19692,12 +24722,15 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } + if (!isTypeParameterAtTopLevel(originalTarget, target)) { + inferences.topLevel = false; + } } return; } } } - else if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -19705,20 +24738,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { - var sourceTypes = source.elementTypes; - var targetTypes = target.elementTypes; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 49152) { + else if (target.flags & 1572864) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; - for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { - var t = targetTypes_2[_b]; - if (t.flags & 512 && ts.contains(context.typeParameters, t)) { + for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { + var t = targetTypes_2[_d]; + if (t.flags & 16384 && ts.contains(typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -19732,18 +24758,16 @@ var ts; inferiority--; } } - else if (source.flags & 49152) { + else if (source.flags & 1572864) { var sourceTypes = source.types; - for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { - var sourceType = sourceTypes_3[_c]; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || - target.flags & 8192 || - target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (source.flags & 2588672) { if (isInProcess(source, target)) { return; } @@ -19751,7 +24775,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -19772,8 +24796,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -19790,8 +24814,11 @@ var ts; inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } + function inferFromParameterTypes(source, target) { + return inferFromTypes(source, target); + } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromParameterTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -19820,8 +24847,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -19836,19 +24863,28 @@ var ts; reducedTypes.push(t); } } - return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); + return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190); + } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; var inferenceSucceeded; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var signature = context.signature; + var widenLiteralTypes = context.inferences[index].topLevel && + !hasPrimitiveConstraint(signature.typeParameters[index]) && + (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); + var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -19858,7 +24894,7 @@ var ts; } context.inferredTypes[index] = inferredType; if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -19914,10 +24950,6 @@ var ts; } return undefined; } - function isNullOrUndefinedLiteral(node) { - return node.kind === 93 || - node.kind === 69 && getResolvedSymbol(node) === undefinedSymbol; - } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69: @@ -19929,16 +24961,17 @@ var ts; return undefined; } function isMatchingReference(source, target) { - if (source.kind === target.kind) { - switch (source.kind) { - case 69: - return getResolvedSymbol(source) === getResolvedSymbol(target); - case 97: - return true; - case 172: - return source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } + switch (source.kind) { + case 69: + return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 218 || target.kind === 169) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 97: + return target.kind === 97; + case 172: + return target.kind === 172 && + source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); } return false; } @@ -19951,6 +24984,40 @@ var ts; } return false; } + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 172 && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 69) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 172) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.text); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 524288) { + var prop = getPropertyOfType(type, name); + if (!prop) { + var filteredType = getTypeWithFacts(type, 4194304); + if (filteredType !== type && filteredType.flags & 524288) { + prop = getPropertyOfType(filteredType, name); + } + } + if (prop && prop.flags & 268435456) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !prop.hasCommonType && + isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -19977,7 +25044,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 16384)) { + if (!(source.flags & 524288)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -19989,70 +25056,82 @@ var ts; return false; } function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType && declaredType.flags & 16384) { - var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedTypes.length) { - return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); + if (declaredType !== assignedType) { + if (assignedType.flags & 8192) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192)) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); + } function getTypeFacts(type) { var flags = type.flags; - if (flags & 258) { + if (flags & 2) { return strictNullChecks ? 4079361 : 4194049; } - if (flags & 132) { + if (flags & 32) { + return strictNullChecks ? + type.text === "" ? 3030785 : 1982209 : + type.text === "" ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } + if (flags & (64 | 256)) { + var isZero = type.text === "0"; + return strictNullChecks ? + isZero ? 3030658 : 1982082 : + isZero ? 3145346 : 4193922; + } if (flags & 8) { return strictNullChecks ? 4078980 : 4193668; } - if (flags & 80896) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? - strictNullChecks ? 1970144 : 4181984 : - strictNullChecks ? 1972176 : 4184016; + if (flags & 136) { + return strictNullChecks ? + type === falseType ? 3030404 : 1981828 : + type === falseType ? 3145092 : 4193668; } - if (flags & (16 | 32)) { + if (flags & 2588672) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 : 8376288 : + strictNullChecks ? 6166480 : 8378320; + } + if (flags & (1024 | 2048)) { return 2457472; } - if (flags & 64) { + if (flags & 4096) { return 2340752; } - if (flags & 16777216) { + if (flags & 512) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 512) { + if (flags & 16384) { var constraint = getConstraintOfTypeParameter(type); - return constraint ? getTypeFacts(constraint) : 4194303; + return getTypeFacts(constraint || emptyObjectType); } - if (flags & 32768) { - return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0); + if (flags & 1572864) { + return getTypeFactsOfTypes(type.types); } - return 4194303; + return 8388607; } function getTypeWithFacts(type, include) { - if (!(type.flags & 16384)) { - return getTypeFacts(type) & include ? type : neverType; - } - var firstType; - var types; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (getTypeFacts(t) & include) { - if (!firstType) { - firstType = t; - } - else { - if (!types) { - types = [firstType]; - } - types.push(t); - } - } - } - return firstType ? types ? getUnionType(types, true) : firstType : neverType; + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -20146,53 +25225,88 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getReferenceFromExpression(node) { + function getInitialOrAssignedType(node) { + return node.kind === 218 || node.kind === 169 ? + getInitialType(node) : + getAssignedType(node); + } + function getReferenceCandidate(node) { switch (node.kind) { case 178: - return getReferenceFromExpression(node.expression); + return getReferenceCandidate(node.expression); case 187: switch (node.operatorToken.kind) { case 56: - return getReferenceFromExpression(node.left); + return getReferenceCandidate(node.left); case 24: - return getReferenceFromExpression(node.right); + return getReferenceCandidate(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249) { - var expr = clause.expression; - return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; } - return undefined; + return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 524288) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + return true; + } + return containsType(target.types, source); } function filterType(type, f) { - return type.flags & 16384 ? - getUnionType(ts.filter(type.types, f)) : - f(type) ? type : neverType; + if (type.flags & 524288) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32); + var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; - var result = getTypeAtFlowNode(reference.flowNode); + var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288) === neverType) { + if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288).flags & 8192) { return declaredType; } return result; @@ -20230,7 +25344,7 @@ var ts; } else if (flow.flags & 2) { var container = flow.container; - if (container && includeOuterFunctions) { + if (container && container !== flowContainer && reference.kind !== 172) { flow = container.flowNode; continue; } @@ -20249,16 +25363,10 @@ var ts; } function getTypeAtFlowAssignment(flow) { var node = flow.node; - if ((node.kind === 218 || node.kind === 169) && - reference.kind === 69 && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { - return declaredType.flags & 16384 ? - getAssignmentReducedType(declaredType, getInitialType(node)) : - declaredType; - } if (isMatchingReference(reference, node)) { - return declaredType.flags & 16384 ? - getAssignmentReducedType(declaredType, getAssignedType(node)) : + var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; + return declaredType.flags & 524288 && !isIncrementOrDecrement ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -20267,37 +25375,55 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - if (type !== neverType) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (!(type.flags & 8192)) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { - type = narrowType(declaredType, flow.expression, assumeTrue); + if (type.flags & 8192 && isIncomplete(flowType)) { + type = silentNeverType; } } - return type; + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtSwitchClause(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) { return type; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } } - return getUnionType(antecedentTypes); + return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); if (!key) { key = getFlowCacheKey(reference); } @@ -20306,32 +25432,66 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return getUnionType(flowLoopTypes[i]); + return createFlowType(getUnionType(flowLoopTypes[i]), true); } } var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); if (cache[key]) { return cache[key]; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } if (type === declaredType) { break; } } - return cache[key] = getUnionType(antecedentTypes); + var result = getUnionType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, true); + } + return cache[key] = result; + } + function isMatchingReferenceDiscriminant(expr) { + return expr.kind === 172 && + declaredType.flags & 524288 && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(declaredType, expr.name.text); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152) : type; + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + } + if (isMatchingReferenceDiscriminant(expr)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -20341,26 +25501,29 @@ var ts; case 31: case 32: case 33: - var left = expr.left; - var operator = expr.operatorToken.kind; - var right = expr.right; - if (isNullOrUndefinedLiteral(right)) { - return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 182 && right_1.kind === 9) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (isNullOrUndefinedLiteral(left)) { - return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + if (right_1.kind === 182 && left_1.kind === 9) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (left.kind === 182 && right.kind === 9) { - return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } - if (right.kind === 182 && left.kind === 9) { - return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } - if (left.kind === 172) { - return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + if (isMatchingReferenceDiscriminant(left_1)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (right.kind === 172) { - return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); + if (isMatchingReferenceDiscriminant(right_1)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; } break; case 91: @@ -20370,23 +25533,41 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1) { + return type; + } if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { + var valueType = checkExpression(value); + if (valueType.flags & 6144) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 30 || operator === 31; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + value.kind === 93 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); + } + if (type.flags & 2589191) { return type; } - var doubleEquals = operator === 30 || operator === 31; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - literal.kind === 93 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 ? type : narrowedType; + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceFromExpression(typeOfExpr.expression); + var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (containsMatchingReference(reference, target)) { return declaredType; @@ -20396,76 +25577,40 @@ var ts; if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, literal.text); + if (assumeTrue && !(type.flags & 524288)) { + var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, literal.text) || 64 : - ts.getProperty(typeofNEFacts, literal.text) || 8192; + typeofEQFacts[literal.text] || 64 : + typeofNEFacts[literal.text] || 8192; return getTypeWithFacts(type, facts); } - function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { - if (!isMatchingReference(reference, propAccess.expression)) { - return type; - } - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } - var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); - if (!isStringLiteralUnionType(discriminantType)) { - return type; - } - if (operator === 31 || operator === 33) { - assumeTrue = !assumeTrue; - } - if (assumeTrue) { - return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); - } - if (discriminantType.flags & 256) { - return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); - } - return type; - } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - if (!isMatchingReference(reference, switchStatement.expression.expression)) { - return type; - } - var propName = switchStatement.expression.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); - var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; - var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; - var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); - return caseType ? getUnionType([caseType, defaultType]) : defaultType; + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left); + var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (containsMatchingReference(reference, left)) { return declaredType; } return type; } - if (isTypeAny(type)) { - return type; - } var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; @@ -20478,12 +25623,15 @@ var ts; targetType = prototypePropertyType; } } + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 2048) { + if (rightType.flags & 65536) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 65536) { + else if (rightType.flags & 2097152) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -20497,23 +25645,22 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return type.flags & 16384 ? - getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : - type; + return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); } - if (type.flags & 16384) { - var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); - if (assignableConstituents.length) { - return getUnionType(assignableConstituents); + if (type.flags & 524288) { + var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (!(assignableType.flags & 8192)) { + return assignableType; } } - var targetType = type.flags & 512 ? getApparentType(type) : type; - return isTypeAssignableTo(candidate, targetType) ? candidate : + var targetType = type.flags & 16384 ? getApparentType(type) : type; + return isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : - getIntersectionType([type, candidate]); + isTypeAssignableTo(candidate, targetType) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (type.flags & 1 || !hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -20521,6 +25668,9 @@ var ts; if (!predicate) { return type; } + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -20591,31 +25741,62 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 256 || node.kind === 145) { + if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 226 || + node.kind === 256 || + node.kind === 145) { return node; } } } - function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { - var declarationContainer = getControlFlowContainer(declaration); - var container = getControlFlowContainer(reference); - while (container !== declarationContainer && - (container.kind === 179 || container.kind === 180) && - (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { - container = getControlFlowContainer(container); + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304)) { + links.flags |= 4194304; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + while (true) { + node = node.parent; + if (!node) { + return false; + } + if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304) { + return true; + } + } + } + function markParameterAssignments(node) { + if (node.kind === 69) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); } - return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 180) { - if (languageVersion < 2) { + if (languageVersion < 2) { + if (container.kind === 180) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } + else if (ts.hasModifier(container, 256)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } } - if (node.flags & 33554432) { + if (node.flags & 262144) { getNodeLinks(container).flags |= 8192; } } @@ -20623,34 +25804,56 @@ var ts; markAliasSymbolAsReferenced(symbol); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (languageVersion === 2 - && localOrExportSymbol.flags & 32 - && localOrExportSymbol.valueDeclaration.kind === 221 - && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { - getNodeLinks(container).flags |= 524288; - getNodeLinks(node).flags |= 1048576; - break; + if (localOrExportSymbol.flags & 32) { + var declaration_1 = localOrExportSymbol.valueDeclaration; + if (languageVersion === 2 + && declaration_1.kind === 221 + && ts.nodeIsDecorated(declaration_1)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration_1 && container.name !== node) { + getNodeLinks(declaration_1).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration_1.kind === 192) { + var container = ts.getThisContainer(node, false); + while (container !== undefined) { + if (container.parent === declaration_1) { + if (container.kind === 145 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration_1).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + } + break; + } + container = ts.getThisContainer(container, false); } - container = ts.getContainingClass(container); } } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node)) { + var declaration = localOrExportSymbol.valueDeclaration; + if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { return type; } - var declaration = localOrExportSymbol.valueDeclaration; - var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || !declaration || - ts.getRootDeclaration(declaration).kind === 142 || ts.isInAmbientContext(declaration) || - !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); - if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32) && getCombinedTypeFlags(flowType) & 32) { + var isParameter = ts.getRootDeclaration(declaration).kind === 142; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + while (flowContainer !== declarationContainer && + (flowContainer.kind === 179 || flowContainer.kind === 180) && + (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || + isOuterVariable || ts.isInAmbientContext(declaration); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); + if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -20788,7 +25991,7 @@ var ts; break; case 145: case 144: - if (container.flags & 32) { + if (ts.getModifierFlags(container) & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -20813,10 +26016,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -20824,8 +26023,8 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - var type = container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, true, true); + var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type, true, undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -20886,15 +26085,15 @@ var ts; } return unknownType; } - if ((container.flags & 32) || isCallExpression) { + if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } else { nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 147 && container.flags & 256) { - if (ts.isSuperPropertyOrElementAccess(node.parent) && ts.isAssignmentTarget(node.parent)) { + if (container.kind === 147 && ts.getModifierFlags(container) & 256) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } else { @@ -20938,7 +26137,7 @@ var ts; } else { if (ts.isClassLike(container.parent) || container.parent.kind === 171) { - if (container.flags & 32) { + if (ts.getModifierFlags(container) & 32) { return container.kind === 147 || container.kind === 146 || container.kind === 149 || @@ -20958,11 +26157,11 @@ var ts; return false; } } - function getContextuallyTypedThisType(func) { + function getContextualThisParameter(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return getThisTypeOfSignature(contextualSignature); + return contextualSignature.thisParameter; } } return undefined; @@ -20977,14 +26176,14 @@ var ts; if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getTypeOfExpression(iife.arguments[i])); + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } return createArrayType(getUnionType(restTypes)); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; links.resolvedSignature = anySignature; - var type = checkExpression(iife.arguments[indexOfParameter]); + var type = getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])); links.resolvedSignature = cached; return type; } @@ -21019,15 +26218,15 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true); + return getTypeFromBindingPattern(declaration.name, true, false); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_13 = declaration.propertyName || declaration.name; + var name_17 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_13)) { - var text = getTextOfPropertyName(name_13); + !ts.isBindingPattern(name_17)) { + var text = getTextOfPropertyName(name_17); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -21102,6 +26301,9 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 && operator <= 68) { + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + return undefined; + } if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); } @@ -21121,14 +26323,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 16384)) { + if (!(type.flags & 524288)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -21146,7 +26348,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 130048 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -21154,7 +26356,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -21242,6 +26444,7 @@ var ts; case 187: return getContextualTypeForBinaryOperand(node); case 253: + case 254: return getContextualTypeForObjectLiteralElement(parent); case 170: return getContextualTypeForElementExpression(node); @@ -21288,13 +26491,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 16384)) { + if (!(type.flags & 524288)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -21343,14 +26546,14 @@ var ts; } } else { - var type = checkExpression(e, contextualMapper); + var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 191; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -21362,7 +26565,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.elementTypes[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { if (patternElement.kind !== 193) { @@ -21377,17 +26580,22 @@ var ts; } } } - return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, true) : + strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } function isNumericLiteralName(name) { return (+name).toString() === name; } @@ -21395,7 +26603,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 16777216)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -21411,13 +26619,13 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = {}; + var propertiesTable = ts.createMap(); var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -21441,7 +26649,7 @@ var ts; } else { ts.Debug.assert(memberDecl.kind === 254); - type = checkExpression(memberDecl.name, contextualMapper); + type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); @@ -21455,7 +26663,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -21493,7 +26701,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!ts.hasProperty(propertiesTable, prop.name)) { + if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -21505,8 +26713,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -21560,9 +26768,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var indexerType = getIndexTypeOfType(elementAttributesType, 0); - if (indexerType) { - correspondingPropType = indexerType; + var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); + if (attributeType) { + correspondingPropType = attributeType; } else { if (!correspondingPropType) { @@ -21635,7 +26843,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 16384)); + ts.Debug.assert(!(valueType.flags & 524288)); if (isTypeAny(valueType)) { return anyType; } @@ -21647,11 +26855,11 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature)); + return getUnionType(signatures.map(getReturnTypeOfSignature), true); } function getJsxElementPropertiesName() { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064); var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -21674,16 +26882,16 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 16384) { + if (elemType.flags & 524288) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - })); + }), true); } if (elemType.flags & 2) { return anyType; } - else if (elemType.flags & 256) { + else if (elemType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elemType.text; @@ -21736,7 +26944,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 16384) { + else if (attributesType.flags & 524288) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -21819,7 +27027,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = {}; + var nameTable = ts.createMap(); var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { if (node.attributes[i].kind === 246) { @@ -21837,7 +27045,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912) && - nameTable[targetProperties[i].name] === undefined) { + !nameTable[targetProperties[i].name]) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -21854,11 +27062,14 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 145; } - function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + function getDeclarationModifierFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function checkClassPropertyAccess(node, left, type, prop) { - var flags = getDeclarationFlagsFromSymbol(prop); + var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 172 || node.kind === 218 ? node.name : @@ -21873,7 +27084,7 @@ var ts; return false; } } - if (!(flags & (8 | 16))) { + if (!(flags & 24)) { return true; } if (flags & 8) { @@ -21898,10 +27109,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 33554432) { + if (type.flags & 268435456) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (1024 | 2048) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -21910,9 +27121,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getCombinedTypeFlags(type) & 96; + var kind = getFalsyFlags(type) & 6144; if (kind) { - error(node, kind & 32 ? kind & 64 ? + error(node, kind & 2048 ? kind & 4096 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -21929,23 +27140,23 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); - if (isTypeAny(type)) { + if (isTypeAny(type) || type === silentNeverType) { return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 512 && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); + reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); } return unknownType; } if (noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && (prop.valueDeclaration.flags & 8)) { + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { if (prop.flags & 16777216) { getSymbolLinks(prop).target.isReferenced = true; } @@ -21960,10 +27171,24 @@ var ts; var propType = getTypeOfSymbol(prop); if (node.kind !== 172 || ts.isAssignmentTarget(node) || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 16384)) { + !(prop.flags & 8192 && propType.flags & 524288)) { return propType; } - return getFlowTypeOfReference(node, propType, true, false); + return getFlowTypeOfReference(node, propType, true, undefined); + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 524288 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -22031,8 +27256,8 @@ var ts; } var objectType = getApparentType(checkNonNullExpression(node.expression)); var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; - if (objectType === unknownType) { - return unknownType; + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; } var isConstEnum = isConstEnumObjectType(objectType); if (isConstEnum && @@ -22041,21 +27266,22 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_14 !== undefined) { - var prop = getPropertyOfType(objectType, name_14); + var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_18 !== undefined) { + var prop = getPropertyOfType(objectType, name_18); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol)); return unknownType; } } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + var allowedNullableFlags = strictNullChecks ? 0 : 6144; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -22100,7 +27326,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 16777216) === 0) { + if ((expressionType.flags & 512) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -22149,22 +27375,22 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_9 = signature.declaration && signature.declaration.parent; + var parent_10 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_9 === lastParent) { + if (lastParent && parent_10 === lastParent) { index++; } else { - lastParent = parent_9; + lastParent = parent_10; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_9; + lastParent = parent_10; } lastSymbol = symbol; - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -22238,7 +27464,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -22248,7 +27474,7 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature.typeParameters, true); + var context = createInferenceContext(signature, true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { inferTypes(context, instantiateType(source, contextualMapper), target); }); @@ -22338,9 +27564,7 @@ var ts; var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { - argType = arg.kind === 9 && !reportErrors - ? getStringLiteralTypeForText(arg.text) - : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { @@ -22444,10 +27668,10 @@ var ts; case 69: case 8: case 9: - return getStringLiteralTypeForText(element.name.text); + return getLiteralTypeForText(32, element.name.text); case 140: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 16777216)) { + if (isTypeOfKind(nameType, 512)) { return nameType; } else { @@ -22573,7 +27797,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -22594,7 +27818,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); } return candidate; } @@ -22619,14 +27843,14 @@ var ts; var candidate = void 0; var typeArgumentsAreValid = void 0; var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate.typeParameters, false) + ? createInferenceContext(originalCandidate, false) : undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -22681,15 +27905,16 @@ var ts; return resolveUntypedCall(node); } var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } var apparentType = getApparentType(funcType); if (apparentType === unknownType) { return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isTypeAny(funcType) || - (isTypeAny(apparentType) && funcType.flags & 512) || - (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -22700,12 +27925,27 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); } return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + if (funcType.flags & 524288) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -22714,12 +27954,15 @@ var ts; } } var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } expressionType = getApparentType(expressionType); if (expressionType === unknownType) { return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 128) { + if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -22755,17 +27998,29 @@ var ts; return true; } var declaration = signature.declaration; - var flags = declaration.flags; - if (!(flags & (8 | 16))) { + var modifiers = ts.getModifierFlags(declaration); + if (!(modifiers & 24)) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - if (flags & 8) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } + if (modifiers & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (flags & 16) { + if (modifiers & 16) { error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -22779,11 +28034,12 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -22810,13 +28066,14 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); return resolveErrorCall(node); @@ -22839,21 +28096,21 @@ var ts; function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); var cached = links.resolvedSignature; - if (cached && cached !== anySignature && !candidatesOutArray) { + if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = anySignature; + links.resolvedSignature = resolvingSignature; var result = resolveSignature(node, candidatesOutArray); links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); } return links.inferredClassType; } @@ -22891,7 +28148,7 @@ var ts; return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { @@ -22910,7 +28167,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32); + return includeFalsyTypes(type, 2048); } } return type; @@ -22922,6 +28179,12 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (context.thisParameter) { + if (!signature.thisParameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); + } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -22937,7 +28200,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193) { + if (!ts.isOmittedExpression(element)) { if (element.name.kind === 69) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -23019,17 +28282,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); - if (!type) { - if (funcIsGenerator) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); - return createIterableIteratorType(unknownType); - } - else { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); - } - } + type = getUnionType(types, true); if (funcIsGenerator) { type = createIterableIteratorType(type); } @@ -23037,6 +28290,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } + if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } var widenedType = getWidenedType(type); return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } @@ -23057,27 +28313,21 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - var expr = node.expression; - if (!node.possiblyExhaustive || expr.kind !== 172) { + if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(expr.expression); - if (!(type.flags & 16384)) { - return false; - } - var propName = expr.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { + var type = checkExpression(node.expression); + if (!isLiteralType(type)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(propType, switchTypes); + return eachTypeContainedIn(type, switchTypes); } function functionHasImplicitReturn(func) { - if (!(func.flags & 32768)) { + if (!(func.flags & 128)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); @@ -23098,7 +28348,7 @@ var ts; if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type === neverType) { + if (type.flags & 8192) { hasReturnOfTypeNever = true; } else if (!ts.contains(aggregatedTypes, type)) { @@ -23124,14 +28374,14 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { return; } if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } - var hasExplicitReturn = func.flags & 65536; - if (returnType === neverType) { + var hasExplicitReturn = func.flags & 256; + if (returnType && returnType.flags & 8192) { error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -23226,7 +28476,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { error(operand, diagnostic); return false; } @@ -23234,8 +28484,8 @@ var ts; } function isReadonlySymbol(symbol) { return symbol.isReadonly || - symbol.flags & 4 && (getDeclarationFlagsFromSymbol(symbol) & 64) !== 0 || - symbol.flags & 3 && (getDeclarationFlagsFromSymbol(symbol) & 2048) !== 0 || + symbol.flags & 4 && (getDeclarationModifierFlagsFromSymbol(symbol) & 64) !== 0 || + symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 || symbol.flags & 98304 && !(symbol.flags & 65536) || (symbol.flags & 8) !== 0; } @@ -23308,7 +28558,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 33554432)) { + if (!(node.flags & 262144)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -23320,16 +28570,25 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 36 && node.operand.kind === 8) { + return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + } switch (node.operator) { case 35: case 36: case 50: - if (maybeTypeOfKind(operandType, 16777216)) { + if (maybeTypeOfKind(operandType, 512)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49: - return booleanType; + var facts = getTypeFacts(operandType) & (1048576 | 2097152); + return facts === 1048576 ? falseType : + facts === 2097152 ? trueType : + booleanType; case 41: case 42: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -23342,6 +28601,9 @@ var ts; } function checkPostfixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); @@ -23352,10 +28614,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 49152) { + if (type.flags & 1572864) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -23367,20 +28629,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 16384) { + if (type.flags & 524288) { var types = type.types; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 32768) { + if (type.flags & 1048576) { var types = type.types; - for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { - var t = types_12[_a]; + for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { + var t = types_16[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -23389,13 +28651,16 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (80896 | 65536) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (isTypeOfKind(leftType, 16777726)) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (isTypeOfKind(leftType, 8190)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -23404,32 +28669,35 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var p = properties_3[_i]; + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var p = properties_4[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); } return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_15 = property.name; - if (name_15.kind === 140) { - checkComputedPropertyName(name_15); + var name_19 = property.name; + if (name_19.kind === 140) { + checkComputedPropertyName(name_19); } - if (isComputedNonLiteralName(name_15)) { + if (isComputedNonLiteralName(name_19)) { return undefined; } - var text = getTextOfPropertyName(name_15); + var text = getTextOfPropertyName(name_19); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -23444,7 +28712,7 @@ var ts; } } else { - error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); + error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); } } else { @@ -23474,8 +28742,9 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { + checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -23505,7 +28774,7 @@ var ts; var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -23534,8 +28803,65 @@ var ts; } return sourceType; } + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 69: + case 9: + case 10: + case 176: + case 189: + case 11: + case 8: + case 99: + case 84: + case 93: + case 135: + case 179: + case 192: + case 180: + case 170: + case 171: + case 182: + case 196: + case 242: + case 241: + return true; + case 188: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 187: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 185: + case 186: + switch (node.operator) { + case 49: + case 35: + case 36: + case 50: + return true; + } + return false; + case 183: + case 177: + case 195: + default: + return false; + } + } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 96) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], true); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -23570,15 +28896,18 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 96) + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (leftType.flags & 6144) leftType = rightType; - if (rightType.flags & 96) + if (rightType.flags & 6144) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; - if ((leftType.flags & 8) && - (rightType.flags & 8) && + if ((leftType.flags & 136) && + (rightType.flags & 136) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -23592,18 +28921,21 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 96) + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (leftType.flags & 6144) leftType = rightType; - if (rightType.flags & 96) + if (rightType.flags & 6144) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { + if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { resultType = numberType; } else { - if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { + if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -23635,6 +28967,12 @@ var ts; case 31: case 32: case 33: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -23644,18 +28982,25 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; + return getTypeFacts(leftType) & 1048576 ? + includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + leftType; case 52: - return getUnionType([getNonNullableType(leftType), rightType]); + return getTypeFacts(leftType) & 2097152 ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; case 56: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); case 24: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : - maybeTypeOfKind(rightType, 16777216) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : + maybeTypeOfKind(rightType, 512) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -23707,7 +29052,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 8388608) || isYieldExpressionInClass(node)) { + if (!(node.flags & 65536) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -23740,14 +29085,22 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getUnionType([type1, type2]); + return getBestChoiceType(type1, type2); } - function checkStringLiteralExpression(node) { - var contextualType = getContextualType(node); - if (contextualType && isStringLiteralUnionType(contextualType)) { - return getStringLiteralTypeForText(node.text); + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + case 8: + return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + case 99: + return trueType; + case 84: + return falseType; } - return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -23772,11 +29125,38 @@ var ts; } return links.resolvedType; } + function isTypeAssertion(node) { + node = skipParenthesizedNodes(node); + return node.kind === 177 || node.kind === 195; + } + function checkDeclarationInitializer(declaration) { + var type = checkExpressionCached(declaration.initializer); + return ts.getCombinedNodeFlags(declaration) & 2 || + ts.getCombinedModifierFlags(declaration) & 64 || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 16384) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (apparentType.flags & (2 | 4 | 8 | 16)) { + return true; + } + contextualType = apparentType; + } + return maybeTypeOfKind(contextualType, 480); + } + return false; + } + function checkExpressionForMutableLocation(node, contextualMapper) { + var type = checkExpression(node, contextualMapper); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } function checkPropertyAssignment(node, contextualMapper) { if (node.name.kind === 140) { checkComputedPropertyName(node.name); } - return checkExpression(node.initializer, contextualMapper); + return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); @@ -23820,10 +29200,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -23834,15 +29210,13 @@ var ts; return checkSuperExpression(node); case 93: return nullWideningType; + case 9: + case 8: case 99: case 84: - return booleanType; - case 8: - return checkNumericLiteral(node); + return checkLiteralExpression(node); case 189: return checkTemplateExpression(node); - case 9: - return checkStringLiteralExpression(node); case 11: return stringType; case 10: @@ -23919,7 +29293,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 92) { + if (ts.getModifierFlags(node) & 92) { func = ts.getContainingFunction(node); if (!(func.kind === 148 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -23987,9 +29361,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (ts.isBindingPattern(name_16) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { + var name_20 = _a[_i].name; + if (ts.isBindingPattern(name_20) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -24009,23 +29383,27 @@ var ts; case 156: case 147: case 146: - var parent_10 = node.parent; - if (node === parent_10.type) { - return parent_10; + var parent_11 = node.parent; + if (node === parent_11.type) { + return parent_11; } } } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_17 = _a[_i].name; - if (name_17.kind === 69 && - name_17.text === predicateVariableName) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name_21 = element.name; + if (name_21.kind === 69 && + name_21.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_17.kind === 168 || - name_17.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { + else if (name_21.kind === 168 || + name_21.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { return true; } } @@ -24073,22 +29451,21 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (!node.body) { + if (noUnusedIdentifiers && !node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var getter = 1, setter = 2, property = getter | setter; - var instanceNames = {}; - var staticNames = {}; + var instanceNames = ts.createMap(); + var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, property); + addName(instanceNames, param.name, param.name.text, 3); } } } @@ -24099,21 +29476,21 @@ var ts; if (memberName) { switch (member.kind) { case 149: - addName(names, member.name, memberName, getter); + addName(names, member.name, memberName, 1); break; case 150: - addName(names, member.name, memberName, setter); + addName(names, member.name, memberName, 2); break; case 145: - addName(names, member.name, memberName, property); + addName(names, member.name, memberName, 3); break; } } } } function addName(names, location, name, meaning) { - if (ts.hasProperty(names, name)) { - var prev = names[name]; + var prev = names[name]; + if (prev) { if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -24127,7 +29504,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = {}; + var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144) { @@ -24141,7 +29518,7 @@ var ts; default: continue; } - if (ts.hasProperty(names, memberName)) { + if (names[memberName]) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -24195,7 +29572,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); - if (node.flags & 128 && node.body) { + if (ts.getModifierFlags(node) & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -24240,7 +29617,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 145 && - !(n.flags & 32) && + !(ts.getModifierFlags(n) & 32) && !!n.initializer; } var containingClassDecl = node.parent; @@ -24252,7 +29629,7 @@ var ts; error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & 92; }); + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -24282,13 +29659,8 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); if (node.kind === 149) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { - if (node.flags & 65536) { - if (compilerOptions.noImplicitReturns) { - error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -24300,17 +29672,20 @@ var ts; var otherKind = node.kind === 149 ? 150 : 149; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 28) !== (otherAccessor.flags & 28))) { + if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (((node.flags & 128) !== (otherAccessor.flags & 128))) { + if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - getTypeOfAccessors(getSymbolOfNode(node)); + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 149) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -24342,7 +29717,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -24363,6 +29738,9 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } + if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } } } function checkTypeQuery(node) { @@ -24391,10 +29769,10 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 8) && ts.isInAmbientContext(node); + return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedNodeFlags(n); + var flags = ts.getCombinedModifierFlags(n); if (n.parent.kind !== 222 && n.parent.kind !== 221 && n.parent.kind !== 192 && @@ -24475,9 +29853,9 @@ var ts; var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { var reportError = (node.kind === 147 || node.kind === 146) && - (node.flags & 32) !== (subsequentNode.flags & 32); + (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); if (reportError) { - var diagnostic = node.flags & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -24493,7 +29871,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (node.flags & 128) { + if (ts.getModifierFlags(node) & 128) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -24553,7 +29931,7 @@ var ts; }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -24632,10 +30010,10 @@ var ts; case 224: return 2097152 | 1048576; case 229: - var result_1 = 0; + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); - return result_1; + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; default: return 1048576; } @@ -24658,7 +30036,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 4096) { + if (promise.flags & 131072) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -24684,7 +30062,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -24695,13 +30073,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 16384) { + if (type.flags & 524288) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types); + return getUnionType(types, true); } else { var promisedType = getPromisedType(type); @@ -24723,7 +30101,7 @@ var ts; } } } - function checkCorrectPromiseType(returnType, location) { + function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { if (returnType === unknownType) { return unknownType; } @@ -24732,13 +30110,13 @@ var ts; || globalPromiseType === getTargetType(returnType)) { return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } - error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(location, diagnostic, typeName); return unknownType; } function checkAsyncFunctionReturnType(node) { if (languageVersion >= 2) { var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type); + return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { @@ -24753,12 +30131,11 @@ var ts; var typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - return unknownType; + return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); } checkReturnTypeAnnotationAsExpression(node); var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } var promiseName = ts.getEntityNameFromTypeNode(node.type); @@ -24806,7 +30183,7 @@ var ts; function checkTypeNodeAsExpression(node) { if (node && node.kind === 155) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793056 : 1536; + var meaning = root.parent.kind === 155 ? 793064 : 1920; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -24961,22 +30338,21 @@ var ts; } function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function(key) { - if (ts.hasProperty(node.locals, key)) { - var local_1 = node.locals[key]; - if (!local_1.isReferenced) { - if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142) { - var parameter = local_1.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); - } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); + var _loop_1 = function (key) { + var local = node.locals[key]; + if (!local.isReferenced) { + if (local.valueDeclaration && local.valueDeclaration.kind === 142) { + var parameter = local.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + } } }; for (var key in node.locals) { @@ -24984,6 +30360,9 @@ var ts; } } } + function parameterIsThisKeyword(parameter) { + return parameter.name && parameter.name.originalKeywordKind === 97; + } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -24993,15 +30372,15 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 147 || member.kind === 145) { - if (!member.symbol.isReferenced && member.flags & 8) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } else if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && parameter.flags & 8) { - error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -25012,9 +30391,14 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!typeParameter.symbol.isReferenced) { + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -25024,14 +30408,12 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - if (ts.hasProperty(node.locals, key)) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); - } + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } } @@ -25137,12 +30519,12 @@ var ts; return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152) { + if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 3072) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } if (node.kind === 218 && !node.initializer) { @@ -25154,7 +30536,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219); var container = varDeclList.parent.kind === 200 && varDeclList.parent.parent ? varDeclList.parent.parent @@ -25165,8 +30547,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_18 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); + var name_22 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); } } } @@ -25206,7 +30588,7 @@ var ts; return; } if (current.parent.kind === 145 && - !(current.parent.flags & 32) && + !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)) { return; } @@ -25234,12 +30616,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_11 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_11); - var name_19 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); - if (parent_11.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); + var parent_12 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_12); + var name_23 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); + if (parent_12.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -25302,7 +30684,7 @@ var ts; 128 | 64 | 32; - return (left.flags & interestingFlags) === (right.flags & interestingFlags); + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -25413,7 +30795,7 @@ var ts; if (varExpr.kind === 170 || varExpr.kind === 171) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -25421,7 +30803,7 @@ var ts; } } var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -25474,7 +30856,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 4096) && type.target === getGlobalIterableType()) { + if ((type.flags & 131072) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -25489,7 +30871,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), true), errorNode); } } return typeAsIterable.iterableElementType; @@ -25500,7 +30882,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 4096) && type.target === getGlobalIteratorType()) { + if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -25515,7 +30897,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), true); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -25535,7 +30917,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 4096) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -25544,10 +30926,10 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 16384) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); + if (arrayOrStringType.flags & 524288) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); } - else if (arrayOrStringType.flags & 258) { + else if (arrayOrStringType.flags & 34) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -25557,7 +30939,7 @@ var ts; error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); reportedError = true; } - if (arrayType === neverType) { + if (arrayType.flags & 8192) { return stringType; } } @@ -25572,10 +30954,10 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 258) { + if (arrayElementType.flags & 34) { return stringType; } - return getUnionType([arrayElementType, stringType]); + return getUnionType([arrayElementType, stringType], true); } return arrayElementType; } @@ -25587,7 +30969,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -25600,7 +30982,7 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType === neverType) { + if (strictNullChecks || node.expression || returnType.flags & 8192) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (func.asteriskToken) { return; @@ -25635,7 +31017,7 @@ var ts; } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 33554432) { + if (node.flags & 262144) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -25718,7 +31100,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals && ts.hasProperty(locals, identifierName)) { + if (locals) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -25743,11 +31125,11 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(member.flags & 32) && ts.hasDynamicName(member)) { + if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -25758,7 +31140,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 2048)) { + if (!errorNode && (type.flags & 65536)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -25780,7 +31162,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 2048) { + else if (containingType.flags & 65536) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -25845,7 +31227,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 512)) { + if (!node.name && !(ts.getModifierFlags(node) & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -25888,6 +31270,11 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { + error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); + } + } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { @@ -25901,15 +31288,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { + if (!ts.isEntityNameExpression(typeRefNode.expression)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 4096) ? t.target : t; - if (declaredType.flags & (1024 | 2048)) { + var declaredType = (t.flags & 131072) ? t.target : t; + if (declaredType.flags & (32768 | 65536)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -25928,7 +31315,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && declaration.flags & 8) { + if (declaration && ts.getModifierFlags(declaration) & 8) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); @@ -25951,12 +31338,12 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { if (derivedClassDecl.kind === 192) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -25966,7 +31353,7 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); if ((baseDeclarationFlags & 8) || (derivedDeclarationFlags & 8)) { continue; } @@ -26033,19 +31420,19 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = {}; + var seen = ts.createMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; - if (!ts.hasProperty(seen, prop.name)) { + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var prop = properties_5[_a]; + var existing = seen[prop.name]; + if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; } else { - var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -26083,7 +31470,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -26091,7 +31478,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - checkUnusedTypeParameters(node); + registerForUnusedIdentifiersCheck(node); } } function checkTypeAliasDeclaration(node) { @@ -26114,7 +31501,7 @@ var ts; } else { var text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text)) { + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -26406,9 +31793,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -26434,9 +31818,9 @@ var ts; break; case 169: case 218: - var name_20 = node.name; - if (ts.isBindingPattern(name_20)) { - for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { + var name_24 = node.name; + if (ts.isBindingPattern(name_24)) { + for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26462,19 +31846,20 @@ var ts; } } function getFirstIdentifier(node) { - while (true) { - if (node.kind === 139) { - node = node.left; - } - else if (node.kind === 172) { - node = node.expression; - } - else { - break; - } + switch (node.kind) { + case 69: + return node; + case 139: + do { + node = node.left; + } while (node.kind !== 69); + return node; + case 172: + do { + node = node.expression; + } while (node.kind !== 69); + return node; } - ts.Debug.assert(node.kind === 69); - return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -26502,8 +31887,8 @@ var ts; var target = resolveAlias(symbol); if (target !== unknownSymbol) { var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793056 ? 793056 : 0) | - (symbol.flags & 1536 ? 1536 : 0); + (symbol.flags & 793064 ? 793064 : 0) | + (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -26522,7 +31907,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -26549,7 +31934,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1) { + if (ts.getModifierFlags(node) & 1) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -26557,11 +31942,11 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 107455) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1536).flags & 1536)) { + if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793056) { + if (target.flags & 793064) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -26577,7 +31962,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -26605,7 +31990,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); } @@ -26623,7 +32008,7 @@ var ts; error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69) { @@ -26661,13 +32046,13 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports_2 = getExportsOfModule(moduleSymbol); - for (var id in exports_2) { + var exports_1 = getExportsOfModule(moduleSymbol); + for (var id in exports_1) { if (id === "__export") { continue; } - var _a = exports_2[id], declarations = _a.declarations, flags = _a.flags; - if (flags & (1536 | 64 | 384)) { + var _a = exports_1[id], declarations = _a.declarations, flags = _a.flags; + if (flags & (1920 | 64 | 384)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -26837,9 +32222,10 @@ var ts; } } function checkSourceFile(node) { - var start = new Date().getTime(); + ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); - ts.checkTime += new Date().getTime() - start; + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); } function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -26910,7 +32296,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -26941,7 +32327,7 @@ var ts; case 221: case 222: if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056); + copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; case 179: @@ -26954,7 +32340,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = location.flags; + memberFlags = ts.getModifierFlags(location); location = location.parent; } copySymbols(globals, meaning); @@ -26962,7 +32348,7 @@ var ts; function copySymbol(symbol, meaning) { if (symbol.flags & meaning) { var id = symbol.name; - if (!ts.hasProperty(symbols, id)) { + if (!symbols[id]) { symbols[id] = symbol; } } @@ -27050,15 +32436,13 @@ var ts; default: } } - if (entityName.parent.kind === 235) { - return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); + if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); } - if (entityName.kind !== 172) { - if (isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); - } + if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 229); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -27066,18 +32450,18 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 194) { - meaning = 793056; + meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; } } else { - meaning = 1536; + meaning = 1920; } meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if (ts.isExpression(entityName)) { + else if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; } @@ -27103,7 +32487,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793056 : 1536; + var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 246) { @@ -27155,7 +32539,7 @@ var ts; } } case 95: - var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case 165: return getTypeFromTypeNode(node).symbol; @@ -27195,16 +32579,16 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { return unknownType; } - if (ts.isTypeNode(node)) { + if (ts.isPartOfTypeNode(node)) { return getTypeFromTypeNode(node); } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { return getTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -27263,11 +32647,11 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return checkExpression(expr); + return getRegularTypeOfLiteralType(checkExpression(expr)); } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 32 + return ts.getModifierFlags(node) & 32 ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -27276,7 +32660,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!ts.hasProperty(propsByName, p.name)) { + if (!propsByName[p.name]) { propsByName[p.name] = p; } }); @@ -27286,9 +32670,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_21 = symbol.name; + var name_25 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_21); + var symbol = getPropertyOfType(t, name_25); if (symbol) { symbols_3.push(symbol); } @@ -27308,11 +32692,17 @@ var ts; return [symbol]; } function isArgumentsLocalBinding(node) { - return getReferencedValueSymbol(node) === argumentsSymbol; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + return getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol) { + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -27321,7 +32711,7 @@ var ts; if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455) - : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -27329,34 +32719,48 @@ var ts; return s && !!(s.flags & 107455); } } - function getReferencedExportContainer(node) { - var symbol = getReferencedValueSymbol(node); - if (symbol) { - if (symbol.flags & 1048576) { - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (exportSymbol.flags & 944) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { - if (parentSymbol.valueDeclaration === ts.getSourceFileOfNode(node)) { - return parentSymbol.valueDeclaration; + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944) { + return undefined; } + symbol = exportSymbol; } - for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 225 || n.kind === 224) && getSymbolOfNode(n) === parentSymbol) { - return n; + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { + var symbolFile = parentSymbol.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + for (var n = node.parent; n; n = n.parent) { + if (ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) { + return n; + } } } } } } function getReferencedImportDeclaration(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && symbol.flags & 8388608 ? getDeclarationOfAliasSymbol(symbol) : undefined; + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && symbol.flags & 8388608) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418) { @@ -27384,30 +32788,53 @@ var ts; return false; } function getReferencedDeclarationWithCollidingName(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; } function isDeclarationWithCollidingName(node) { - return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; } function isValueAliasDeclaration(node) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + return true; + } switch (node.kind) { case 229: case 231: case 232: case 234: case 238: - return isAliasResolvedToValue(getSymbolOfNode(node)); + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); case 235: - return node.expression && node.expression.kind === 69 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; + return node.expression + && node.expression.kind === 69 + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -27425,9 +32852,13 @@ var ts; return isConstEnumSymbol(s) || s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + return true; + } if (ts.isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (getSymbolLinks(symbol).referenced) { + if (symbol && getSymbolLinks(symbol).referenced) { return true; } } @@ -27446,7 +32877,8 @@ var ts; return false; } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + node = ts.getParseTreeNode(node); + return node ? getNodeLinks(node).flags : undefined; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -27465,15 +32897,19 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 80896 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; } - function getTypeReferenceSerializationKind(typeName) { - var valueSymbol = resolveEntityName(typeName, 107455, true); + function getTypeReferenceSerializationKind(typeName, location) { + var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); + var globalPromiseSymbol = tryGetGlobalPromiseConstructorSymbol(); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } var constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793056, true); + var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -27484,22 +32920,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16)) { - return ts.TypeReferenceSerializationKind.VoidType; + else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 8)) { + else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 132)) { + else if (isTypeOfKind(type, 340)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 258)) { + else if (isTypeOfKind(type, 34)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTypeOfKind(type, 8192)) { + else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 16777216)) { + else if (isTypeOfKind(type, 512)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -27515,7 +32951,7 @@ var ts; function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 | 131072)) - ? getTypeOfSymbol(symbol) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -27534,16 +32970,44 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return ts.hasProperty(globals, name); + return !!globals[name]; } - function getReferencedValueSymbol(reference) { - return getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + var parent_13 = reference.parent; + if (ts.isDeclaration(parent_13) && reference === parent_13.name) { + location = getDeclarationContainer(parent_13); + } + } + return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); } function getReferencedValueDeclaration(reference) { - ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getReferencedValueSymbol(reference); - return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 && type.flags & 16777216); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -27551,9 +33015,6 @@ var ts; if (resolvedTypeReferenceDirectives) { fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { - if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { - continue; - } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; @@ -27589,7 +33050,9 @@ var ts; isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { @@ -27597,7 +33060,7 @@ var ts; } var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) ? 107455 | 1048576 - : 793056 | 1536; + : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -27627,9 +33090,9 @@ var ts; } var current = symbol; while (true) { - var parent_12 = getParentOfSymbol(current); - if (parent_12) { - current = parent_12; + var parent_14 = getParentOfSymbol(current); + if (parent_14) { + current = parent_14; } else { break; @@ -27657,11 +33120,15 @@ var ts; return ts.getDeclarationOfKind(moduleSymbol, 256); } function initializeTypeChecker() { - ts.forEach(host.getSourceFiles(), function (file) { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); - }); + } var augmentations; - ts.forEach(host.getSourceFiles(), function (file) { + var requestedExternalEmitHelpers = 0; + var firstFileRequestingExternalHelpers; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -27672,14 +33139,28 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - mergeSymbolTable(globals, file.symbol.globalExports); + var source = file.symbol.globalExports; + for (var id in source) { + if (!(id in globals)) { + globals[id] = source[id]; + } + } } - }); + if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { + var fileRequestedExternalEmitHelpers = file.flags & 31744; + if (fileRequestedExternalEmitHelpers) { + requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; + if (firstFileRequestingExternalHelpers === undefined) { + firstFileRequestingExternalHelpers = file; + } + } + } + } if (augmentations) { - for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { - var list = augmentations_1[_i]; - for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { - var augmentation = list_2[_a]; + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; mergeModuleAugmentation(augmentation); } } @@ -27703,10 +33184,11 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056, undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064, undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); + tryGetGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalSymbol("Promise", 107455, undefined) && getGlobalPromiseConstructorSymbol(); }); getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); getGlobalThenableType = ts.memoize(createThenableType); getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); }); @@ -27723,9 +33205,42 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { + var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); + if (helpersModule) { + var exports_2 = helpersModule.exports; + if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { + verifyHelperSymbol(exports_2, "__extends", 107455); + } + if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { + verifyHelperSymbol(exports_2, "__assign", 107455); + } + if (requestedExternalEmitHelpers & 2048) { + verifyHelperSymbol(exports_2, "__decorate", 107455); + if (compilerOptions.emitDecoratorMetadata) { + verifyHelperSymbol(exports_2, "__metadata", 107455); + } + } + if (requestedExternalEmitHelpers & 4096) { + verifyHelperSymbol(exports_2, "__param", 107455); + } + if (requestedExternalEmitHelpers & 8192) { + verifyHelperSymbol(exports_2, "__awaiter", 107455); + if (languageVersion < 2) { + verifyHelperSymbol(exports_2, "__generator", 107455); + } + } + } + } + } + function verifyHelperSymbol(symbols, name, meaning) { + var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); + if (!symbol) { + error(undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -27737,7 +33252,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(65536); + var thenableType = createObjectType(2097152); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -27765,49 +33280,9 @@ var ts; return false; } function checkGrammarModifiers(node) { - switch (node.kind) { - case 149: - case 150: - case 148: - case 145: - case 144: - case 147: - case 146: - case 153: - case 225: - case 230: - case 229: - case 236: - case 235: - case 179: - case 180: - case 142: - break; - case 220: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && - node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 221: - case 222: - case 200: - case 223: - if (node.modifiers && node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 224: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && - node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - default: - return false; - } - if (!node.modifiers) { - return; + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -27945,7 +33420,7 @@ var ts; node.kind !== 150) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 && node.parent.flags & 128)) { + if (!(node.parent.kind === 221 && ts.getModifierFlags(node.parent) & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -28000,10 +33475,57 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function checkGrammarAsyncModifier(node, asyncModifier) { - if (languageVersion < 2) { - return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 149: + case 150: + case 148: + case 145: + case 144: + case 147: + case 146: + case 153: + case 225: + case 230: + case 229: + case 236: + case 235: + case 179: + case 180: + case 142: + return false; + default: + if (node.parent.kind === 226 || node.parent.kind === 256) { + return false; + } + switch (node.kind) { + case 220: + return nodeHasAnyModifiersExcept(node, 118); + case 221: + return nodeHasAnyModifiersExcept(node, 115); + case 222: + case 200: + case 223: + return true; + case 224: + return nodeHasAnyModifiersExcept(node, 74); + default: + ts.Debug.fail(); + return false; + } } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { case 147: case 220: @@ -28093,7 +33615,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1023) { + if (ts.getModifierFlags(parameter) !== 0) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -28130,8 +33652,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { - var arg = args_1[_i]; + for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { + var arg = args_2[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -28232,30 +33754,34 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; - var _loop_2 = function(prop) { - var name_22 = prop.name; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var name_26 = prop.name; if (prop.kind === 193 || - name_22.kind === 140) { - checkGrammarComputedPropertyName(name_22); + name_26.kind === 140) { + checkGrammarComputedPropertyName(name_26); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { - return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } - ts.forEach(prop.modifiers, function (mod) { - if (mod.kind !== 118 || prop.kind !== 147) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 118 || prop.kind !== 147) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } } - }); + } var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_22.kind === 8) { - checkGrammarNumericLiteral(name_22); + if (name_26.kind === 8) { + checkGrammarNumericLiteral(name_26); } currentKind = Property; } @@ -28271,51 +33797,46 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); if (effectiveName === undefined) { - return "continue"; + continue; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); + grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } - }; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var state_3 = _loop_2(prop); - if (typeof state_3 === "object") return state_3.value; } } function checkGrammarJsxElement(node) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247) { continue; } var jsxAttr = attr; - var name_23 = jsxAttr.name; - if (!ts.hasProperty(seen, name_23.text)) { - seen[name_23.text] = true; + var name_27 = jsxAttr.name; + if (!seen[name_27.text]) { + seen[name_27.text] = true; } else { - return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28365,7 +33886,7 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(accessor.flags & 128)) { + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { @@ -28502,10 +34023,26 @@ var ts; } } } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 || expr.kind === 8 || + expr.kind === 185 && expr.operator === 36 && + expr.operand.kind === 8; + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 207 && node.parent.parent.kind !== 208) { if (ts.isInAmbientContext(node)) { if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { var equalsTokenLength = "=".length; return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } @@ -28532,7 +34069,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 193) { + if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -28578,8 +34115,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); return true; } } @@ -28639,8 +34176,8 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || - (node.flags & 2) || - (node.flags & (1 | 512))) { + node.kind === 228 || + ts.getModifierFlags(node) & (2 | 1 | 512)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -28685,278 +34222,7977 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); return true; } } - var _a; + function getAmbientModules() { + var result = []; + for (var sym in globals) { + if (ambientModuleSymbolRegex.test(sym)) { + result.push(globals[sym]); + } + } + return result; + } } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; (function (ts) { - var nullSourceMapWriter; - var defaultLastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitStart: function (range) { }, - emitEnd: function (range, stopOverridingSpan) { }, - emitPos: function (pos) { }, - changeEmitSourcePos: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; }, - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { } - }; - } - return nullSourceMapWriter; + ; + var nodeEdgeTraversalMap = ts.createMap((_a = {}, + _a[139] = [ + { name: "left", test: ts.isEntityName }, + { name: "right", test: ts.isIdentifier } + ], + _a[143] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[177] = [ + { name: "type", test: ts.isTypeNode }, + { name: "expression", test: ts.isUnaryExpression } + ], + _a[195] = [ + { name: "expression", test: ts.isExpression }, + { name: "type", test: ts.isTypeNode } + ], + _a[196] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[224] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[225] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[226] = [ + { name: "statements", test: ts.isStatement } + ], + _a[229] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "moduleReference", test: ts.isModuleReference } + ], + _a[240] = [ + { name: "expression", test: ts.isExpression, optional: true } + ], + _a[255] = [ + { name: "name", test: ts.isPropertyName }, + { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } + ], + _a)); + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; } - ts.getNullSourceMapWriter = getNullSourceMapWriter; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - var currentSourceFile; - var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; - var sourceMapSourceIndex; - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan; - var lastEncodedNameIndex; - var sourceMapData; - return { - getSourceMapData: function () { return sourceMapData; }, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - changeEmitSourcePos: changeEmitSourcePos, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - initialize: initialize, - reset: reset - }; - function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { - if (sourceMapData) { - reset(); - } - currentSourceFile = undefined; - sourceMapSourceIndex = -1; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; - lastEncodedNameIndex = 0; - sourceMapData = { - sourceMapFilePath: sourceMapFilePath, - jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, - sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (!isBundledEmit) { - ts.Debug.assert(sourceFiles.length === 1); - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); - } + function reduceEachChild(node, f, initial) { + if (node === undefined) { + return initial; } - function reset() { - currentSourceFile = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; + var kind = node.kind; + if ((kind > 0 && kind <= 138)) { + return initial; } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; + if ((kind >= 154 && kind <= 166)) { + return initial; + } + var result = initial; + switch (node.kind) { + case 198: + case 201: + case 193: + case 217: + case 287: + break; + case 140: + result = reduceNode(node.expression, f, result); + break; + case 142: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 143: + result = reduceNode(node.expression, f, result); + break; + case 145: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 147: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 148: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 149: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 150: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 167: + case 168: + result = ts.reduceLeft(node.elements, f, result); + break; + case 169: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 170: + result = ts.reduceLeft(node.elements, f, result); + break; + case 171: + result = ts.reduceLeft(node.properties, f, result); + break; + case 172: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.name, f, result); + break; + case 173: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.argumentExpression, f, result); + break; + case 174: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 175: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 176: + result = reduceNode(node.tag, f, result); + result = reduceNode(node.template, f, result); + break; + case 179: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 180: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 178: + case 181: + case 182: + case 183: + case 184: + case 190: + case 191: + case 196: + result = reduceNode(node.expression, f, result); + break; + case 185: + case 186: + result = reduceNode(node.operand, f, result); + break; + case 187: + result = reduceNode(node.left, f, result); + result = reduceNode(node.right, f, result); + break; + case 188: + result = reduceNode(node.condition, f, result); + result = reduceNode(node.whenTrue, f, result); + result = reduceNode(node.whenFalse, f, result); + break; + case 189: + result = reduceNode(node.head, f, result); + result = ts.reduceLeft(node.templateSpans, f, result); + break; + case 192: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 194: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + break; + case 197: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.literal, f, result); + break; + case 199: + result = ts.reduceLeft(node.statements, f, result); + break; + case 200: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.declarationList, f, result); + break; + case 202: + result = reduceNode(node.expression, f, result); + break; + case 203: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.thenStatement, f, result); + result = reduceNode(node.elseStatement, f, result); + break; + case 204: + result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, f, result); + break; + case 205: + case 212: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 206: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.condition, f, result); + result = reduceNode(node.incrementor, f, result); + result = reduceNode(node.statement, f, result); + break; + case 207: + case 208: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 211: + case 215: + result = reduceNode(node.expression, f, result); + break; + case 213: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.caseBlock, f, result); + break; + case 214: + result = reduceNode(node.label, f, result); + result = reduceNode(node.statement, f, result); + break; + case 216: + result = reduceNode(node.tryBlock, f, result); + result = reduceNode(node.catchClause, f, result); + result = reduceNode(node.finallyBlock, f, result); + break; + case 218: + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 219: + result = ts.reduceLeft(node.declarations, f, result); + break; + case 220: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 221: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 227: + result = ts.reduceLeft(node.clauses, f, result); + break; + case 230: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.importClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 231: + result = reduceNode(node.name, f, result); + result = reduceNode(node.namedBindings, f, result); + break; + case 232: + result = reduceNode(node.name, f, result); + break; + case 233: + case 237: + result = ts.reduceLeft(node.elements, f, result); + break; + case 234: + case 238: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + break; + case 235: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.expression, f, result); + break; + case 236: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.exportClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 241: + result = reduceNode(node.openingElement, f, result); + result = ts.reduceLeft(node.children, f, result); + result = reduceNode(node.closingElement, f, result); + break; + case 242: + case 243: + result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.attributes, f, result); + break; + case 245: + result = reduceNode(node.tagName, f, result); + break; + case 246: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 247: + result = reduceNode(node.expression, f, result); + break; + case 248: + result = reduceNode(node.expression, f, result); + break; + case 249: + result = reduceNode(node.expression, f, result); + case 250: + result = ts.reduceLeft(node.statements, f, result); + break; + case 251: + result = ts.reduceLeft(node.types, f, result); + break; + case 252: + result = reduceNode(node.variableDeclaration, f, result); + result = reduceNode(node.block, f, result); + break; + case 253: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 254: + result = reduceNode(node.name, f, result); + result = reduceNode(node.objectAssignmentInitializer, f, result); + break; + case 256: + result = ts.reduceLeft(node.statements, f, result); + break; + case 288: + result = reduceNode(node.expression, f, result); + break; + default: + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_1 = edgeTraversalPath; _i < edgeTraversalPath_1.length; _i++) { + var edge = edgeTraversalPath_1[_i]; + var value = node[edge.name]; + if (value !== undefined) { + result = ts.isArray(value) + ? ts.reduceLeft(value, f, result) + : f(result, value); + } } } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } - } - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - } - function emitPos(pos) { - if (pos === -1) { - return; - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - sourceIndex: sourceMapSourceIndex - }; - stopOverridingSpan = false; - } - else if (!stopOverridingSpan) { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - updateLastEncodedAndRecordedSpans(); - } - function getStartPos(range) { - var rangeHasDecorators = !!range.decorators; - return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; - } - function emitStart(range) { - emitPos(getStartPos(range)); - } - function emitEnd(range, stopOverridingEnd) { - emitPos(range.end); - stopOverridingSpan = stopOverridingEnd; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); - if (sourceMapSourceIndex === -1) { - sourceMapSourceIndex = sourceMapData.sourceMapSources.length; - sourceMapData.sourceMapSources.push(source); - sourceMapData.inputSourceFileNames.push(sourceFile.fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(sourceFile.text); - } - } - } - function getText() { - encodeLastRecordedSourceMapSpan(); - return ts.stringify({ - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent - }); - } - function getSourceMappingURL() { - if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(getText()); - return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; - } - else { - return sourceMapData.jsSourceMappingURL; - } + break; } + return result; } - ts.createSourceMapWriter = createSourceMapWriter; - var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - function base64FormatEncode(inValue) { - if (inValue < 64) { - return base64Chars.charAt(inValue); + ts.reduceEachChild = reduceEachChild; + function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { + if (node === undefined) { + return undefined; } - throw TypeError(inValue + ": not a 64 based value"); - } - function base64VLQFormatEncode(inValue) { - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + if (!optional) { + Debug.failNotOptional(); + } + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); } else { - inValue = inValue << 1; + visitedNode = visited; } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; + if (parenthesize !== undefined) { + visitedNode = parenthesize(visitedNode, parentNode); + } + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + return visitedNode; } + ts.visitNode = visitNode; + function visitNodes(nodes, visitor, test, start, count, parenthesize, parentNode) { + if (nodes === undefined) { + return undefined; + } + var updated; + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + updated = ts.createNodeArray([], undefined, nodes.hasTrailingComma && start + count === length); + } + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + updated = ts.createNodeArray(nodes.slice(0, i), nodes, nodes.hasTrailingComma); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + visitedNode = parenthesize + ? parenthesize(visitedNode, parentNode) + : visitedNode; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + var visitedNode = parenthesize + ? parenthesize(visited, parentNode) + : visited; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + function visitEachChild(node, visitor, context) { + if (node === undefined) { + return undefined; + } + var kind = node.kind; + if ((kind > 0 && kind <= 138)) { + return node; + } + if ((kind >= 154 && kind <= 166)) { + return node; + } + switch (node.kind) { + case 198: + case 201: + case 193: + case 217: + return node; + case 140: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + case 142: + return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 145: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 147: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 148: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 149: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 150: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 167: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 168: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 169: + return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 170: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 171: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 172: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 173: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 174: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 175: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 176: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + case 178: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 179: + return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 180: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, true), context.endLexicalEnvironment())); + case 181: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 182: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 183: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 185: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 186: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 188: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 189: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 190: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 191: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 194: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 197: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + case 199: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 200: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 202: + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 203: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); + case 204: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 205: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 206: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 207: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 208: + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 209: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + case 210: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + case 211: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + case 212: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 213: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 214: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 215: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 216: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + case 218: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 219: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 220: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 221: + return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 227: + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 230: + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 231: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); + case 232: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 233: + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 234: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 235: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 236: + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); + case 237: + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + case 238: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 241: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 242: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 243: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 245: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 246: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 247: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 248: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 249: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + case 250: + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 251: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 252: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + case 253: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 254: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 256: + context.startLexicalEnvironment(); + return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); + case 288: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + default: + var updated = void 0; + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_2 = edgeTraversalPath; _i < edgeTraversalPath_2.length; _i++) { + var edge = edgeTraversalPath_2[_i]; + var value = node[edge.name]; + if (value !== undefined) { + var visited = ts.isArray(value) + ? visitNodes(value, visitor, edge.test, 0, value.length, edge.parenthesize, node) + : visitNode(value, visitor, edge.test, edge.optional, edge.lift, edge.parenthesize, node); + if (updated !== undefined || visited !== value) { + if (updated === undefined) { + updated = ts.getMutableClone(node); + } + if (visited !== value) { + updated[edge.name] = visited; + } + } + } + } + } + return updated ? ts.updateNode(updated, node) : node; + } + } + ts.visitEachChild = visitEachChild; + function mergeFunctionBodyLexicalEnvironment(body, declarations) { + if (body && declarations !== undefined && declarations.length > 0) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.createNodeArray(ts.concatenate(body.statements, declarations), body.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([ts.createReturn(body, body)].concat(declarations), body), body, true); + } + } + return body; + } + ts.mergeFunctionBodyLexicalEnvironment = mergeFunctionBodyLexicalEnvironment; + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + function extractSingleNode(nodes) { + Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0; + } + else if (node.transformFlags & 536870912) { + return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + } + function aggregateTransformFlagsForSubtree(node) { + if (ts.hasModifier(node, 2) || ts.isTypeNode(node)) { + return 0; + } + return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0); + } + function aggregateTransformFlagsForChildNode(transformFlags, child) { + return transformFlags | aggregateTransformFlagsForNode(child); + } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 154 && kind <= 166) { + return -3; + } + switch (kind) { + case 174: + case 175: + case 170: + return 537133909; + case 225: + return 546335573; + case 142: + return 538968917; + case 180: + return 550710101; + case 179: + case 220: + return 550726485; + case 219: + return 538968917; + case 221: + case 192: + return 537590613; + case 148: + return 550593365; + case 147: + case 149: + case 150: + return 550593365; + case 117: + case 130: + case 127: + case 132: + case 120: + case 133: + case 103: + case 141: + case 144: + case 146: + case 151: + case 152: + case 153: + case 222: + case 223: + return -3; + case 171: + return 537430869; + default: + return 536871765; + } + } + var Debug; + (function (Debug) { + Debug.failNotOptional = Debug.shouldAssert(1) + ? function (message) { return Debug.assert(false, message || "Node not optional."); } + : function (message) { }; + Debug.failBadSyntaxKind = Debug.shouldAssert(1) + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + : function (node, message) { }; + Debug.assertNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : function (node, test, message) { }; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + })(Debug = ts.Debug || (ts.Debug = {})); + var _a; +})(ts || (ts = {})); +var ts; +(function (ts) { + function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { + if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + var right = node.right; + if (ts.isDestructuringAssignment(right)) { + return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); + } + else { + return node.right; + } + } + var location = node; + var value = node.right; + var expressions = []; + if (needsValue) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment, visitor); + } + else if (ts.nodeIsSynthesized(node)) { + location = value; + } + flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); + if (needsValue) { + expressions.push(value); + } + var expression = ts.inlineExpressions(expressions); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location) { + var expression = ts.createAssignment(name, value, location); + context.setNodeEmitFlags(expression, 2048); + ts.aggregateTransformFlags(expression); + expressions.push(expression); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function flattenParameterDestructuring(context, node, value, visitor) { + var declarations = []; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location) { + var declaration = ts.createVariableDeclaration(name, undefined, value, location); + context.setNodeEmitFlags(declaration, 2048); + ts.aggregateTransformFlags(declaration); + declarations.push(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(undefined); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenParameterDestructuring = flattenParameterDestructuring; + function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { + var declarations = []; + var pendingAssignments; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location, original) { + if (pendingAssignments) { + pendingAssignments.push(value); + value = ts.inlineExpressions(pendingAssignments); + pendingAssignments = undefined; + } + var declaration = ts.createVariableDeclaration(name, undefined, value, location); + declaration.original = original; + context.setNodeEmitFlags(declaration, 2048); + declarations.push(declaration); + ts.aggregateTransformFlags(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + if (recordTempVariable) { + var assignment = ts.createAssignment(name, value, location); + if (pendingAssignments) { + pendingAssignments.push(assignment); + } + else { + pendingAssignments = [assignment]; + } + } + else { + emitAssignment(name, value, location, undefined); + } + return name; + } + } + ts.flattenVariableDestructuring = flattenVariableDestructuring; + function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { + var pendingAssignments = []; + flattenDestructuring(context, node, undefined, node, emitAssignment, emitTempVariableAssignment, visitor); + var expression = ts.inlineExpressions(pendingAssignments); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location, original) { + var left = nameSubstitution && nameSubstitution(name) || name; + emitPendingAssignment(left, value, location, original); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitPendingAssignment(name, value, location, undefined); + return name; + } + function emitPendingAssignment(name, value, location, original) { + var expression = ts.createAssignment(name, value, location); + expression.original = original; + context.setNodeEmitFlags(expression, 2048); + pendingAssignments.push(expression); + return expression; + } + } + ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; + function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { + if (value && visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + if (ts.isBinaryExpression(root)) { + emitDestructuringAssignment(root.left, value, location); + } + else { + emitBindingElement(root, value); + } + function emitDestructuringAssignment(bindingTarget, value, location) { + var target; + if (ts.isShorthandPropertyAssignment(bindingTarget)) { + var initializer = visitor + ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) + : bindingTarget.objectAssignmentInitializer; + if (initializer) { + value = createDefaultValueCheck(value, initializer, location); + } + target = bindingTarget.name; + } + else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56) { + var initializer = visitor + ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) + : bindingTarget.right; + value = createDefaultValueCheck(value, initializer, location); + target = bindingTarget.left; + } + else { + target = bindingTarget; + } + if (target.kind === 171) { + emitObjectLiteralAssignment(target, value, location); + } + else if (target.kind === 170) { + emitArrayLiteralAssignment(target, value, location); + } + else { + var name_28 = ts.getMutableClone(target); + context.setSourceMapRange(name_28, target); + context.setCommentRange(name_28, target); + emitAssignment(name_28, value, location, undefined); + } + } + function emitObjectLiteralAssignment(target, value, location) { + var properties = target.properties; + if (properties.length !== 1) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + if (p.kind === 253 || p.kind === 254) { + var propName = p.name; + var target_1 = p.kind === 254 ? p : p.initializer || propName; + emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); + } + } + } + function emitArrayLiteralAssignment(target, value, location) { + var elements = target.elements; + var numElements = elements.length; + if (numElements !== 1) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var e = elements[i]; + if (e.kind !== 193) { + if (e.kind !== 191) { + emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); + } + else if (i === numElements - 1) { + emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); + } + } + } + } + function emitBindingElement(target, value) { + var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + if (initializer) { + value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + } + else if (!value) { + value = ts.createVoidZero(); + } + var name = target.name; + if (ts.isBindingPattern(name)) { + var elements = name.elements; + var numElements = elements.length; + if (numElements !== 1) { + value = ensureIdentifier(value, numElements !== 0, target, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (ts.isOmittedExpression(element)) { + continue; + } + else if (name.kind === 167) { + var propName = element.propertyName || element.name; + emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); + } + else { + if (!element.dotDotDotToken) { + emitBindingElement(element, ts.createElementAccess(value, i)); + } + else if (i === numElements - 1) { + emitBindingElement(element, ts.createArraySlice(value, i)); + } + } + } + } + else { + emitAssignment(name, value, target, target); + } + } + function createDefaultValueCheck(value, defaultValue, location) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53), defaultValue, ts.createToken(54), value); + } + function createDestructuringPropertyAccess(expression, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, false, propertyName, emitTempVariableAssignment)); + } + else if (ts.isLiteralExpression(propertyName)) { + var clone_2 = ts.getSynthesizedClone(propertyName); + clone_2.text = ts.unescapeIdentifier(clone_2.text); + return ts.createElementAccess(expression, clone_2); + } + else { + if (ts.isGeneratedIdentifier(propertyName)) { + var clone_3 = ts.getSynthesizedClone(propertyName); + clone_3.text = ts.unescapeIdentifier(clone_3.text); + return ts.createPropertyAccess(expression, clone_3); + } + else { + return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + } + } + } + } + function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + if (visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + return emitTempVariableAssignment(value, location); + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var USE_NEW_TYPE_METADATA_FORMAT = false; + function transformTypeScript(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentScope; + var currentSourceFileExternalHelpersModuleName; + var enabledSubstitutions; + var classAliases; + var applicableSubstitutions; + var currentSuperContainer; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function saveStateAndInvoke(node, f) { + var savedCurrentScope = currentScope; + onBeforeVisitNode(node); + var visited = f(node); + currentScope = savedCurrentScope; + return visited; + } + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + function visitorWorker(node) { + if (node.kind === 256) { + return visitSourceFile(node); + } + else if (node.transformFlags & 1) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + function namespaceElementVisitorWorker(node) { + if (node.kind === 236 || + node.kind === 230 || + node.kind === 231 || + (node.kind === 229 && + node.moduleReference.kind === 240)) { + return undefined; + } + else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + function classElementVisitorWorker(node) { + switch (node.kind) { + case 148: + return undefined; + case 145: + case 153: + case 149: + case 150: + case 147: + return visitorWorker(node); + case 198: + return node; + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitTypeScript(node) { + if (ts.hasModifier(node, 2) && ts.isStatement(node)) { + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 82: + case 77: + return currentNamespace ? undefined : node; + case 112: + case 110: + case 111: + case 115: + case 118: + case 74: + case 122: + case 128: + case 160: + case 161: + case 159: + case 154: + case 141: + case 117: + case 120: + case 132: + case 130: + case 127: + case 103: + case 133: + case 157: + case 156: + case 158: + case 155: + case 162: + case 163: + case 164: + case 165: + case 166: + case 153: + case 143: + case 223: + case 145: + case 148: + return undefined; + case 222: + return ts.createNotEmittedStatement(node); + case 221: + return visitClassDeclaration(node); + case 192: + return visitClassExpression(node); + case 251: + return visitHeritageClause(node); + case 194: + return visitExpressionWithTypeArguments(node); + case 147: + return visitMethodDeclaration(node); + case 149: + return visitGetAccessor(node); + case 150: + return visitSetAccessor(node); + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + case 180: + return visitArrowFunction(node); + case 142: + return visitParameter(node); + case 178: + return visitParenthesizedExpression(node); + case 177: + case 195: + return visitAssertionExpression(node); + case 196: + return visitNonNullExpression(node); + case 224: + return visitEnumDeclaration(node); + case 184: + return visitAwaitExpression(node); + case 200: + return visitVariableStatement(node); + case 225: + return visitModuleDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 256: + case 227: + case 226: + case 199: + currentScope = node; + break; + } + } + function visitSourceFile(node) { + currentSourceFile = node; + if (node.flags & 31744 + && compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); + var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); + var externalHelpersModuleImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + externalHelpersModuleImport.parent = node; + externalHelpersModuleImport.flags &= ~8; + statements.push(externalHelpersModuleImport); + currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + currentSourceFileExternalHelpersModuleName = undefined; + node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + node.externalHelpersModuleName = externalHelpersModuleName; + } + else { + node = ts.visitEachChild(node, visitor, context); + } + setNodeEmitFlags(node, 1 | node.emitFlags); + return node; + } + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function visitClassDeclaration(node) { + var staticProperties = getInitializedProperties(node, true); + var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; + var isDecoratedClass = shouldEmitDecorateCallForClass(node); + var classAlias; + var name = node.name; + if (!name && staticProperties.length > 0) { + name = ts.getGeneratedNameForNode(node); + } + var statements = []; + if (!isDecoratedClass) { + var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + ts.setOriginalNode(classDeclaration, node); + if (staticProperties.length > 0) { + setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + } + statements.push(classDeclaration); + } + else { + classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); + } + if (staticProperties.length) { + addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, true)); + } + addClassElementDecorationStatements(statements, node, false); + addClassElementDecorationStatements(statements, node, true); + addConstructorDecorationStatement(statements, node, classAlias); + if (isNamespaceExport(node)) { + addExportMemberAssignment(statements, node); + } + else if (isDecoratedClass) { + if (isDefaultExternalModuleExport(node)) { + statements.push(ts.createExportAssignment(undefined, undefined, false, getLocalName(node))); + } + else if (isNamedExternalModuleExport(node)) { + statements.push(createExternalModuleExport(name)); + } + } + return statements; + } + function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + var location = ts.moveRangePastDecorators(node); + var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), location), node); + if (!name) { + name = ts.getGeneratedNameForNode(node); + } + var classAlias; + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + } + var declaredName = getDeclarationName(node, true); + var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) + ]), location); + setCommentRange(transformedClassExpression, node); + statements.push(ts.setOriginalNode(transformedClassExpression, node)); + if (classAlias) { + statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(declaredName, undefined, classAlias) + ]), location), node)); + } + return classAlias; + } + function visitClassExpression(node) { + var staticProperties = getInitializedProperties(node, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, heritageClauses !== undefined); + var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members, node), node); + if (staticProperties.length > 0) { + var expressions = []; + var temp = ts.createTempVariable(hoistVariableDeclaration); + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + } + setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + return classExpression; + } + function transformClassMembers(node, hasExtendsClause) { + var members = []; + var constructor = transformConstructor(node, hasExtendsClause); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.createNodeArray(members, node.members); + } + function transformConstructor(node, hasExtendsClause) { + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = node.transformFlags & 131072; + var constructor = ts.getFirstConstructorWithBody(node); + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor(undefined, undefined, parameters, body, constructor || node), constructor)); + } + function transformConstructorParameters(constructor) { + return constructor + ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) + : []; + } + function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + var statements = []; + var indexOfFirstStatement = 0; + startLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (hasExtendsClause) { + statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + var properties = getInitializedProperties(node, false); + addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + if (constructor) { + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + ts.addRange(statements, endLexicalEnvironment()); + return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined), true); + } + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + var index = ts.addPrologueDirectives(result, statements, false, visitor); + if (index === statements.length) { + return index; + } + var statement = statements[index]; + if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92) + && ts.isIdentifier(parameter.name); + } + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + setNodeEmitFlags(propertyName, 49152 | 1536); + var localName = ts.getMutableClone(name); + setNodeEmitFlags(localName, 49152); + return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); + } + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, true); + } + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, false); + } + function isInitializedProperty(member, isStatic) { + return member.kind === 145 + && isStatic === ts.hasModifier(member, 32) + && member.initializer !== undefined; + } + function addInitializedPropertyStatements(statements, node, properties, receiver) { + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var property = properties_7[_i]; + var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); + setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + setCommentRange(statement, property); + statements.push(statement); + } + } + function generateInitializedPropertyExpressions(node, properties, receiver) { + var expressions = []; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var expression = transformInitializedProperty(node, property, receiver); + expression.startsOnNewLine = true; + setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + setCommentRange(expression, property); + expressions.push(expression); + } + return expressions; + } + function transformInitializedProperty(node, property, receiver) { + var propertyName = visitPropertyNameOfClassElement(property); + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); + return ts.createAssignment(memberAccess, initializer); + } + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + } + function isStaticDecoratedClassElement(member) { + return isDecoratedClassElement(member, true); + } + function isInstanceDecoratedClassElement(member) { + return isDecoratedClassElement(member, false); + } + function isDecoratedClassElement(member, isStatic) { + return ts.nodeOrChildIsDecorated(member) + && isStatic === ts.hasModifier(member, 32); + } + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 149: + case 150: + return getAllDecoratorsOfAccessors(node, member); + case 147: + return getAllDecoratorsOfMethod(member); + case 145: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + if (accessor !== firstAccessor) { + return undefined; + } + var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + function transformAllDecoratorsOfDeclaration(node, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, decoratorExpressions); + return decoratorExpressions; + } + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, true); + var descriptor = languageVersion > 0 + ? member.kind === 145 + ? ts.createVoidZero() + : ts.createNull() + : undefined; + var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + setNodeEmitFlags(helper, 49152); + return helper; + } + function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { + var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + if (expression) { + statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + } + } + function generateConstructorDecorationExpression(node, decoratedClassAlias) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + if (decoratedClassAlias) { + var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); + var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152); + return result; + } + else { + var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152); + return result; + } + } + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); + setNodeEmitFlags(helper, 49152); + expressions.push(helper); + } + } + return expressions; + } + function addTypeMetadata(node, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, decoratorExpressions); + } + else { + addOldTypeMetadata(node, decoratorExpressions); + } + } + function addOldTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeParameterTypesOfNode(node)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); + } + } + } + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 147 + || kind === 149 + || kind === 150 + || kind === 145; + } + function shouldAddReturnTypeMetadata(node) { + return node.kind === 147; + } + function shouldAddParamTypesMetadata(node) { + var kind = node.kind; + return kind === 221 + || kind === 192 + || kind === 147 + || kind === 149 + || kind === 150; + } + function serializeTypeOfNode(node) { + switch (node.kind) { + case 145: + case 142: + case 149: + return serializeTypeNode(node.type); + case 150: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 221: + case 192: + case 147: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + function getRestParameterElementType(node) { + if (node && node.kind === 160) { + return node.elementType; + } + else if (node && node.kind === 155) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + function serializeParameterTypesOfNode(node) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = valueDeclaration.parameters; + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunctionLike(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 103: + return ts.createVoidZero(); + case 164: + return serializeTypeNode(node.type); + case 156: + case 157: + return ts.createIdentifier("Function"); + case 160: + case 161: + return ts.createIdentifier("Array"); + case 154: + case 120: + return ts.createIdentifier("Boolean"); + case 132: + return ts.createIdentifier("String"); + case 166: + switch (node.literal.kind) { + case 9: + return ts.createIdentifier("String"); + case 8: + return ts.createIdentifier("Number"); + case 99: + case 84: + return ts.createIdentifier("Boolean"); + default: + ts.Debug.failBadSyntaxKind(node.literal); + break; + } + break; + case 130: + return ts.createIdentifier("Number"); + case 133: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 155: + return serializeTypeReferenceNode(node); + case 158: + case 159: + case 162: + case 163: + case 117: + case 165: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + return ts.createIdentifier("Object"); + } + function serializeTypeReferenceNode(node) { + switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + case ts.TypeReferenceSerializationKind.Unknown: + var serialized = serializeEntityNameAsExpression(node.typeName, true); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName, false); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + default: + return ts.createIdentifier("Object"); + } + } + function serializeEntityNameAsExpression(node, useFallback) { + switch (node.kind) { + case 69: + var name_29 = ts.getMutableClone(node); + name_29.flags &= ~8; + name_29.original = undefined; + name_29.parent = currentScope; + if (useFallback) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + } + return name_29; + case 139: + return serializeQualifiedNameAsExpression(node, useFallback); + } + } + function serializeQualifiedNameAsExpression(node, useFallback) { + var left; + if (node.left.kind === 69) { + left = serializeEntityNameAsExpression(node.left, useFallback); + } + else if (useFallback) { + var temp = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, true)), temp); + } + else { + left = serializeEntityNameAsExpression(node.left, false); + } + return ts.createPropertyAccess(left, node.right); + } + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53), ts.createIdentifier("Symbol"), ts.createToken(54), ts.createIdentifier("Object")); + } + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(name.text); + } + else { + return ts.getSynthesizedClone(name); + } + } + function visitPropertyNameOfClassElement(member) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + if (member.decorators) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + expression = ts.createAssignment(generatedName, expression); + } + return ts.setOriginalNode(ts.createComputedPropertyName(expression, name), name); + } + else { + return name; + } + } + function visitHeritageClause(node) { + if (node.token === 83) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.createHeritageClause(83, types, node); + } + return undefined; + } + function visitExpressionWithTypeArguments(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createExpressionWithTypeArguments(undefined, expression, node); + } + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + setCommentRange(method, node); + setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(method, node); + return method; + } + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); + } + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var func = ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + if (isNamespaceExport(node)) { + var statements = [func]; + addExportMemberAssignment(statements, node); + return statements; + } + return func; + } + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + var func = ts.createFunctionExpression(node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + return func; + } + function visitArrowFunction(node) { + var func = ts.createArrowFunction(undefined, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.equalsGreaterThanToken, transformConciseBody(node), node); + ts.setOriginalNode(func, node); + return func; + } + function transformFunctionBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformFunctionBodyWorker(node.body); + } + function transformFunctionBodyWorker(body, start) { + if (start === void 0) { start = 0; } + var savedCurrentScope = currentScope; + currentScope = body; + startLexicalEnvironment(); + var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); + var visited = ts.updateBlock(body, statements); + var declarations = endLexicalEnvironment(); + currentScope = savedCurrentScope; + return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + } + function transformConciseBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformConciseBodyWorker(node.body, false); + } + function transformConciseBodyWorker(body, forceBlockFunctionBody) { + if (ts.isBlock(body)) { + return transformFunctionBodyWorker(body); + } + else { + startLexicalEnvironment(); + var visited = ts.visitNode(body, visitor, ts.isConciseBody); + var declarations = endLexicalEnvironment(); + var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + if (forceBlockFunctionBody && !ts.isBlock(merged)) { + return ts.createBlock([ + ts.createReturn(merged) + ]); + } + else { + return merged; + } + } + } + function getPromiseConstructor(type) { + var typeName = ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function transformAsyncFunctionBody(node) { + var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(node.type) : undefined; + var isArrowFunction = node.kind === 180; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); + statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + var block = ts.createBlock(statements, node.body, true); + if (languageVersion >= 2) { + if (resolver.getNodeCheckFlags(node) & 4096) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 8); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 4); + } + } + return block; + } + else { + return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, true)); + } + } + function visitParameter(node) { + if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + return undefined; + } + var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); + ts.setOriginalNode(parameter, node); + setCommentRange(parameter, node); + setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + setNodeEmitFlags(parameter.name, 1024); + return parameter; + } + function visitVariableStatement(node) { + if (isNamespaceExport(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + } + else { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), node); + } + } + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + } + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2); + if (ts.isAssertionExpression(innerExpression)) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function shouldEmitEnumDeclaration(node) { + return !ts.isConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + function shouldEmitVarForEnumDeclaration(node) { + return !ts.hasModifier(node, 1) + || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + } + function addVarForEnumExportedFromNamespace(statements, node) { + var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); + setSourceMapRange(statement, node); + statements.push(statement); + } + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + var emitFlags = 64; + if (shouldEmitVarForEnumDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = getExportName(node); + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); + ts.setOriginalNode(enumStatement, node); + setNodeEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + if (isNamespaceExport(node)) { + addVarForEnumExportedFromNamespace(statements, node); + } + return statements; + } + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, ts.map(node.members, transformEnumMember)); + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); + } + function transformEnumMember(member) { + var name = getExpressionForPropertyName(member, false); + return ts.createStatement(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name, member), member); + } + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + function isModuleMergedWithES6Class(node) { + return languageVersion === 2 + && ts.isMergedWithClass(node); + } + function isES6ExportedDeclaration(node) { + return isExternalModuleExport(node) + && moduleKind === ts.ModuleKind.ES6; + } + function shouldEmitVarForModuleDeclaration(node) { + return !isModuleMergedWithES6Class(node) + && (!isES6ExportedDeclaration(node) + || ts.isFirstDeclarationOfKind(node, node.kind)); + } + function addVarForEnumOrModuleDeclaration(statements, node) { + var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) + ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) + : undefined, [ + ts.createVariableDeclaration(getDeclarationName(node, false, true)) + ]); + ts.setOriginalNode(statement, node); + if (node.kind === 224) { + setSourceMapRange(statement.declarationList, node); + } + else { + setSourceMapRange(statement, node); + } + setCommentRange(statement, node); + setNodeEmitFlags(statement, 32768); + statements.push(statement); + } + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + var emitFlags = 64; + if (shouldEmitVarForModuleDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = getExportName(node); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (ts.hasModifier(node, 1) && !isES6ExportedDeclaration(node)) { + var localName = getLocalName(node); + moduleArg = ts.createAssignment(localName, moduleArg); + } + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); + ts.setOriginalNode(moduleStatement, node); + setNodeEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + return statements; + } + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 226) { + ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); + if (body.kind !== 226) { + setNodeEmitFlags(block, block.emitFlags | 49152); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 225) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function shouldEmitImportEqualsDeclaration(node) { + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + return ts.visitEachChild(node, visitor, context); + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + setNodeEmitFlags(moduleReference, 49152 | 65536); + if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(node.name, undefined, moduleReference) + ]), node), node); + } + else { + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + function isNamespaceExport(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1); + } + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1); + } + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512); + } + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512); + } + function expressionToStatement(expression) { + return ts.createStatement(expression, undefined); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); + setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var statement = ts.createStatement(expression); + setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, false, true), exportValue), location); + } + function createExternalModuleExport(exportName) { + return ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([ + ts.createExportSpecifier(exportName) + ])); + } + function getNamespaceMemberName(name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), name); + var emitFlags; + if (!allowComments) { + emitFlags |= 49152; + } + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (emitFlags) { + setNodeEmitFlags(qualifiedName, emitFlags); + } + return qualifiedName; + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return getNamespaceMemberName(name, false, true); + } + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + setSourceMapRange(name, node.name); + return name; + } + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + function getLocalName(node, noSourceMaps, allowComments) { + return getDeclarationName(node, allowComments, !noSourceMaps, 262144); + } + function getExportName(node, noSourceMaps, allowComments) { + if (isNamespaceExport(node)) { + return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); + } + return getDeclarationName(node, allowComments, !noSourceMaps, 131072); + } + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name) { + var name_30 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (!allowComments) { + emitFlags |= 49152; + } + if (emitFlags) { + setNodeEmitFlags(name_30, emitFlags); + } + return name_30; + } + else { + return ts.getGeneratedNameForNode(node); + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32) + ? getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8) === 0) { + enabledSubstitutions |= 8; + context.enableSubstitution(69); + } + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 4) === 0) { + enabledSubstitutions |= 4; + context.enableSubstitution(174); + context.enableSubstitution(172); + context.enableSubstitution(173); + context.enableEmitNotification(221); + context.enableEmitNotification(147); + context.enableEmitNotification(149); + context.enableEmitNotification(150); + context.enableEmitNotification(148); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(69); + classAliases = ts.createMap(); + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(69); + context.enableSubstitution(254); + context.enableEmitNotification(225); + } + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 221 + || kind === 148 + || kind === 147 + || kind === 149 + || kind === 150; + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 225; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 224; + } + function onEmitNode(node, emit) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSuperContainer = currentSuperContainer; + if (enabledSubstitutions & 4 && isSuperContainer(node)) { + currentSuperContainer = node; + } + if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2; + } + if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8; + } + previousOnEmitNode(node, emit); + applicableSubstitutions = savedApplicableSubstitutions; + currentSuperContainer = savedCurrentSuperContainer; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2) { + var name_31 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_31); + if (exportedName) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name_31, initializer, node); + } + return ts.createPropertyAssignment(name_31, exportedName, node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + } + if (enabledSubstitutions & 4) { + switch (node.kind) { + case 174: + return substituteCallExpression(node); + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1) { + if (resolver.getNodeCheckFlags(node) & 16777216) { + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; + if (classAlias) { + var clone_4 = ts.getSynthesizedClone(classAlias); + setSourceMapRange(clone_4, node); + setCommentRange(clone_4, node); + return clone_4; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + var container = resolver.getReferencedExportContainer(node, false); + if (container) { + var substitute = (applicableSubstitutions & 2 && container.kind === 225) || + (applicableSubstitutions & 8 && container.kind === 224); + if (substitute) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, node); + } + } + } + return undefined; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 95) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 95) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + } + } + ts.transformTypeScript = transformTypeScript; +})(ts || (ts = {})); +var ts; +(function (ts) { + var entities = createEntitiesMap(); + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + return node; + } + function visitor(node) { + if (node.transformFlags & 4) { + return visitorWorker(node); + } + else if (node.transformFlags & 8) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 241: + return visitJsxElement(node, false); + case 242: + return visitJsxSelfClosingElement(node, false); + case 248: + return visitJsxExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 244: + return visitJsxText(node); + case 248: + return visitJsxExpression(node); + case 241: + return visitJsxElement(node, true); + case 242: + return visitJsxSelfClosingElement(node, true); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, undefined, isChild, node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes; + if (attrs.length === 0) { + objectProperties = ts.createNull(); + } + else { + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + segments.unshift(ts.createObjectLiteral()); + } + objectProperties = ts.singleOrUndefined(segments) + || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + } + var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createLiteral(true); + } + else if (node.kind === 9) { + var decoded = tryDecodeEntities(node.text); + return decoded ? ts.createLiteral(decoded, node) : node; + } + else if (node.kind === 248) { + return visitJsxExpression(node); + } + else { + ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var text = ts.getTextOfNode(node, true); + var parts; + var firstNonWhitespace = 0; + var lastNonWhitespace = -1; + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { + var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + if (!parts) { + parts = []; + } + parts.push(ts.createLiteral(decodeEntities(part))); + } + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpace(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + if (firstNonWhitespace !== -1) { + var part = text.substr(firstNonWhitespace); + if (!parts) { + parts = []; + } + parts.push(ts.createLiteral(decodeEntities(part))); + } + if (parts) { + return ts.reduceLeft(parts, aggregateJsxTextParts); + } + return undefined; + } + function aggregateJsxTextParts(left, right) { + return ts.createAdd(ts.createAdd(left, ts.createLiteral(" ")), right); + } + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities[word]; + return ch ? String.fromCharCode(ch) : match; + } + }); + } + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 241) { + return getTagName(node.openingElement); + } + else { + var name_32 = node.tagName; + if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { + return ts.createLiteral(name_32.text); + } + else { + return ts.createExpressionFromEntityName(name_32); + } + } + } + function getAttributeName(node) { + var name = node.name; + if (/^[A-Za-z_]\w*$/.test(name.text)) { + return name; + } + else { + return ts.createLiteral(name.text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + function createEntitiesMap() { + return ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES7(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if (node.transformFlags & 16) { + return visitorWorker(node); + } + else if (node.transformFlags & 32) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 187: + return visitBinaryExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (node.operatorToken.kind === 60) { + var target = void 0; + var value = void 0; + if (ts.isElementAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); + } + else if (ts.isPropertyAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); + value = ts.createPropertyAccess(expressionTemp, left.name, left); + } + else { + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, node), node); + } + else if (node.operatorToken.kind === 38) { + return ts.createMathPow(left, right, node); + } + else { + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + } + ts.transformES7 = transformES7; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES6(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + var convertedLoopState; + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64) !== 0 || + node.kind === 214 || + (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { + switch (node.kind) { + case 211: + return visitReturnStatement(node); + case 200: + return visitVariableStatement(node); + case 213: + return visitSwitchStatement(node); + case 210: + case 209: + return visitBreakOrContinueStatement(node); + case 97: + return visitThisKeyword(node); + case 69: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 82: + return node; + case 221: + return visitClassDeclaration(node); + case 192: + return visitClassExpression(node); + case 142: + return visitParameter(node); + case 220: + return visitFunctionDeclaration(node); + case 180: + return visitArrowFunction(node); + case 179: + return visitFunctionExpression(node); + case 218: + return visitVariableDeclaration(node); + case 69: + return visitIdentifier(node); + case 219: + return visitVariableDeclarationList(node); + case 214: + return visitLabeledStatement(node); + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 208: + return visitForOfStatement(node); + case 202: + return visitExpressionStatement(node); + case 171: + return visitObjectLiteralExpression(node); + case 254: + return visitShorthandPropertyAssignment(node); + case 170: + return visitArrayLiteralExpression(node); + case 174: + return visitCallExpression(node); + case 175: + return visitNewExpression(node); + case 178: + return visitParenthesizedExpression(node, true); + case 187: + return visitBinaryExpression(node, true); + case 11: + case 12: + case 13: + case 14: + return visitTemplateLiteral(node); + case 176: + return visitTaggedTemplateExpression(node); + case 189: + return visitTemplateExpression(node); + case 190: + return visitYieldExpression(node); + case 95: + return visitSuperKeyword(node); + case 190: + return ts.visitEachChild(node, visitor, context); + case 147: + return visitMethodDeclaration(node); + case 256: + return visitSourceFileNode(node); + case 200: + return visitVariableStatement(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 180) { + enclosingNonArrowFunction = currentNode; + if (!(currentNode.emitFlags & 2097152)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + switch (currentNode.kind) { + case 200: + enclosingVariableStatement = currentNode; + break; + case 219: + case 218: + case 169: + case 167: + case 168: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps |= 2; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 180) { + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + var jump = node.kind === 210 ? 2 : 4; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 210) { + convertedLoopState.nonLocalJumps |= 2; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4; + labelMarker = "continue"; + } + } + else { + if (node.kind === 210) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 24, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 24, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitClassDeclaration(node) { + var modifierFlags = ts.getModifierFlags(node); + var isExported = modifierFlags & 1; + var isDefault = modifierFlags & 512; + var modifiers = isExported && !isDefault + ? ts.filter(node.modifiers, isExportModifier) + : undefined; + var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(getDeclarationName(node, true), undefined, transformClassLikeDeclarationToExpression(node)) + ]), node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + if (isExported && isDefault) { + var statements = [statement]; + statements.push(ts.createExportAssignment(undefined, undefined, false, getDeclarationName(node, false))); + return statements; + } + return statement; + } + function isExportModifier(node) { + return node.kind === 82; + } + function visitClassExpression(node) { + return transformClassLikeDeclarationToExpression(node); + } + function transformClassLikeDeclarationToExpression(node) { + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); + if (getNodeEmitFlags(node) & 524288) { + setNodeEmitFlags(classFunction, 524288); + } + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + setNodeEmitFlags(inner, 49152); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + setNodeEmitFlags(outer, 49152); + return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16); + var localName = getLocalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + setNodeEmitFlags(outer, 49152); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + setNodeEmitFlags(statement, 49152 | 12288); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); + setNodeEmitFlags(block, 49152); + return block; + } + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), extendsClauseElement)); + } + } + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + } + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + if (constructor && !hasSynthesizedSuper) { + return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); + } + return []; + } + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + startLexicalEnvironment(); + if (constructor) { + addCaptureThisForNodeIfNeeded(statements, constructor); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + } + addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); + if (constructor) { + var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + ts.addRange(statements, body); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); + if (!constructor) { + setNodeEmitFlags(block, 49152); + } + return block; + } + function transformConstructorBodyWithSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); + } + function transformConstructorBodyWithoutSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + } + function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { + if (constructor ? hasSynthesizedSuper : extendsClauseElement) { + statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + } + } + function visitParameter(node) { + if (node.dotDotDotToken) { + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), undefined, node), node); + } + else if (node.initializer) { + return ts.setOriginalNode(ts.createParameter(node.name, undefined, node), node); + } + else { + return node; + } + } + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536) !== 0; + } + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_33)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + } + } + } + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + if (name.elements.length > 0) { + statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + } + else if (initializer) { + statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + } + } + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + ], parameter), 32 | 1024 | 12288), undefined, parameter); + statement.startsOnNewLine = true; + setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + statements.push(statement); + } + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 69 && !inConstructorWithSynthesizedSuper; + } + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + var declarationName = ts.getMutableClone(parameter.name); + setNodeEmitFlags(declarationName, 1536); + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) + ]), parameter), 8388608)); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) + ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) + ])); + setNodeEmitFlags(forStatement, 8388608); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 && node.kind !== 180) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, ts.createThis()) + ])); + setNodeEmitFlags(captureThisStatement, 49152 | 8388608); + setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + } + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 198: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 147: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 149: + case 150: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 148: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(member); + } + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = getCommentRange(member); + var sourceMapRange = getSourceMapRange(member); + var func = transformFunctionLikeToExpression(member, member, undefined); + setNodeEmitFlags(func, 49152); + setSourceMapRange(func, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); + ts.setOriginalNode(statement, member); + setCommentRange(statement, commentRange); + setNodeEmitFlags(statement, 1536); + return statement; + } + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); + setNodeEmitFlags(statement, 49152); + return statement; + } + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var target = ts.getMutableClone(receiver); + setNodeEmitFlags(target, 49152 | 1024); + setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + setNodeEmitFlags(propertyName, 49152 | 512); + setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); + setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + var getter = ts.createPropertyAssignment("get", getterFunction); + setCommentRange(getter, getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); + setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + var setter = ts.createPropertyAssignment("set", setterFunction); + setCommentRange(setter, getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, undefined, true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + function visitArrowFunction(node) { + if (node.transformFlags & 8192) { + enableSubstitutionsForCapturedThis(); + } + var func = transformFunctionLikeToExpression(node, node, undefined); + setNodeEmitFlags(func, 256); + return func; + } + function visitFunctionExpression(node) { + return transformFunctionLikeToExpression(node, node, node.name); + } + function visitFunctionDeclaration(node) { + return ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node), node); + } + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 180) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + function transformFunctionBody(node) { + var multiLine = false; + var singleLine = false; + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + startLexicalEnvironment(); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, false); + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 180); + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, body); + setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + statements.push(returnStatement); + closeBraceLocation = body; + } + var lexicalEnvironment = endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + setNodeEmitFlags(block, 32); + } + if (closeBraceLocation) { + setTokenSourceMapRange(block, 16, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitExpressionStatement(node) { + switch (node.expression.kind) { + case 178: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); + case 187: + return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParenthesizedExpression(node, needsDestructuringValue) { + if (needsDestructuringValue) { + switch (node.expression.kind) { + case 178: + return ts.createParen(visitParenthesizedExpression(node.expression, true), node); + case 187: + return ts.createParen(visitBinaryExpression(node.expression, true), node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitBinaryExpression(node, needsDestructuringValue) { + ts.Debug.assert(ts.isDestructuringAssignment(node)); + return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3) == 0) { + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); + } + else { + assignment = ts.createBinary(decl.name, 56, decl.initializer); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24, acc); }), node); + } + else { + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclarationList(node) { + if (node.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, node); + ts.setOriginalNode(declarationList, node); + setCommentRange(declarationList, node); + if (node.transformFlags & 2097152 + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + function shouldEmitExplicitInitializerForLetDeclaration(node) { + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072; + var isDeclaredInLoop = flags & 262144; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 207 + && enclosingBlockScopeContainer.kind !== 208 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, false))); + return emitExplicitInitializer; + } + function visitVariableDeclarationInLetDeclarationList(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_5 = ts.getMutableClone(node); + clone_5.initializer = ts.createVoidZero(); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name)) { + var recordTempVariablesInLine = !enclosingVariableStatement + || !ts.hasModifier(enclosingVariableStatement, 1); + return ts.flattenVariableDestructuring(context, node, undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 69 + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(undefined); + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); + var declarationList = ts.createVariableDeclarationList(declarations, initializer); + ts.setOriginalNode(declarationList, initializer); + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement(undefined, declarationList)); + } + else { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, ts.createElementAccess(rhsReference, counter)) + ], ts.moveRangePos(initializer, -1)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); + if (ts.isDestructuringAssignment(assignment)) { + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, false, hoistVariableDeclaration, visitor))); + } + else { + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); + setNodeEmitFlags(body, 1536 | 12288); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) + ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); + setNodeEmitFlags(forStatement, 8192); + return forStatement; + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var numProperties = properties.length; + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 4194304 + || property.name.kind === 140) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var expressions = []; + var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536) !== 0; + } + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 69) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 | 4; + } + var result = convert ? convert(node, undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 206: + case 207: + case 208: + var initializer = node.initializer; + if (initializer && initializer.kind === 219) { + loopInitializer = initializer; + } + break; + } + var loopParameters = []; + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + if (outerConvertedLoopState.argumentsName) { + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length) { + var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + copyOutParameters(loopOutParameters, 1, statements_3); + loopBody = ts.createBlock(statements_3, undefined, true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], undefined, true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (node.statement.transformFlags & 4194304) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 256; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 2097152; + } + var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ])); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + if (currentState.argumentsName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + if (outerConvertedLoopState) { + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var name_34 in currentState.hoistedLocalVariables) { + var identifier = currentState.hoistedLocalVariables[name_34]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { + var outParam = loopOutParameters_1[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + loop.statement = undefined; + loop = ts.visitEachChild(loop, visitor, context); + loop.statement = ts.createBlock(convertedLoopBodyStatements, undefined, true); + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 214 + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 56, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + var isSimpleLoop = !(state.nonLocalJumps & ~4) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0, statements); + if (state.nonLocalJumps & 8) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 32, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(name)); + if (resolver.getNodeCheckFlags(decl) & 2097152) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 149: + case 150: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 253: + expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 254: + expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 147: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined), method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function visitMethodDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); + setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, node); + } + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), node); + } + function visitYieldExpression(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitArrayLiteralExpression(node) { + return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); + } + function visitCallExpression(node) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.transformFlags & 262144) { + return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + } + else { + return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + } + } + function visitNewExpression(node) { + ts.Debug.assert((node.transformFlags & 262144) !== 0); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); + } + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpreadElement(node) { + return ts.isSpreadElementExpression(node) + ? visitSpanOfSpreadElements + : visitSpanOfNonSpreadElements; + } + function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.map(chunk, visitExpressionOfSpreadElement); + } + function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, undefined, hasTrailingComma), visitor, ts.isExpression), undefined, multiLine); + } + function visitExpressionOfSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, node); + } + function visitTaggedTemplateExpression(node) { + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, undefined, templateArguments) + ])); + } + function getRawLiteral(node) { + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + var isLast = node.kind === 11 || node.kind === 14; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, node); + } + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + function shouldAddTemplateHead(node) { + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + function visitSuperKeyword(node) { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32) + && currentParent.kind !== 174 + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + function visitSourceFileNode(node) { + var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, prologue); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); + ts.addRange(statements, endLexicalEnvironment()); + var clone = ts.getMutableClone(node); + clone.statements = ts.createNodeArray(statements, node.statements); + return clone; + } + function onEmitNode(node, emit) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { + enclosingFunction = node; + } + previousOnEmitNode(node, emit); + enclosingFunction = savedEnclosingFunction; + } + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(69); + } + } + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(97); + context.enableEmitNotification(148); + context.enableEmitNotification(147); + context.enableEmitNotification(149); + context.enableEmitNotification(150); + context.enableEmitNotification(180); + context.enableEmitNotification(179); + context.enableEmitNotification(220); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + function substituteIdentifier(node) { + if (enabledSubstitutions & 2) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 169: + case 221: + case 224: + case 218: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 97: + return substituteThisKeyword(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 + && enclosingFunction + && enclosingFunction.emitFlags & 256) { + return ts.createIdentifier("_this", node); + } + return node; + } + function getLocalName(node, allowComments, allowSourceMaps) { + return getDeclarationName(node, allowComments, allowSourceMaps, 262144); + } + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && !ts.isGeneratedIdentifier(node.name)) { + var name_35 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (!allowComments) { + emitFlags |= 49152; + } + if (emitFlags) { + setNodeEmitFlags(name_35, emitFlags); + } + return name_35; + } + return ts.getGeneratedNameForNode(node); + } + function getClassMemberPrefix(node, member) { + var expression = getLocalName(node); + return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + var parameter = ts.singleOrUndefined(constructor.parameters); + if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression === parameter.name; + } + } + ts.transformES6 = transformES6; +})(ts || (ts = {})); +var ts; +(function (ts) { + var instructionNames = ts.createMap((_a = {}, + _a[2] = "return", + _a[3] = "break", + _a[4] = "yield", + _a[5] = "yield*", + _a[7] = "endfinally", + _a)); + function transformGenerators(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + var blocks; + var blockOffsets; + var blockActions; + var blockStack; + var labelOffsets; + var labelExpressions; + var nextLabelId = 1; + var operations; + var operationArguments; + var operationLocations; + var state; + var blockIndex = 0; + var labelNumber = 0; + var labelNumbers; + var lastOperationWasAbrupt; + var lastOperationWasCompletion; + var clauses; + var statements; + var exceptionBlockStack; + var currentExceptionBlock; + var withBlockStack; + return transformSourceFile; + function transformSourceFile(node) { + if (node.transformFlags & 1024) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + } + return node; + } + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 512) { + return visitGenerator(node); + } + else if (transformFlags & 1024) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 213: + return visitSwitchStatement(node); + case 214: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + case 149: + case 150: + return visitAccessorDeclaration(node); + case 200: + return visitVariableStatement(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 210: + return visitBreakStatement(node); + case 209: + return visitContinueStatement(node); + case 211: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (1024 | 8388608)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 187: + return visitBinaryExpression(node); + case 188: + return visitConditionalExpression(node); + case 190: + return visitYieldExpression(node); + case 170: + return visitArrayLiteralExpression(node); + case 171: + return visitObjectLiteralExpression(node); + case 173: + return visitElementAccessExpression(node); + case 174: + return visitCallExpression(node); + case 175: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitGenerator(node) { + switch (node.kind) { + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitFunctionDeclaration(node) { + if (node.asteriskToken && node.emitFlags & 2097152) { + node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + function visitFunctionExpression(node) { + if (node.asteriskToken && node.emitFlags & 2097152) { + node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + function transformGeneratorFunctionBody(body) { + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(undefined); + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addRange(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.createBlock(statements, body, body.multiLine); + } + function visitVariableStatement(node) { + if (node.transformFlags & 4194304) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + if (node.emitFlags & 8388608) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + } + } + function visitBinaryExpression(node) { + switch (ts.getExpressionAssociativity(node)) { + case 0: + return visitLeftAssociativeBinaryExpression(node); + case 1: + return visitRightAssociativeBinaryExpression(node); + default: + ts.Debug.fail("Unknown associativity."); + } + } + function isCompoundAssignment(kind) { + return kind >= 57 + && kind <= 68; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 57: return 35; + case 58: return 36; + case 59: return 37; + case 60: return 38; + case 61: return 39; + case 62: return 40; + case 63: return 43; + case 64: return 44; + case 65: return 45; + case 66: return 46; + case 67: return 47; + case 68: return 48; + } + } + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 172: + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 173: + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.createBinary(target, 56, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 24) { + return visitCommaExpression(node); + } + var clone_6 = ts.getMutableClone(node); + clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitLogicalBinaryExpression(node) { + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); + if (node.operatorToken.kind === 51) { + emitBreakWhenFalse(resultLabel, resultLocal, node.left); + } + else { + emitBreakWhenTrue(resultLabel, resultLocal, node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), node.right); + markLabel(resultLabel); + return resultLocal; + } + function visitCommaExpression(node) { + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + function visitConditionalExpression(node) { + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + emitYieldStar(expression, node); + } + else { + emitYield(expression, node); + } + markLabel(resumeLabel); + return createGeneratorResume(); + } + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, node.multiLine); + } + function visitElements(elements, multiLine) { + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp = declareLocal(); + var hasAssignedTemp = false; + if (numInitialElements > 0) { + emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + hasAssignedTemp = true; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions)); + hasAssignedTemp = true; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + visited.startsOnNewLine = true; + } + expressions.push(visited); + } + return expressions; + } + } + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + var clone_7 = ts.getMutableClone(node); + clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_7; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, false), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, false)), undefined, [], node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 199: + return transformAndEmitBlock(node); + case 202: + return transformAndEmitExpressionStatement(node); + case 203: + return transformAndEmitIfStatement(node); + case 204: + return transformAndEmitDoStatement(node); + case 205: + return transformAndEmitWhileStatement(node); + case 206: + return transformAndEmitForStatement(node); + case 207: + return transformAndEmitForInStatement(node); + case 209: + return transformAndEmitContinueStatement(node); + case 210: + return transformAndEmitBreakStatement(node); + case 211: + return transformAndEmitReturnStatement(node); + case 212: + return transformAndEmitWithStatement(node); + case 213: + return transformAndEmitSwitchStatement(node); + case 214: + return transformAndEmitLabeledStatement(node); + case 215: + return transformAndEmitThrowStatement(node); + case 216: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement, true)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression, true), ts.visitNode(node.incrementor, visitor, ts.isExpression, true), ts.visitNode(node.statement, visitor, ts.isStatement, false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + if (containsYield(node)) { + var keysArray = declareLocal(); + var key = declareLocal(); + var keysIndex = ts.createLoopVariable(); + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); + emitBreak(label, node); + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); + emitBreak(label, node); + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression, true), node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression, true), node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 250 && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 249) { + var caseClause = clause; + if (containsYield(caseClause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(caseClause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], caseClause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + beginLabeledBlock(node.label.text); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(node.label.text); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return node && (node.transformFlags & 4194304) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (renamedCatchVariables && ts.hasProperty(renamedCatchVariables, node.text)) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_36) { + var clone_8 = ts.getMutableClone(name_36); + setSourceMapRange(clone_8, node); + setCommentRange(clone_8, node); + return clone_8; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node)) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(undefined); + hoistVariableDeclaration(temp); + return temp; + } + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + function endBlock() { + var block = peekBlock(); + ts.Debug.assert(block !== undefined, "beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1); + var block = endBlock(); + markLabel(block.endLabel); + } + function isWithBlock(block) { + return block.kind === 1; + } + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0, + state: 0, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0); + var text = variable.name.text; + var name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = ts.createMap(); + context.enableSubstitution(69); + } + renamedCatchVariables[text] = true; + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [])); + emitNop(); + } + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2; + exception.finallyLabel = finallyLabel; + } + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = endBlock(); + var state = exception.state; + if (state < 2) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3; + } + function isExceptionBlock(block) { + return block.kind === 0; + } + function beginScriptLoopBlock() { + beginBlock({ + kind: 3, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel + }); + return breakLabel; + } + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2, + isScript: true, + breakLabel: -1 + }); + } + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2, + isScript: false, + breakLabel: breakLabel + }); + return breakLabel; + } + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + function supportsUnlabeledBreak(block) { + return block.kind === 2 + || block.kind === 3; + } + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4; + } + function supportsUnlabeledContinue(block) { + return block.kind === 3; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + function findBreakTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + return 0; + } + function findContinueTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + return 0; + } + function createLabel(label) { + if (label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createSynthesizedNode(8); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createNode(193); + } + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + literal.trailingComment = instructionNames[instruction]; + return literal; + } + function createInlineBreak(label, location) { + ts.Debug.assert(label > 0, "Invalid label: " + label); + return ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), location); + } + function createInlineReturn(expression, location) { + return ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)]), location); + } + function createGeneratorResume(location) { + return ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [], location); + } + function emitNop() { + emitWorker(0); + } + function emitStatement(node) { + if (node) { + emitWorker(1, [node]); + } + else { + emitNop(); + } + } + function emitAssignment(left, right, location) { + emitWorker(2, [left, right], location); + } + function emitBreak(label, location) { + emitWorker(3, [label], location); + } + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4, [label, condition], location); + } + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5, [label, condition], location); + } + function emitYieldStar(expression, location) { + emitWorker(7, [expression], location); + } + function emitYield(expression, location) { + emitWorker(6, [expression], location); + } + function emitReturn(expression, location) { + emitWorker(8, [expression], location); + } + function emitThrow(expression, location) { + emitWorker(9, [expression], location); + } + function emitEndfinally() { + emitWorker(10); + } + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ + ts.createThis(), + setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ]); + } + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + switchStatement.startsOnNewLine = true; + return [switchStatement]; + } + if (statements) { + return statements; + } + return []; + } + function flushLabel() { + if (!statements) { + return; + } + appendLabel(!lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(undefined, undefined); + } + if (statements && clauses) { + appendLabel(false); + } + updateLabelExpressions(); + } + function isFinalLabelReachable(operationIndex) { + if (!lastOperationWasCompletion) { + return true; + } + if (!labelOffsets || !labelExpressions) { + return false; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + if (isExceptionBlock(block)) { + if (blockAction === 0) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + } + else if (isWithBlock(block)) { + if (blockAction === 0) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1) { + withBlockStack.pop(); + } + } + } + } + } + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0) { + return; + } + else if (opcode === 10) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2: + return writeAssign(args[0], args[1], location); + case 3: + return writeBreak(args[0], location); + case 4: + return writeBreakWhenTrue(args[0], args[1], location); + case 5: + return writeBreakWhenFalse(args[0], args[1], location); + case 6: + return writeYield(args[0], location); + case 7: + return writeYieldStar(args[0], location); + case 8: + return writeReturn(args[0], location); + case 9: + return writeThrow(args[0], location); + } + } + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + function writeAssign(left, right, operationLocation) { + writeStatement(ts.createStatement(ts.createAssignment(left, right), operationLocation)); + } + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createThrow(expression, operationLocation)); + } + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)]), operationLocation)); + } + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation)); + } + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.createIf(condition, ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation))); + } + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.createIf(ts.createLogicalNot(condition), ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation))); + } + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4), expression] + : [createInstruction(4)]), operationLocation)); + } + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5), + expression + ]), operationLocation)); + } + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7) + ]))); + } + } + ts.transformGenerators = transformGenerators; + var _a; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69); + context.enableSubstitution(187); + context.enableSubstitution(185); + context.enableSubstitution(186); + context.enableSubstitution(254); + context.enableEmitNotification(256); + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var bindingNameExportSpecifiersMap; + var bindingNameExportSpecifiersForFileMap = ts.createMap(); + var hasExportStarsToExportValues; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule_1(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + return updated; + } + return node; + var _a; + } + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, false); + var updated = updateSourceFile(node, statements); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + } + return updated; + } + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, true); + } + function transformUMDModule(node) { + var define = ts.createIdentifier("define"); + setNodeEmitFlags(define, 16); + return transformAsynchronousModule(node, define, undefined, false); + } + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createFunctionExpression(undefined, undefined, undefined, [ + ts.createParameter("require"), + ts.createParameter("exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + ]))) + ]); + } + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, true); + var body = ts.createBlock(statements, undefined, true); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(body, 2); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (emitAsReturn) { + var statement = ts.createReturn(exportEquals.expression, exportEquals); + setNodeEmitFlags(statement, 12288 | 49152); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); + setNodeEmitFlags(statement, 49152); + statements.push(statement); + } + } + } + function visitor(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 236: + return visitExportDeclaration(node); + case 235: + return visitExportAssignment(node); + case 200: + return visitVariableStatement(node); + case 220: + return visitFunctionDeclaration(node); + case 221: + return visitClassDeclaration(node); + case 202: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var statements = []; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + statements.push(ts.createStatement(createRequireCall(node), node)); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + } + else { + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); + } + } + statements.push(ts.createVariableStatement(undefined, ts.createConstDeclarationList(variables), node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node), node) + ]))); + } + addExportImportAssignments(statements, node); + return ts.singleOrMany(statements); + } + function visitImportEqualsDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + setNodeEmitFlags(node.name, 128); + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1)) { + statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), node)); + } + else { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) + ], undefined, languageVersion >= 2 ? 2 : 0), node)); + } + } + else { + if (ts.hasModifier(node, 1)) { + statements.push(ts.createStatement(createExportAssignment(node.name, node.name), node)); + } + } + addExportImportAssignments(statements, node); + return statements; + } + function visitExportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) + ]), node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + if (resolver.isValueAliasDeclaration(specifier)) { + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), specifier)); + } + } + return ts.singleOrMany(statements); + } + else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), node); + } + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + var statements = []; + addExportDefault(statements, node.expression, node); + return statements; + } + } + return undefined; + } + function addExportDefault(statements, expression, location) { + tryAddExportDefaultCompat(statements); + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); + } + function tryAddExportDefaultCompat(statements) { + var original = ts.getOriginalNode(currentSourceFile); + ts.Debug.assert(original.kind === 256); + if (!original.symbol.exports["___esModule"]) { + if (languageVersion === 0) { + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + function addExportImportAssignments(statements, node) { + if (ts.isImportEqualsDeclaration(node)) { + addExportMemberAssignments(statements, node.name); + } + else { + var names = ts.reduceEachChild(node, collectExportMembers, []); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_37 = names_1[_i]; + addExportMemberAssignments(statements, name_37); + } + } + } + function collectExportMembers(names, node) { + if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { + var name_38 = node.name; + if (ts.isIdentifier(name_38)) { + names.push(name_38); + } + } + return ts.reduceEachChild(node, collectExportMembers, names); + } + function addExportMemberAssignments(statements, name) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), specifier.name))); + } + } + } + function addExportMemberAssignment(statements, node) { + if (ts.hasModifier(node, 512)) { + addExportDefault(statements, getDeclarationName(node), node); + } + else { + statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + } + } + function visitVariableStatement(node) { + var originalKind = ts.getOriginalNode(node).kind; + if (originalKind === 225 || + originalKind === 224 || + originalKind === 221) { + if (!ts.hasModifier(node, 1)) { + return node; + } + return ts.setOriginalNode(ts.createVariableStatement(undefined, node.declarationList), node); + } + var resultStatements = []; + if (ts.hasModifier(node, 1)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length > 0) { + var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + resultStatements.push(inlineAssignments); + } + } + else { + resultStatements.push(node); + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + addExportMemberAssignmentsForBindingName(resultStatements, decl.name); + } + return resultStatements; + } + function addExportMemberAssignmentsForBindingName(resultStatements, name) { + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + addExportMemberAssignmentsForBindingName(resultStatements, element.name); + } + } + } + else { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + var sourceFileId = ts.getOriginalNodeId(currentSourceFile); + if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { + bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); + } + bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; + addExportMemberAssignments(resultStatements, name); + } + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); + } + else { + return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + } + function visitFunctionDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1)) { + statements.push(ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name, undefined, node.parameters, undefined, node.body, node), node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitClassDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1)) { + statements.push(ts.setOriginalNode(ts.createClassDeclaration(undefined, undefined, name, undefined, node.heritageClauses, node.members, node), node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name && !(node.decorators && node.decorators.length)) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitExpressionStatement(node) { + var original = ts.getOriginalNode(node); + var origKind = original.kind; + if (origKind === 224 || origKind === 225) { + return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); + } + else if (origKind === 221) { + var classDecl = original; + if (classDecl.name) { + var statements = [node]; + addExportMemberAssignments(statements, classDecl.name); + return statements; + } + } + return node; + } + function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { + var statements = [node]; + if (ts.hasModifier(original, 1) && + original.kind === 224 && + ts.isFirstDeclarationOfKind(original, 224)) { + addVarForExportedEnumOrNamespaceDeclaration(statements, original); + } + addExportMemberAssignments(statements, original.name); + return statements; + } + function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { + var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); + setNodeEmitFlags(transformedStatement, 49152); + statements.push(transformedStatement); + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function onEmitNode(node, emit) { + if (node.kind === 256) { + bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + bindingNameExportSpecifiersMap = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 187: + return substituteBinaryExpression(node); + case 186: + case 185: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteExportedName(node) + || trySubstituteImportedName(node) + || node; + } + function substituteBinaryExpression(node) { + var left = node.left; + if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { + setNodeEmitFlags(node, 128); + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, node); + } + return nestedExportAssignment; + } + } + return node; + } + function substituteUnaryExpression(node) { + var operator = node.operator; + var operand = node.operand; + if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { + setNodeEmitFlags(node, 128); + var transformedUnaryExpression = void 0; + if (node.kind === 186) { + transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + setNodeEmitFlags(transformedUnaryExpression, 128); + } + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, transformedUnaryExpression || node); + } + return nestedExportAssignment; + } + } + return node; + } + function trySubstituteExportedName(node) { + var emitFlags = getNodeEmitFlags(node); + if ((emitFlags & 262144) === 0) { + var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); + if (container) { + if (container.kind === 256) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); + } + } + } + return undefined; + } + function trySubstituteImportedName(node) { + if ((getNodeEmitFlags(node) & 262144) === 0) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (ts.isImportClause(declaration)) { + if (languageVersion >= 1) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), node); + } + else { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), node); + } + } + else if (ts.isImportSpecifier(declaration)) { + var name_39 = declaration.propertyName || declaration.name; + if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); + } + else { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); + } + } + } + } + return undefined; + } + function getModuleMemberName(name) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), name, name); + } + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (ts.isDefined(moduleName)) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), undefined, args); + } + function createExportStatement(name, value, location) { + var statement = ts.createStatement(createExportAssignment(name, value)); + statement.startsOnNewLine = true; + if (location) { + setSourceMapRange(statement, location); + } + return statement; + } + function createExportAssignment(name, value) { + return ts.createAssignment(name.originalKeywordKind === 77 && languageVersion === 0 + ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) + : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + var aliasedModuleNames = []; + var unaliasedModuleNames = []; + var importAliasNames = []; + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, externalImports_1 = externalImports; _b < externalImports_1.length; _b++) { + var importNode = externalImports_1[_b]; + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + setNodeEmitFlags(importAliasName, 128); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function updateSourceFile(node, statements) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + return updated; + } + var _a; + } + ts.transformModule = transformModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformSystemModule(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69); + context.enableSubstitution(187); + context.enableSubstitution(185); + context.enableSubstitution(186); + context.enableEmitNotification(256); + var exportFunctionForFileMap = []; + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var hasExportStarsToExportValues; + var exportFunctionForFile; + var contextObjectForFile; + var exportedLocalNames; + var exportedFunctionDeclarations; + var enclosingBlockScopedContainer; + var currentParent; + var currentNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + currentNode = node; + var updated = transformSystemModuleWorker(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + exportedLocalNames = undefined; + exportedFunctionDeclarations = undefined; + return updated; + } + return node; + } + function transformSystemModuleWorker(node) { + ts.Debug.assert(!exportFunctionForFile); + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + exportFunctionForFile = ts.createUniqueName("exports"); + contextObjectForFile = ts.createUniqueName("context"); + exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; + var dependencyGroups = collectDependencyGroups(externalImports); + var statements = []; + addSystemModuleBody(statements, node, dependencyGroups); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); + var body = ts.createFunctionExpression(undefined, undefined, undefined, [ + ts.createParameter(exportFunctionForFile), + ts.createParameter(contextObjectForFile) + ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ? [moduleName, dependencies, body] + : [dependencies, body])) + ], ~1 & getNodeEmitFlags(node)); + var _a; + } + function addSystemModuleBody(statements, node, dependencyGroups) { + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitSourceElement); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) + ]))); + var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); + ts.addRange(statements, endLexicalEnvironment()); + ts.addRange(statements, exportedFunctionDeclarations); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) + ]), true))); + } + function addExportStarIfNeeded(statements) { + if (!hasExportStarsToExportValues) { + return; + } + if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, externalImports_2 = externalImports; _i < externalImports_2.length; _i++) { + var externalImport = externalImports_2[_i]; + if (externalImport.kind === 236 && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + return addExportStarFunction(statements, undefined); + } + } + var exportedNames = []; + if (exportedLocalNames) { + for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { + var exportedLocalName = exportedLocalNames_1[_a]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); + } + } + for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { + var externalImport = externalImports_3[_b]; + if (externalImport.kind !== 236) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + continue; + } + for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { + var element = _d[_c]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) + ]))); + return addExportStarFunction(statements, exportedNamesStorageRef); + } + function generateSetters(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 230: + if (!entry.importClause) { + break; + } + case 229: + ts.Debug.assert(importVariableName !== undefined); + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 236: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); + } + else { + statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, ts.createBlock(statements, undefined, true))); + } + return ts.createArrayLiteral(setters, undefined, true); + } + function visitSourceElement(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 236: + return visitExportDeclaration(node); + case 235: + return visitExportAssignment(node); + default: + return visitNestedNode(node); + } + } + function visitNestedNode(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var currentGrandparent = currentParent; + currentParent = currentNode; + currentNode = node; + if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { + enclosingBlockScopedContainer = currentParent; + } + var result = visitNestedNodeWorker(node); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return result; + } + function visitNestedNodeWorker(node) { + switch (node.kind) { + case 200: + return visitVariableStatement(node); + case 220: + return visitFunctionDeclaration(node); + case 221: + return visitClassDeclaration(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 208: + return visitForOfStatement(node); + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 214: + return visitLabeledStatement(node); + case 212: + return visitWithStatement(node); + case 213: + return visitSwitchStatement(node); + case 227: + return visitCaseBlock(node); + case 249: + return visitCaseClause(node); + case 250: + return visitDefaultClause(node); + case 216: + return visitTryStatement(node); + case 252: + return visitCatchClause(node); + case 199: + return visitBlock(node); + case 202: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (node.importClause && ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitImportEqualsDeclaration(node) { + if (ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + var statements = []; + ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); + return statements; + } + return undefined; + } + function visitExportSpecifier(specifier) { + if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) + || resolver.isValueAliasDeclaration(specifier)) { + recordExportName(specifier.name); + return createExportStatement(specifier.name, specifier.propertyName || specifier.name); + } + return undefined; + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + return createExportStatement(ts.createLiteral("default"), node.expression); + } + } + return undefined; + } + function visitVariableStatement(node) { + var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3) == 0) || + enclosingBlockScopedContainer.kind === 256; + if (!shouldHoist) { + return node; + } + var isExported = ts.hasModifier(node, 1); + var expressions = []; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, isExported); + if (visited) { + expressions.push(visited); + } + } + if (expressions.length) { + return ts.createStatement(ts.inlineExpressions(expressions), node); + } + return undefined; + } + function transformVariable(node, isExported) { + hoistBindingElement(node, isExported); + if (!node.initializer) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + return ts.createAssignment(name, node.initializer); + } + else { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); + } + } + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1)) { + var name_40 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); + recordExportedFunctionDeclaration(node); + if (!ts.hasModifier(node, 512)) { + recordExportName(name_40); + } + ts.setOriginalNode(newNode, node); + node = newNode; + } + hoistFunctionDeclaration(node); + return undefined; + } + function visitExpressionStatement(node) { + var originalNode = ts.getOriginalNode(node); + if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { + var name_41 = getDeclarationName(originalNode); + if (originalNode.kind === 224) { + hoistVariableDeclaration(name_41); + } + return [ + node, + createExportStatement(name_41, name_41) + ]; + } + return node; + } + function visitClassDeclaration(node) { + var name = getDeclarationName(node); + hoistVariableDeclaration(name); + var statements = []; + statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, node.heritageClauses, node.members, node)), node)); + if (ts.hasModifier(node, 1)) { + if (!ts.hasModifier(node, 512)) { + recordExportName(name); + } + statements.push(createDeclarationExport(node)); + } + return statements; + } + function shouldHoistLoopInitializer(node) { + return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3) === 0; + } + function visitForStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var expressions = []; + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, false); + if (visited) { + expressions.push(visited); + } + } + ; + return ts.createFor(expressions.length + ? ts.inlineExpressions(expressions) + : ts.createSynthesizedNode(193), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), node); + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function transformForBinding(node) { + var firstDeclaration = ts.firstOrUndefined(node.declarations); + hoistBindingElement(firstDeclaration, false); + var name = firstDeclaration.name; + return ts.isIdentifier(name) + ? name + : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); + } + function visitForInStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function visitForOfStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function visitDoStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitWhileStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitLabeledStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitWithStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitSwitchStatement(node) { + var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); + if (caseBlock !== node.caseBlock) { + var updated = ts.getMutableClone(node); + updated.caseBlock = caseBlock; + return updated; + } + return node; + } + function visitCaseBlock(node) { + var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); + if (clauses !== node.clauses) { + var updated = ts.getMutableClone(node); + updated.clauses = clauses; + return updated; + } + return node; + } + function visitCaseClause(node) { + var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); + if (statements !== node.statements) { + var updated = ts.getMutableClone(node); + updated.statements = statements; + return updated; + } + return node; + } + function visitDefaultClause(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function visitTryStatement(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function visitCatchClause(node) { + var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); + if (block !== node.block) { + var updated = ts.getMutableClone(node); + updated.block = block; + return updated; + } + return node; + } + function visitBlock(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function onEmitNode(node, emit) { + if (node.kind === 256) { + exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + exportFunctionForFile = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 187: + return substituteBinaryExpression(node); + case 185: + case 186: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + var importBinding = createImportBinding(importDeclaration); + if (importBinding) { + return importBinding; + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return substituteAssignmentExpression(node); + } + return node; + } + function substituteAssignmentExpression(node) { + setNodeEmitFlags(node, 128); + var left = node.left; + switch (left.kind) { + case 69: + var exportDeclaration = resolver.getReferencedExportContainer(left); + if (exportDeclaration) { + return createExportExpression(left, node); + } + break; + case 171: + case 170: + if (hasExportedReferenceInDestructuringPattern(left)) { + return substituteDestructuring(node); + } + break; + } + return node; + } + function isExportedBinding(name) { + var container = resolver.getReferencedExportContainer(name); + return container && container.kind === 256; + } + function hasExportedReferenceInDestructuringPattern(node) { + switch (node.kind) { + case 69: + return isExportedBinding(node); + case 171: + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (hasExportedReferenceInObjectDestructuringElement(property)) { + return true; + } + } + break; + case 170: + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (hasExportedReferenceInArrayDestructuringElement(element)) { + return true; + } + } + break; + } + return false; + } + function hasExportedReferenceInObjectDestructuringElement(node) { + if (ts.isShorthandPropertyAssignment(node)) { + return isExportedBinding(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringElement(node.initializer); + } + else { + return false; + } + } + function hasExportedReferenceInArrayDestructuringElement(node) { + if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else { + return hasExportedReferenceInDestructuringElement(node); + } + } + function hasExportedReferenceInDestructuringElement(node) { + if (ts.isBinaryExpression(node)) { + var left = node.left; + return node.operatorToken.kind === 56 + && isDestructuringPattern(left) + && hasExportedReferenceInDestructuringPattern(left); + } + else if (ts.isIdentifier(node)) { + return isExportedBinding(node); + } + else if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else if (isDestructuringPattern(node)) { + return hasExportedReferenceInDestructuringPattern(node); + } + else { + return false; + } + } + function isDestructuringPattern(node) { + var kind = node.kind; + return kind === 69 + || kind === 171 + || kind === 170; + } + function substituteDestructuring(node) { + return ts.flattenDestructuringAssignment(context, node, true, hoistVariableDeclaration); + } + function substituteUnaryExpression(node) { + var operand = node.operand; + var operator = node.operator; + var substitute = ts.isIdentifier(operand) && + (node.kind === 186 || + (node.kind === 185 && (operator === 41 || operator === 42))); + if (substitute) { + var exportDeclaration = resolver.getReferencedExportContainer(operand); + if (exportDeclaration) { + var expr = ts.createPrefix(node.operator, operand, node); + setNodeEmitFlags(expr, 128); + var call = createExportExpression(operand, expr); + if (node.kind === 185) { + return call; + } + else { + return operator === 41 + ? ts.createSubtract(call, ts.createLiteral(1)) + : ts.createAdd(call, ts.createLiteral(1)); + } + } + } + return node; + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function addExportStarFunction(statements, localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); + } + statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(m)], undefined, ts.createBlock([ + ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, undefined) + ]), m, ts.createBlock([ + setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ])), + ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) + ], undefined, true))); + return exportStarFunction; + } + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; + return ts.createCall(exportFunctionForFile, undefined, [exportName, value]); + } + function createExportStatement(name, value) { + return ts.createStatement(createExportExpression(name, value)); + } + function createDeclarationExport(node) { + var declarationName = getDeclarationName(node); + var exportName = ts.hasModifier(node, 512) ? ts.createLiteral("default") : declarationName; + return createExportStatement(exportName, declarationName); + } + function createImportBinding(importDeclaration) { + var importAlias; + var name; + if (ts.isImportClause(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); + name = ts.createIdentifier("default"); + } + else if (ts.isImportSpecifier(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); + name = importDeclaration.propertyName || importDeclaration.name; + } + else { + return undefined; + } + if (name.originalKeywordKind && languageVersion === 0) { + return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); + } + else { + return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); + } + } + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + continue; + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + function getNameOfDependencyGroup(dependencyGroup) { + return dependencyGroup.name; + } + function recordExportName(name) { + if (!exportedLocalNames) { + exportedLocalNames = []; + } + exportedLocalNames.push(name); + } + function recordExportedFunctionDeclaration(node) { + if (!exportedFunctionDeclarations) { + exportedFunctionDeclarations = []; + } + exportedFunctionDeclarations.push(createDeclarationExport(node)); + } + function hoistBindingElement(node, isExported) { + if (ts.isOmittedExpression(node)) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + if (isExported) { + recordExportName(name); + } + } + else if (ts.isBindingPattern(name)) { + ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + } + } + function hoistExportedBindingElement(node) { + hoistBindingElement(node, true); + } + function hoistNonExportedBindingElement(node) { + hoistBindingElement(node, false); + } + function updateSourceFile(node, statements, nodeEmitFlags) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + setNodeEmitFlags(updated, nodeEmitFlags); + return updated; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES6Module(context) { + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 231: + return visitImportClause(node); + case 233: + case 232: + return visitNamedBindings(node); + case 234: + return visitImportSpecifier(node); + case 235: + return visitExportAssignment(node); + case 236: + return visitExportDeclaration(node); + case 237: + return visitNamedExports(node); + case 238: + return visitExportSpecifier(node); + } + return node; + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var original = ts.getOriginalNode(node); + return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, true); + if (node.exportClause === newExportClause) { + return node; + } + return newExportClause + ? ts.createExportDeclaration(undefined, undefined, newExportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); + if (node.elements === newExports) { + return node; + } + return newExports.length ? ts.createNamedExports(newExports) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + function visitImportEqualsDeclaration(node) { + return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitImportDeclaration(node) { + if (node.importClause) { + var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); + if (!newImportClause.name && !newImportClause.namedBindings) { + return undefined; + } + else if (newImportClause !== node.importClause) { + return ts.createImportDeclaration(undefined, undefined, newImportClause, node.moduleSpecifier); + } + } + return node; + } + function visitImportClause(node) { + var newDefaultImport = node.name; + if (!resolver.isReferencedAliasDeclaration(node)) { + newDefaultImport = undefined; + } + var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true); + return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings + ? ts.createImportClause(newDefaultImport, newNamedBindings) + : node; + } + function visitNamedBindings(node) { + if (node.kind === 232) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); + if (!newNamedImportElements || newNamedImportElements.length == 0) { + return undefined; + } + if (newNamedImportElements === node.elements) { + return node; + } + return ts.createNamedImports(newNamedImportElements); + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + } + ts.transformES6Module = transformES6Module; +})(ts || (ts = {})); +var ts; +(function (ts) { + var moduleTransformerMap = ts.createMap((_a = {}, + _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.System] = ts.transformSystemModule, + _a[ts.ModuleKind.AMD] = ts.transformModule, + _a[ts.ModuleKind.CommonJS] = ts.transformModule, + _a[ts.ModuleKind.UMD] = ts.transformModule, + _a[ts.ModuleKind.None] = ts.transformModule, + _a)); + function getTransformers(compilerOptions) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + transformers.push(ts.transformTypeScript); + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (jsx === 2) { + transformers.push(ts.transformJsx); + } + transformers.push(ts.transformES7); + if (languageVersion < 2) { + transformers.push(ts.transformES6); + transformers.push(ts.transformGenerators); + } + return transformers; + } + ts.getTransformers = getTransformers; + var nextTransformId = 1; + function transformFiles(resolver, host, sourceFiles, transformers) { + var transformId = nextTransformId; + nextTransformId++; + var tokenSourceMapRanges = ts.createMap(); + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var enabledSyntaxKindFeatures = new Array(289); + var parseTreeNodesWithAnnotations = []; + var lastTokenSourceMapRangeNode; + var lastTokenSourceMapRangeToken; + var lastTokenSourceMapRange; + var lexicalEnvironmentStackOffset = 0; + var hoistedVariableDeclarations; + var hoistedFunctionDeclarations; + var lexicalEnvironmentDisabled; + var context = { + getCompilerOptions: function () { return host.getCompilerOptions(); }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + getNodeEmitFlags: getNodeEmitFlags, + setNodeEmitFlags: setNodeEmitFlags, + getSourceMapRange: getSourceMapRange, + setSourceMapRange: setSourceMapRange, + getTokenSourceMapRange: getTokenSourceMapRange, + setTokenSourceMapRange: setTokenSourceMapRange, + getCommentRange: getCommentRange, + setCommentRange: setCommentRange, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + startLexicalEnvironment: startLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + onSubstituteNode: onSubstituteNode, + enableSubstitution: enableSubstitution, + isSubstitutionEnabled: isSubstitutionEnabled, + onEmitNode: onEmitNode, + enableEmitNotification: enableEmitNotification, + isEmitNotificationEnabled: isEmitNotificationEnabled + }; + var transformation = chain.apply(void 0, transformers)(context); + var transformed = ts.map(sourceFiles, transformSourceFile); + lexicalEnvironmentDisabled = true; + return { + getSourceFiles: function () { return transformed; }, + getTokenSourceMapRange: getTokenSourceMapRange, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + onSubstituteNode: context.onSubstituteNode, + onEmitNode: context.onEmitNode, + dispose: function () { + for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { + var node = parseTreeNodesWithAnnotations_1[_i]; + if (node.transformId === transformId) { + node.transformId = 0; + node.emitFlags = 0; + node.commentRange = undefined; + node.sourceMapRange = undefined; + } + } + parseTreeNodesWithAnnotations.length = 0; + } + }; + function transformSourceFile(sourceFile) { + if (ts.isDeclarationFile(sourceFile)) { + return sourceFile; + } + return transformation(sourceFile); + } + function enableSubstitution(kind) { + enabledSyntaxKindFeatures[kind] |= 1; + } + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + } + function onSubstituteNode(node, isExpression) { + return node; + } + function enableEmitNotification(kind) { + enabledSyntaxKindFeatures[kind] |= 2; + } + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 + || (getNodeEmitFlags(node) & 64) !== 0; + } + function onEmitNode(node, emit) { + emit(node); + } + function beforeSetAnnotation(node) { + if ((node.flags & 8) === 0 && node.transformId !== transformId) { + parseTreeNodesWithAnnotations.push(node); + node.transformId = transformId; + } + } + function getNodeEmitFlags(node) { + return node.emitFlags; + } + function setNodeEmitFlags(node, emitFlags) { + beforeSetAnnotation(node); + node.emitFlags = emitFlags; + return node; + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + function setSourceMapRange(node, range) { + beforeSetAnnotation(node); + node.sourceMapRange = range; + return node; + } + function getTokenSourceMapRange(node, token) { + if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { + return lastTokenSourceMapRange; + } + var range; + var current = node; + while (current) { + range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; + if (range !== undefined) { + break; + } + current = current.original; + } + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + return range; + } + function setTokenSourceMapRange(node, token, range) { + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; + return node; + } + function getCommentRange(node) { + return node.commentRange || node; + } + function setCommentRange(node, range) { + beforeSetAnnotation(node); + node.commentRange = range; + return node; + } + function hoistVariableDeclaration(name) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var decl = ts.createVariableDeclaration(name); + if (!hoistedVariableDeclarations) { + hoistedVariableDeclarations = [decl]; + } + else { + hoistedVariableDeclarations.push(decl); + } + } + function hoistFunctionDeclaration(func) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + if (!hoistedFunctionDeclarations) { + hoistedFunctionDeclarations = [func]; + } + else { + hoistedFunctionDeclarations.push(func); + } + } + function startLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentStackOffset++; + hoistedVariableDeclarations = undefined; + hoistedFunctionDeclarations = undefined; + } + function endLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + var statements; + if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { + if (hoistedFunctionDeclarations) { + statements = hoistedFunctionDeclarations.slice(); + } + if (hoistedVariableDeclarations) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + lexicalEnvironmentStackOffset--; + hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + return statements; + } + } + ts.transformFiles = transformFiles; + function chain(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + function compose(a, b, c, d, e) { + if (e) { + var args_4 = []; + for (var i = 0; i < arguments.length; i++) { + args_4[i] = arguments[i]; + } + return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + var _a; })(ts || (ts = {})); var ts; (function (ts) { @@ -29056,9 +42292,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -29147,11 +42381,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = {}; + usedTypeDirectiveReferences = ts.createMap(); } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { + if (!(directive in usedTypeDirectiveReferences)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -29176,7 +42410,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -29235,7 +42469,7 @@ var ts; if (declaration) { var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, false, true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -29303,7 +42537,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); emitEntityName(node.expression); if (node.typeArguments) { @@ -29372,15 +42606,15 @@ var ts; } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentIdentifiers, baseName)) { + if (!(baseName in currentIdentifiers)) { return baseName; } var count = 0; while (true) { count++; - var name_24 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_24)) { - return name_24; + var name_42 = baseName + "_" + count; + if (!(name_42 in currentIdentifiers)) { + return name_42; } } } @@ -29478,10 +42712,11 @@ var ts; } function emitModuleElementDeclarationFlags(node) { if (node.parent.kind === 256) { - if (node.flags & 1) { + var modifiers = ts.getModifierFlags(node); + if (modifiers & 1) { write("export "); } - if (node.flags & 512) { + if (modifiers & 512) { write("default "); } else if (node.kind !== 222 && !noDeclare) { @@ -29508,7 +42743,7 @@ var ts; } function writeImportEqualsDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { write("export "); } write("import "); @@ -29544,7 +42779,7 @@ var ts; } function writeImportDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { write("export "); } write("import "); @@ -29635,7 +42870,7 @@ var ts; write("global "); } else { - if (node.flags & 4096) { + if (node.flags & 16) { write("namespace "); } else { @@ -29718,7 +42953,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 && (node.parent.flags & 8); + return node.parent.kind === 147 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -29760,7 +42995,7 @@ var ts; break; case 147: case 146: - if (node.parent.flags & 32) { + if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 221) { @@ -29795,7 +43030,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93) { @@ -29827,7 +43062,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 92) { + if (ts.hasModifier(param, 92)) { emitPropertyDeclaration(param); } }); @@ -29835,7 +43070,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 128) { + if (ts.hasModifier(node, 128)) { write("abstract "); } write("class "); @@ -29881,7 +43116,7 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); emitVariableDeclaration(node); write(";"); writeLine(); @@ -29893,13 +43128,18 @@ var ts; } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || node.kind === 142) && ts.hasQuestionToken(node)) { + if ((node.kind === 145 || node.kind === 144 || + (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 8)) { + else if (resolver.isLiteralConstDeclaration(node)) { + write(" = "); + resolver.writeLiteralConstValue(node, writer); + } + else if (!ts.hasModifier(node, 8)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -29913,7 +43153,7 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } else if (node.kind === 145 || node.kind === 144) { - if (node.flags & 32) { + if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -30006,9 +43246,9 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64)); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); writeTextOfNode(currentText, node.name); - if (!(node.flags & 8)) { + if (!ts.hasModifier(node, 8)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -30035,7 +43275,7 @@ var ts; function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 150) { - if (accessorWithTypeAnnotation.parent.flags & 32) { + if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -30052,7 +43292,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 32) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -30084,7 +43324,7 @@ var ts; emitModuleElementDeclarationFlags(node); } else if (node.kind === 147 || node.kind === 148) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } if (node.kind === 220) { write("function "); @@ -30111,7 +43351,7 @@ var ts; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; if (node.kind === 153) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { @@ -30142,7 +43382,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 148 && !(node.flags & 8)) { + else if (node.kind !== 148 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -30173,7 +43413,7 @@ var ts; break; case 147: case 146: - if (node.flags & 32) { + if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -30230,7 +43470,7 @@ var ts; node.parent.parent.kind === 159) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 8)) { + else if (!ts.hasModifier(node.parent, 8)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { @@ -30259,7 +43499,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 147: case 146: - if (node.parent.flags & 32) { + if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -30417,6283 +43657,725 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getResolvedExternalModuleName(host, file) { - return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); - } - ts.getResolvedExternalModuleName = getResolvedExternalModuleName; - function getExternalModuleNameFromDeclaration(host, resolver, declaration) { - var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || ts.isDeclarationFile(file)) { - return undefined; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { + if (compilerOptions.extendedDiagnostics) { + return createSourceMapWriterWithExtendedDiagnostics(host, writer); + } + return createSourceMapWriterWorker(host, writer); + } + else { + return getNullSourceMapWriter(); } - return getResolvedExternalModuleName(host, file); } - ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = { - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 + ts.createSourceMapWriter = createSourceMapWriter; + var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { }, + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitPos: function (pos) { }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + changeEmitSourcePos: function () { }, + stopOverridingSpan: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + var defaultLastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 }; + function createSourceMapWriterWorker(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; + var currentSourceFile; + var currentSourceText; + var sourceMapDir; + var stopOverridingSpan = false; + var modifyLastSourcePos = false; + var sourceMapSourceIndex; + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + var sourceMapData; + var disableDepth; + return { + initialize: initialize, + reset: reset, + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + emitTokenStart: emitTokenStart, + emitTokenEnd: emitTokenEnd, + changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: function () { return stopOverridingSpan = true; }, + getText: getText, + getSourceMappingURL: getSourceMappingURL + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + currentSourceText = undefined; + disableDepth = 0; + sourceMapSourceIndex = -1; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; + lastEncodedNameIndex = 0; + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + disableDepth = 0; + } + function enable() { + if (disableDepth > 0) { + disableDepth--; + } + } + function disable() { + disableDepth++; + } + function updateLastEncodedAndRecordedSpans() { + if (modifyLastSourcePos) { + modifyLastSourcePos = false; + lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; + lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; + sourceMapData.sourceMapDecodedMappings.pop(); + lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? + sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : + defaultLastEncodedSourceMapSpan; + var sourceMapMappings = sourceMapData.sourceMapMappings; + var lenthToSet = sourceMapMappings.length - 1; + for (; lenthToSet >= 0; lenthToSet--) { + var currentChar = sourceMapMappings.charAt(lenthToSet); + if (currentChar === ",") { + break; + } + if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { + break; + } + } + sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); + } + } + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + return; + } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + stopOverridingSpan = false; + } + else if (!stopOverridingSpan) { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } + } + function getStartPosPastDecorators(range) { + var rangeHasDecorators = !!range.decorators; + return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); + } + function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(getStartPosPastDecorators(range)); + } + if (ignoreChildrenCallback(contextNode)) { + disable(); + } + } + else { + emitPos(getStartPosPastDecorators(range)); + } + } + function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (ignoreChildrenCallback(contextNode)) { + enable(); + } + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(range.end); + } + } + else { + emitPos(range.end); + } + stopOverridingSpan = false; + } + function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return ts.skipTrivia(currentSourceText, tokenStartPos); + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenStartPos = range.pos; + } + } + tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); + emitPos(tokenStartPos); + return tokenStartPos; + } + function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return tokenEndPos; + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenEndPos = range.end; + } + } + emitPos(tokenEndPos); + return tokenEndPos; + } + function changeEmitSourcePos() { + ts.Debug.assert(!modifyLastSourcePos); + modifyLastSourcePos = true; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentSourceText = currentSourceFile.text; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + function createSourceMapWriterWithExtendedDiagnostics(host, writer) { + var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; + return { + initialize: initialize, + reset: reset, + getSourceMapData: getSourceMapData, + setSourceFile: setSourceFile, + emitPos: function (pos) { + ts.performance.mark("sourcemapStart"); + emitPos(pos); + ts.performance.measure("sourceMapTime", "sourcemapStart"); + }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitStart"); + emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); + }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitEnd"); + emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); + }, + emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenStart"); + tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); + return tokenStartPos; + }, + emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenEnd"); + tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); + return tokenEndPos; + }, + changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: stopOverridingSpan, + getText: getText, + getSourceMappingURL: getSourceMappingURL + }; + } + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createCommentWriter(host, writer, sourceMap) { + var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; + var newLine = host.getNewLine(); + var emitPos = sourceMap.emitPos; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentSourceFile; + var currentText; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var disabled = compilerOptions.removeComments; + return { + reset: reset, + setSourceFile: setSourceFile, + emitNodeWithComments: emitNodeWithComments, + emitBodyWithDetachedComments: emitBodyWithDetachedComments, + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + }; + function emitNodeWithComments(node, emitCallback) { + if (disabled) { + emitCallback(node); + return; + } + if (node) { + var _a = node.commentRange || node, pos = _a.pos, end = _a.end; + var emitFlags = node.emitFlags; + if ((pos < 0 && end < 0) || (pos === end)) { + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + } + else { + if (extendedDiagnostics) { + ts.performance.mark("preEmitNodeWithComment"); + } + var isEmittedNode = node.kind !== 287; + var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 32768) !== 0; + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if (!skipLeadingComments) { + containerPos = pos; + } + if (!skipTrailingComments) { + containerEnd = end; + if (node.kind === 219) { + declarationListContainerEnd = end; + } + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitNodeWithComment"); + } + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitNodeWithComment"); + } + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitNodeWithComment"); + } + } + } + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + if (extendedDiagnostics) { + ts.performance.mark("preEmitBodyWithDetachedComments"); + } + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = node.emitFlags; + var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); + } + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + } + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, true); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + } + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); + hasWrittenComment = true; + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + if (!writer.isAtStartOfLine()) { + writer.write(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos) { + if (disabled) { + return; + } + if (extendedDiagnostics) { + ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); + } + forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); + } + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + if (containerPos === -1 || pos !== containerPos) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { + ts.forEachTrailingCommentRange(currentText, end, cb); + } + } + function reset() { + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentText = currentSourceFile.text; + currentLineMap = ts.getLineStarts(currentSourceFile); + detachedCommentsInfo = undefined; + } + function disableCommentsAndEmit(node, emitCallback) { + if (disabled) { + emitCallback(node); + } + else { + disabled = true; + emitCallback(node); + disabled = false; + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + function isTripleSlashComment(commentPos, commentEnd) { + if (currentText.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + currentText.charCodeAt(commentPos + 2) === 47) { + var textSubStr = currentText.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? + true : false; + } + return false; + } + } + ts.createCommentWriter = createCommentWriter; +})(ts || (ts = {})); +var ts; +(function (ts) { function emitFiles(resolver, host, targetSourceFile) { + var delimiters = createDelimiterMap(); + var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; + var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; + var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; + var superHelper = "\nconst _super = name => super[name];"; + var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var emitSkipped = false; var newLine = host.getNewLine(); - var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); + var transformers = ts.getTransformers(compilerOptions); + var writer = ts.createTextWriter(newLine); + var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = ts.createSourceMapWriter(host, writer); + var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var comments = ts.createCommentWriter(host, writer, sourceMap); + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var nodeIdToGeneratedName; + var autoGeneratedIdToGeneratedName; + var generatedNameSet; + var tempFlags; + var currentSourceFile; + var currentText; + var currentFileIdentifiers; + var extendsEmitted; + var assignEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; + var isOwnFileEmit; + var emitSkipped = false; + ts.performance.mark("beforeTransform"); + var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.measure("transformTime", "beforeTransform"); + var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); + transformed.dispose(); + ts.performance.measure("printTime", "beforePrint"); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList }; - function isUniqueLocalName(name, container) { - for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name)) { - if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { - return false; - } - } - } - return true; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function hoistVariableDeclarationFromLoop(state, declaration) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(declaration.name); - function visit(node) { - if (node.kind === 69) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _a = 0, _b = node.elements; _a < _b.length; _a++) { - var element = _b[_a]; - visit(element.name); - } - } - } - } - function createFileEmitter() { - var writer = ts.createTextWriter(newLine); - var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; - var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); - var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; - var currentSourceFile; - var currentText; - var currentLineMap; - var currentFileIdentifiers; - var renamedDependencies; - var isEs6Module; - var isCurrentFileExternalModule; - var exportFunctionForFile; - var contextObjectForFile; - var generatedNameSet; - var nodeToGeneratedName; - var computedPropertyNamesToGeneratedNames; - var decoratedClassAliases; - var convertedLoopState; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; - var tempFlags = 0; - var tempVariables; - var tempParameters; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var detachedCommentsInfo; - var sourceMapData; - var isOwnFileEmit; - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; - var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, - _a[ts.ModuleKind.ES6] = emitES6Module, - _a[ts.ModuleKind.AMD] = emitAMDModule, - _a[ts.ModuleKind.System] = emitSystemModule, - _a[ts.ModuleKind.UMD] = emitUMDModule, - _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, - _a - ); - var bundleEmitDelegates = (_b = {}, - _b[ts.ModuleKind.ES6] = function () { }, - _b[ts.ModuleKind.AMD] = emitAMDModule, - _b[ts.ModuleKind.System] = emitSystemModule, - _b[ts.ModuleKind.UMD] = function () { }, - _b[ts.ModuleKind.CommonJS] = function () { }, - _b - ); - return doEmit; - function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = {}; - nodeToGeneratedName = []; - decoratedClassAliases = []; - isOwnFileEmit = !isBundledEmit; - if (isBundledEmit && modulekind) { - ts.forEach(sourceFiles, emitEmitHelpers); - } - ts.forEach(sourceFiles, emitSourceFile); - writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); - if (sourceMappingURL) { - write("//# sourceMappingURL=" + sourceMappingURL); - } - writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles); - sourceMap.reset(); - writer.reset(); - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - generatedNameSet = undefined; - nodeToGeneratedName = undefined; - decoratedClassAliases = undefined; - computedPropertyNamesToGeneratedNames = undefined; - convertedLoopState = undefined; - extendsEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; - assignEmitted = false; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = undefined; - detachedCommentsInfo = undefined; - sourceMapData = undefined; - isEs6Module = false; - renamedDependencies = undefined; - isCurrentFileExternalModule = false; - } - function emitSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = sourceFile.text; - currentLineMap = ts.getLineStarts(sourceFile); - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; - renamedDependencies = sourceFile.renamedDependencies; - currentFileIdentifiers = sourceFile.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - setSourceFile(sourceFile); - emitNodeWithCommentsAndWithoutSourcemap(sourceFile); - } - function isUniqueName(name) { - return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); - } - function makeTempVariableName(flags) { - if (flags && !(tempFlags & flags)) { - var name_25 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_25)) { - tempFlags |= flags; - return name_25; - } - } - while (true) { - var count = tempFlags & 268435455; - tempFlags++; - if (count !== 8 && count !== 13) { - var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_26)) { - return name_26; - } - } - } - } - function makeUniqueName(baseName) { - if (baseName.charCodeAt(baseName.length - 1) !== 95) { - baseName += "_"; - } - var i = 1; - while (true) { - var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - return generatedNameSet[generatedName] = generatedName; - } - i++; - } - } - function generateNameForModuleOrEnum(node) { - var name = node.name.text; - return isUniqueLocalName(name, node) ? name : makeUniqueName(name); - } - function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - return makeUniqueName(baseName); - } - function generateNameForExportDefault() { - return makeUniqueName("default"); - } - function generateNameForClassExpression() { - return makeUniqueName("class"); - } - function generateNameForNode(node) { - switch (node.kind) { - case 69: - return makeUniqueName(node.text); - case 225: - case 224: - return generateNameForModuleOrEnum(node); - case 230: - case 236: - return generateNameForImportOrExportDeclaration(node); - case 220: - case 221: - case 235: - return generateNameForExportDefault(); - case 192: - return generateNameForClassExpression(); - default: - ts.Debug.fail(); - } - } - function getGeneratedNameForNode(node) { - var id = ts.getNodeId(node); - return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); - } - function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark, sourceFiles) { - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); - } - ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark, sourceFiles); - } - function createTempVariable(flags) { - var result = ts.createSynthesizedNode(69); - result.text = makeTempVariableName(flags); - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function createAndRecordTempVariable(flags) { - var temp = createTempVariable(flags); - recordTempDeclaration(temp); - return temp; - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - function emitToken(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - emitPos(tokenStartPos); - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - var tokenEndPos = tokenStartPos + tokenString.length; - emitPos(tokenEndPos); - return tokenEndPos; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitParenthesizedIf(node, parenthesized) { - if (parenthesized) { - write("("); - } - emit(node); - if (parenthesized) { - write(")"); - } - } - function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { - ts.Debug.assert(nodes.length > 0); - increaseIndent(); - if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - for (var i = 0, n = nodes.length; i < n; i++) { - if (i) { - if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { - write(", "); - } - else { - write(","); - writeLine(); - } - } - emit(nodes[i]); - } - if (nodes.hasTrailingComma && allowTrailingComma) { - write(","); - } - decreaseIndent(); - if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - } - function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) { - if (!emitNode) { - emitNode = emit; - } - for (var i = 0; i < count; i++) { - if (multiLine) { - if (i || leadingComma) { - write(","); - } - writeLine(); - } - else { - if (i || leadingComma) { - write(", "); - } - } - var node = nodes[start + i]; - emitTrailingCommentsOfPosition(node.pos); - emitNode(node); - leadingComma = true; - } - if (trailingComma) { - write(","); - } - if (multiLine && !noTrailingNewLine) { - writeLine(); - } - return count; - } - function emitCommaList(nodes) { - if (nodes) { - emitList(nodes, 0, nodes.length, false, false); - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(node, text) { - if (node.kind === 8 && text.length > 1) { - switch (text.charCodeAt(1)) { - case 98: - case 66: - case 111: - case 79: - return true; - } - } - return false; - } - function emitLiteral(node) { - var text = getLiteralText(node); - if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (languageVersion < 2 && isBinaryOrOctalIntegerLiteral(node, text)) { - write(node.text); - } - else { - write(text); - } - } - function getLiteralText(node) { - if (languageVersion < 2 && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { - return getQuotedEscapedLiteralText('"', node.text, '"'); - } - if (node.parent) { - return ts.getTextOfNodeFromSourceText(currentText, node); - } - switch (node.kind) { - case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11: - return getQuotedEscapedLiteralText("`", node.text, "`"); - case 12: - return getQuotedEscapedLiteralText("`", node.text, "${"); - case 13: - return getQuotedEscapedLiteralText("}", node.text, "${"); - case 14: - return getQuotedEscapedLiteralText("}", node.text, "`"); - case 8: - return node.text; - } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); - } - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; - } - function emitDownlevelRawTemplateLiteral(node) { - var text = ts.getTextOfNodeFromSourceText(currentText, node); - var isLast = node.kind === 11 || node.kind === 14; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - text = text.replace(/\r\n?/g, "\n"); - text = ts.escapeString(text); - write("\"" + text + "\""); - } - function emitDownlevelTaggedTemplateArray(node, literalEmitter) { - write("["); - if (node.template.kind === 11) { - literalEmitter(node.template); - } - else { - literalEmitter(node.template.head); - ts.forEach(node.template.templateSpans, function (child) { - write(", "); - literalEmitter(child.literal); - }); - } - write("]"); - } - function emitDownlevelTaggedTemplate(node) { - var tempVariable = createAndRecordTempVariable(0); - write("("); - emit(tempVariable); - write(" = "); - emitDownlevelTaggedTemplateArray(node, emit); - write(", "); - emit(tempVariable); - write(".raw = "); - emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral); - write(", "); - emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); - write("("); - emit(tempVariable); - if (node.template.kind === 189) { - ts.forEach(node.template.templateSpans, function (templateSpan) { - write(", "); - var needsParens = templateSpan.expression.kind === 187 - && templateSpan.expression.operatorToken.kind === 24; - emitParenthesizedIf(templateSpan.expression, needsParens); - }); - } - write("))"); - } - function emitTemplateExpression(node) { - if (languageVersion >= 2) { - ts.forEachChild(node, emit); - return; - } - var emitOuterParens = ts.isExpression(node.parent) - && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - var headEmitted = false; - if (shouldEmitTemplateHead()) { - emitLiteral(node.head); - headEmitted = true; - } - for (var i = 0, n = node.templateSpans.length; i < n; i++) { - var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 178 - && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; - if (i > 0 || headEmitted) { - write(" + "); - } - emitParenthesizedIf(templateSpan.expression, needsParens); - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - } - if (emitOuterParens) { - write(")"); - } - function shouldEmitTemplateHead() { - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 174: - case 175: - return parent.expression === template; - case 176: - case 178: - return false; - default: - return comparePrecedenceToBinaryPlus(parent) !== -1; - } - } - function comparePrecedenceToBinaryPlus(expression) { - switch (expression.kind) { - case 187: - switch (expression.operatorToken.kind) { - case 37: - case 39: - case 40: - return 1; - case 35: - case 36: - return 0; - default: - return -1; - } - case 190: - case 188: - return -1; - default: - return 1; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - function jsxEmitReact(node) { - function emitTagName(name) { - if (name.kind === 69 && ts.isIntrinsicJsxName(name.text)) { - write('"'); - emit(name); - write('"'); - } - else { - emit(name); - } - } - function emitAttributeName(name) { - if (/^[A-Za-z_]\w*$/.test(name.text)) { - emit(name); - } - else { - write('"'); - emit(name); - write('"'); - } - } - function emitJsxAttribute(node) { - emitAttributeName(node.name); - write(": "); - if (node.initializer) { - emit(node.initializer); - } - else { - write("true"); - } - } - function emitJsxElement(openingNode, children) { - var syntheticReactRef = ts.createSynthesizedNode(69); - syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; - syntheticReactRef.parent = openingNode; - emitLeadingComments(openingNode); - emitExpressionIdentifier(syntheticReactRef); - write(".createElement("); - emitTagName(openingNode.tagName); - write(", "); - if (openingNode.attributes.length === 0) { - write("null"); - } - else { - var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 247; })) { - write("__assign("); - var haveOpenedObjectLiteral = false; - for (var i = 0; i < attrs.length; i++) { - if (attrs[i].kind === 247) { - if (i === 0) { - write("{}, "); - } - if (haveOpenedObjectLiteral) { - write("}"); - haveOpenedObjectLiteral = false; - } - if (i > 0) { - write(", "); - } - emit(attrs[i].expression); - } - else { - ts.Debug.assert(attrs[i].kind === 246); - if (haveOpenedObjectLiteral) { - write(", "); - } - else { - haveOpenedObjectLiteral = true; - if (i > 0) { - write(", "); - } - write("{"); - } - emitJsxAttribute(attrs[i]); - } - } - if (haveOpenedObjectLiteral) - write("}"); - write(")"); - } - else { - write("{"); - for (var i = 0, n = attrs.length; i < n; i++) { - if (i > 0) { - write(", "); - } - emitJsxAttribute(attrs[i]); - } - write("}"); - } - } - if (children) { - var firstChild = void 0; - var multipleEmittableChildren = false; - for (var i = 0, n = children.length; i < n; i++) { - var jsxChild = children[i]; - if (isJsxChildEmittable(jsxChild)) { - if (!firstChild) { - write(", "); - firstChild = jsxChild; - } - else { - if (!multipleEmittableChildren) { - multipleEmittableChildren = true; - increaseIndent(); - writeLine(); - emit(firstChild); - } - write(", "); - writeLine(); - emit(jsxChild); - } - } - } - if (multipleEmittableChildren) { - decreaseIndent(); - } - else if (firstChild) { - if (firstChild.kind !== 241 && firstChild.kind !== 242) { - emit(firstChild); - } - else { - increaseIndent(); - writeLine(); - emit(firstChild); - writeLine(); - decreaseIndent(); - } - } - } - write(")"); - emitTrailingComments(openingNode); - } - if (node.kind === 241) { - emitJsxElement(node.openingElement, node.children); - } - else { - ts.Debug.assert(node.kind === 242); - emitJsxElement(node); - } - } - function jsxEmitPreserve(node) { - function emitJsxAttribute(node) { - emit(node.name); - if (node.initializer) { - write("="); - emit(node.initializer); - } - } - function emitJsxSpreadAttribute(node) { - write("{..."); - emit(node.expression); - write("}"); - } - function emitAttributes(attribs) { - for (var i = 0, n = attribs.length; i < n; i++) { - if (i > 0) { - write(" "); - } - if (attribs[i].kind === 247) { - emitJsxSpreadAttribute(attribs[i]); - } - else { - ts.Debug.assert(attribs[i].kind === 246); - emitJsxAttribute(attribs[i]); - } - } - } - function emitJsxOpeningOrSelfClosingElement(node) { - write("<"); - emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 242)) { - write(" "); - } - emitAttributes(node.attributes); - if (node.kind === 242) { - write("/>"); - } - else { - write(">"); - } - } - function emitJsxClosingElement(node) { - write(""); - } - function emitJsxElement(node) { - emitJsxOpeningOrSelfClosingElement(node.openingElement); - for (var i = 0, n = node.children.length; i < n; i++) { - emit(node.children[i]); - } - emitJsxClosingElement(node.closingElement); - } - if (node.kind === 241) { - emitJsxElement(node); - } - else { - ts.Debug.assert(node.kind === 242); - emitJsxOpeningOrSelfClosingElement(node); - } - } - function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 169); - if (node.kind === 9) { - emitLiteral(node); - } - else if (node.kind === 140) { - if (ts.nodeIsDecorated(node.parent)) { - if (!computedPropertyNamesToGeneratedNames) { - computedPropertyNamesToGeneratedNames = []; - } - var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)]; - if (generatedName) { - write(generatedName); - return; - } - generatedName = createAndRecordTempVariable(0).text; - computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName; - write(generatedName); - write(" = "); - } - emit(node.expression); - } - else { - write('"'); - if (node.kind === 8) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - write('"'); - } - } - function isExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 170: - case 195: - case 184: - case 187: - case 174: - case 249: - case 140: - case 188: - case 143: - case 181: - case 204: - case 173: - case 235: - case 202: - case 194: - case 206: - case 207: - case 208: - case 203: - case 245: - case 242: - case 243: - case 247: - case 248: - case 175: - case 196: - case 178: - case 186: - case 185: - case 211: - case 254: - case 191: - case 213: - case 176: - case 197: - case 215: - case 177: - case 182: - case 183: - case 205: - case 212: - case 190: - return true; - case 169: - case 255: - case 142: - case 253: - case 145: - case 218: - return parent.initializer === node; - case 172: - return parent.expression === node; - case 180: - case 179: - return parent.body === node; - case 229: - return parent.moduleReference === node; - case 139: - return parent.left === node; - } - return false; - } - function emitExpressionIdentifier(node) { - var container = resolver.getReferencedExportContainer(node); - if (container) { - if (container.kind === 256) { - if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - else { - write(getGeneratedNameForNode(container)); - write("."); - } - } - else { - if (modulekind !== ts.ModuleKind.ES6) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (declaration.kind === 231) { - write(getGeneratedNameForNode(declaration.parent)); - write(languageVersion === 0 ? '["default"]' : ".default"); - return; - } - else if (declaration.kind === 234) { - write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_27 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); - if (languageVersion === 0 && identifier === "default") { - write('["default"]'); - } - else { - write("."); - write(identifier); - } - return; - } - } - } - if (languageVersion < 2) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - else if (resolver.getNodeCheckFlags(node) & 1048576) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; - if (classAlias !== undefined) { - write(classAlias); - return; - } - } - } - } - if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { - if (languageVersion < 2) { - var parent_13 = node.parent; - switch (parent_13.kind) { - case 169: - case 221: - case 224: - case 218: - return parent_13.name === node && resolver.isDeclarationWithCollidingName(parent_13); - } - } - return false; - } - function getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node) { - if (languageVersion >= 2) { - var parent_14 = node.parent; - if (parent_14.kind === 172 && parent_14.expression === node) { - parent_14 = parent_14.parent; - while (parent_14 && parent_14.kind !== 145) { - parent_14 = parent_14.parent; - } - return parent_14 && parent_14.kind === 145 && (parent_14.flags & 32) !== 0 && - parent_14.parent.kind === 192 ? parent_14.parent : undefined; - } - } - return undefined; - } - function emitIdentifier(node) { - if (convertedLoopState) { - if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_28); - return; - } - } - if (!node.parent) { - write(node.text); - } - else if (isExpressionIdentifier(node)) { - var classExpression = getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node); - if (classExpression) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration === classExpression) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - emitExpressionIdentifier(node); - } - else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { - write(getGeneratedNameForNode(node)); - } - else if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2) { - write("_this"); - } - else if (convertedLoopState) { - write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); - } - else { - write("this"); - } - } - function emitSuper(node) { - if (languageVersion >= 2) { - write("super"); - } - else { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 256) { - write("_super.prototype"); - } - else { - write("_super"); - } - } - } - function emitObjectBindingPattern(node) { - write("{ "); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write("]"); - } - function emitBindingElement(node) { - if (node.propertyName) { - emit(node.propertyName); - write(": "); - } - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emit(node.name); - } - else { - emitModuleMemberName(node); - } - emitOptional(" = ", node.initializer); - } - function emitSpreadElementExpression(node) { - write("..."); - emit(node.expression); - } - function emitYieldExpression(node) { - write(ts.tokenToString(114)); - if (node.asteriskToken) { - write("*"); - } - if (node.expression) { - write(" "); - emit(node.expression); - } - } - function emitAwaitExpression(node) { - var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); - if (needsParenthesis) { - write("("); - } - write(ts.tokenToString(114)); - write(" "); - emit(node.expression); - if (needsParenthesis) { - write(")"); - } - } - function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 187 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { - return true; - } - else if (node.parent.kind === 188 && node.parent.condition === node) { - return true; - } - return false; - } - function needsParenthesisForPropertyAccessOrInvocation(node) { - switch (node.kind) { - case 69: - case 170: - case 172: - case 173: - case 174: - case 178: - return false; - } - return true; - } - function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { - var pos = 0; - var group = 0; - var length = elements.length; - while (pos < length) { - if (group === 1 && useConcat) { - write(".concat("); - } - else if (group > 0) { - write(", "); - } - var e = elements[pos]; - if (e.kind === 191) { - e = e.expression; - emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); - pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 170) { - write(".slice()"); - } - } - else { - var i = pos; - while (i < length && elements[i].kind !== 191) { - i++; - } - write("["); - if (multiLine) { - increaseIndent(); - } - emitList(elements, pos, i - pos, multiLine, trailingComma && i === length); - if (multiLine) { - decreaseIndent(); - } - write("]"); - pos = i; - } - group++; - } - if (group > 1) { - if (useConcat) { - write(")"); - } - } - } - function isSpreadElementExpression(node) { - return node.kind === 191; - } - function emitArrayLiteral(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else if (languageVersion >= 2 || !ts.forEach(elements, isSpreadElementExpression)) { - write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, false); - write("]"); - } - else { - emitListWithSpread(elements, true, node.multiLine, elements.hasTrailingComma, true); - } - } - function emitObjectLiteralBody(node, numElements) { - if (numElements === 0) { - write("{}"); - return; - } - write("{"); - if (numElements > 0) { - var properties = node.properties; - if (numElements === properties.length) { - emitLinePreservingList(node, properties, languageVersion >= 1, true); - } - else { - var multiLine = node.multiLine; - if (!multiLine) { - write(" "); - } - else { - increaseIndent(); - } - emitList(properties, 0, numElements, multiLine, false); - if (!multiLine) { - write(" "); - } - else { - decreaseIndent(); - } - } - } - write("}"); - } - function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = node.multiLine; - var properties = node.properties; - write("("); - if (multiLine) { - increaseIndent(); - } - var tempVar = createAndRecordTempVariable(0); - emit(tempVar); - write(" = "); - emitObjectLiteralBody(node, firstComputedPropertyIndex); - for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); - var property = properties[i]; - emitStart(property); - if (property.kind === 149 || property.kind === 150) { - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property !== accessors.firstAccessor) { - continue; - } - write("Object.defineProperty("); - emit(tempVar); - write(", "); - emitStart(property.name); - emitExpressionForPropertyName(property.name); - emitEnd(property.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("})"); - emitEnd(property); - } - else { - emitLeadingComments(property); - emitStart(property.name); - emit(tempVar); - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - if (property.kind === 253) { - emit(property.initializer); - } - else if (property.kind === 254) { - emitExpressionIdentifier(property.name); - } - else if (property.kind === 147) { - emitFunctionDeclaration(property); - } - else { - ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); - } - } - emitEnd(property); - } - writeComma(); - emit(tempVar); - if (multiLine) { - decreaseIndent(); - writeLine(); - } - write(")"); - function writeComma() { - if (multiLine) { - write(","); - writeLine(); - } - else { - write(", "); - } - } - } - function emitObjectLiteral(node) { - var properties = node.properties; - if (languageVersion < 2) { - var numProperties = properties.length; - var numInitialNonComputedProperties = numProperties; - for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 140) { - numInitialNonComputedProperties = i; - break; - } - } - var hasComputedProperty = numInitialNonComputedProperties !== properties.length; - if (hasComputedProperty) { - emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); - return; - } - } - emitObjectLiteralBody(node, properties.length); - } - function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(187, startsOnNewLine); - result.operatorToken = ts.createSynthesizedNode(operator); - result.left = left; - result.right = right; - return result; - } - function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(172); - result.expression = parenthesizeForAccess(expression); - result.name = name; - return result; - } - function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(173); - result.expression = parenthesizeForAccess(expression); - result.argumentExpression = argumentExpression; - return result; - } - function parenthesizeForAccess(expr) { - while (expr.kind === 177 || - expr.kind === 195 || - expr.kind === 196) { - expr = expr.expression; - } - if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 175 && - expr.kind !== 8) { - return expr; - } - var node = ts.createSynthesizedNode(178); - node.expression = expr; - return node; - } - function emitComputedPropertyName(node) { - write("["); - emitExpressionForPropertyName(node); - write("]"); - } - function emitMethod(node) { - if (languageVersion >= 2 && node.asteriskToken) { - write("*"); - } - emit(node.name); - if (languageVersion < 2) { - write(": function "); - } - emitSignatureAndBody(node); - } - function emitPropertyAssignment(node) { - emit(node.name); - write(": "); - emitTrailingCommentsOfPosition(node.initializer.pos); - emit(node.initializer); - } - function isExportReference(node) { - var container = resolver.getReferencedExportContainer(node); - return !!container; - } - function isImportedReference(node) { - var declaration = resolver.getReferencedImportDeclaration(node); - return declaration && (declaration.kind === 231 || declaration.kind === 234); - } - function emitShorthandPropertyAssignment(node) { - writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { - write(": "); - emitExpressionIdentifier(node.name); - } - if (languageVersion >= 2 && node.objectAssignmentInitializer) { - write(" = "); - emit(node.objectAssignmentInitializer); - } - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(constantValue.toString()); - if (!compilerOptions.removeComments) { - var propertyName = node.kind === 172 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return node.kind === 172 || node.kind === 173 - ? resolver.getConstantValue(node) - : undefined; - } - function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) { - var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); - var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); - if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { - increaseIndent(); - writeLine(); - return true; - } - else { - if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); - } - return false; - } - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 && - node.expression.kind === 95 && - isInAsyncMethodWithSuperInES6(node)) { - var name_29 = ts.createSynthesizedNode(9); - name_29.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_29); - return; - } - emit(node.expression); - var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; - var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); - var shouldEmitSpace = false; - if (!indentedBeforeDot) { - if (node.expression.kind === 8) { - var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); - shouldEmitSpace = text.indexOf(ts.tokenToString(21)) < 0; - } - else { - var constantValue = tryGetConstEnumValue(node.expression); - shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; - } - } - if (shouldEmitSpace) { - write(" ."); - } - else { - write("."); - } - var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); - emit(node.name); - decreaseIndentIf(indentedBeforeDot, indentedAfterDot); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitQualifiedNameAsExpression(node, useFallback) { - if (node.left.kind === 69) { - emitEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = createAndRecordTempVariable(0); - write("("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(node.left, true); - write(") && "); - emitNodeWithoutSourceMap(temp); - } - else { - emitEntityNameAsExpression(node.left, false); - } - write("."); - emit(node.right); - } - function emitEntityNameAsExpression(node, useFallback) { - switch (node.kind) { - case 69: - if (useFallback) { - write("typeof "); - emitExpressionIdentifier(node); - write(" !== 'undefined' && "); - } - emitExpressionIdentifier(node); - break; - case 139: - emitQualifiedNameAsExpression(node, useFallback); - break; - default: - emitNodeWithoutSourceMap(node); - break; - } - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 && - node.expression.kind === 95 && - isInAsyncMethodWithSuperInES6(node)) { - emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 191; }); - } - function skipParentheses(node) { - while (node.kind === 178 || - node.kind === 177 || - node.kind === 195 || - node.kind === 196) { - node = node.expression; - } - return node; - } - function emitCallTarget(node) { - if (node.kind === 69 || node.kind === 97 || node.kind === 95) { - emit(node); - return node; - } - var temp = createAndRecordTempVariable(0); - write("("); - emit(temp); - write(" = "); - emit(node); - write(")"); - return temp; - } - function emitCallWithSpread(node) { - var target; - var expr = skipParentheses(node.expression); - if (expr.kind === 172) { - target = emitCallTarget(expr.expression); - write("."); - emit(expr.name); - } - else if (expr.kind === 173) { - target = emitCallTarget(expr.expression); - write("["); - emit(expr.argumentExpression); - write("]"); - } - else if (expr.kind === 95) { - target = expr; - write("_super"); - } - else { - emit(node.expression); - } - write(".apply("); - if (target) { - if (target.kind === 95) { - emitThis(target); - } - else { - emit(target); - } - } - else { - write("void 0"); - } - write(", "); - emitListWithSpread(node.arguments, false, false, false, true); - write(")"); - } - function isInAsyncMethodWithSuperInES6(node) { - if (languageVersion === 2) { - var container = ts.getSuperContainer(node, false); - if (container && resolver.getNodeCheckFlags(container) & (2048 | 4096)) { - return true; - } - } - return false; - } - function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { - var container = ts.getSuperContainer(superNode, false); - var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096; - write("_super("); - emit(argumentExpression); - write(isSuperBinding ? ").value" : ")"); - } - function emitCallExpression(node) { - if (languageVersion < 2 && hasSpreadElement(node.arguments)) { - emitCallWithSpread(node); - return; - } - var expression = node.expression; - var superCall = false; - var isAsyncMethodWithSuper = false; - if (expression.kind === 95) { - emitSuper(expression); - superCall = true; - } - else { - superCall = ts.isSuperPropertyOrElementAccess(expression); - isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); - emit(expression); - } - if (superCall && (languageVersion < 2 || isAsyncMethodWithSuper)) { - write(".call("); - emitThis(expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - if (languageVersion === 1 && - node.arguments && - hasSpreadElement(node.arguments)) { - write("("); - var target = emitCallTarget(node.expression); - write(".bind.apply("); - emit(target); - write(", [void 0].concat("); - emitListWithSpread(node.arguments, false, false, false, false); - write(")))"); - write("()"); - } - else { - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - } - function emitTaggedTemplateExpression(node) { - if (languageVersion >= 2) { - emit(node.tag); - write(" "); - emit(node.template); - } - else { - emitDownlevelTaggedTemplate(node); - } - } - function emitParenExpression(node) { - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 180) { - if (node.expression.kind === 177 || - node.expression.kind === 195 || - node.expression.kind === 196) { - var operand = node.expression.expression; - while (operand.kind === 177 || - operand.kind === 195 || - operand.kind === 196) { - operand = operand.expression; - } - if (operand.kind !== 185 && - operand.kind !== 183 && - operand.kind !== 182 && - operand.kind !== 181 && - operand.kind !== 186 && - operand.kind !== 175 && - !(operand.kind === 174 && node.parent.kind === 175) && - !(operand.kind === 179 && node.parent.kind === 174) && - !(operand.kind === 8 && node.parent.kind === 172)) { - emit(operand); - return; - } - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(78)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(103)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(101)); - write(" "); - emit(node.expression); - } - function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) { - if (!isCurrentFileSystemExternalModule() || node.kind !== 69 || ts.nodeIsSynthesized(node)) { - return false; - } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 218 || node.parent.kind === 169); - var targetDeclaration = isVariableDeclarationOrBindingElement - ? node.parent - : resolver.getReferencedValueDeclaration(node); - return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, true); - } - function isNameOfExportedDeclarationInNonES6Module(node) { - if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { - return false; - } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); - } - function emitPrefixUnaryExpression(node) { - var isPlusPlusOrMinusMinus = (node.operator === 41 - || node.operator === 42); - var externalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - if (externalExportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - } - var internalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedDeclarationInNonES6Module(node.operand); - if (internalExportChanged) { - emitAliasEqual(node.operand); - } - write(ts.tokenToString(node.operator)); - if (node.operand.kind === 185) { - var operand = node.operand; - if (node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) { - write(" "); - } - else if (node.operator === 36 && (operand.operator === 36 || operand.operator === 42)) { - write(" "); - } - } - emit(node.operand); - if (externalExportChanged) { - write(")"); - } - } - function emitPostfixUnaryExpression(node) { - var externalExportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - var internalExportChanged = isNameOfExportedDeclarationInNonES6Module(node.operand); - if (externalExportChanged) { - write("(" + exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - write(ts.tokenToString(node.operator)); - emit(node.operand); - if (node.operator === 41) { - write(") - 1)"); - } - else { - write(") + 1)"); - } - } - else if (internalExportChanged) { - emitAliasEqual(node.operand); - emit(node.operand); - if (node.operator === 41) { - write(" += 1"); - } - else { - write(" -= 1"); - } - } - else { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - } - function shouldHoistDeclarationInSystemJsModule(node) { - return isSourceFileLevelDeclarationInSystemJsModule(node, false); - } - function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { - if (!node || !isCurrentFileSystemExternalModule()) { - return false; - } - var current = ts.getRootDeclaration(node).parent; - while (current) { - if (current.kind === 256) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); - } - else if (ts.isDeclaration(current)) { - return false; - } - else { - current = current.parent; - } - } - } - function emitExponentiationOperator(node) { - var leftHandSideExpression = node.left; - if (node.operatorToken.kind === 60) { - var synthesizedLHS = void 0; - var shouldEmitParentheses = false; - if (ts.isElementAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(173, false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); - synthesizedLHS.expression = identifier; - if (leftHandSideExpression.argumentExpression.kind !== 8 && - leftHandSideExpression.argumentExpression.kind !== 9) { - var tempArgumentExpression = createAndRecordTempVariable(268435456); - synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, true, leftHandSideExpression.expression); - } - else { - synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; - } - write(", "); - } - else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(172, false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); - synthesizedLHS.expression = identifier; - synthesizedLHS.name = leftHandSideExpression.name; - write(", "); - } - emit(synthesizedLHS || leftHandSideExpression); - write(" = "); - write("Math.pow("); - emit(synthesizedLHS || leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - if (shouldEmitParentheses) { - write(")"); - } - } - else { - write("Math.pow("); - emit(leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - } - } - function emitAliasEqual(name) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - emitStart(specifier.name); - emitContainingModuleName(specifier); - if (languageVersion === 0 && name.text === "default") { - write('["default"]'); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - } - emitEnd(specifier.name); - write(" = "); - } - return true; - } - function emitBinaryExpression(node) { - if (languageVersion < 2 && node.operatorToken.kind === 56 && - (node.left.kind === 171 || node.left.kind === 170)) { - emitDestructuring(node, node.parent.kind === 202); - } - else { - var isAssignment = ts.isAssignmentOperator(node.operatorToken.kind); - var externalExportChanged = isAssignment && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left); - if (externalExportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.left); - write("\", "); - } - var internalExportChanged = isAssignment && - isNameOfExportedDeclarationInNonES6Module(node.left); - if (internalExportChanged) { - emitAliasEqual(node.left); - } - if (node.operatorToken.kind === 38 || node.operatorToken.kind === 60) { - emitExponentiationOperator(node); - } - else { - emit(node.left); - var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 ? " " : undefined); - write(ts.tokenToString(node.operatorToken.kind)); - var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); - emit(node.right); - decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); - } - if (externalExportChanged) { - write(")"); - } - } - } - function synthesizedNodeStartsOnNewLine(node) { - return ts.nodeIsSynthesized(node) && node.startsOnNewLine; - } - function emitConditionalExpression(node) { - emit(node.condition); - var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); - write("?"); - var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); - emit(node.whenTrue); - decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); - write(":"); - var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); - emit(node.whenFalse); - decreaseIndentIf(indentedBeforeColon, indentedAfterColon); - } - function decreaseIndentIf(value1, value2) { - if (value1) { - decreaseIndent(); - } - if (value2) { - decreaseIndent(); - } - } - function isSingleLineEmptyBlock(node) { - if (node && node.kind === 199) { - var block = node; - return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); - } - } - function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - emitToken(15, node.pos); - write(" "); - emitToken(16, node.statements.end); - return; - } - emitToken(15, node.pos); - increaseIndent(); - if (node.kind === 226) { - ts.Debug.assert(node.parent.kind === 225); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 226) { - emitTempDeclarations(true); - } - decreaseIndent(); - writeLine(); - emitToken(16, node.statements.end); - } - function emitEmbeddedStatement(node) { - if (node.kind === 199) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 180); - write(";"); - } - function emitIfStatement(node) { - var endPos = emitToken(88, node.pos); - write(" "); - endPos = emitToken(17, endPos); - emit(node.expression); - emitToken(18, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(80, node.thenStatement.end); - if (node.elseStatement.kind === 203) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - } - function emitDoStatement(node) { - emitLoop(node, emitDoStatementWorker); - } - function emitDoStatementWorker(node, loop) { - write("do"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - if (node.statement.kind === 199) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - emitLoop(node, emitWhileStatementWorker); - } - function emitWhileStatementWorker(node, loop) { - write("while ("); - emit(node.expression); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function tryEmitStartOfVariableDeclarationList(decl) { - if (shouldHoistVariable(decl, true)) { - return false; - } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072) === 0) { - for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { - var varDecl = _b[_a]; - hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); - } - return false; - } - emitStart(decl); - if (decl && languageVersion >= 2) { - if (ts.isLet(decl)) { - write("let "); - } - else if (ts.isConst(decl)) { - write("const "); - } - else { - write("var "); - } - } - else { - write("var "); - } - return true; - } - function emitVariableDeclarationListSkippingUninitializedEntries(list) { - var started = false; - for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) { - var decl = _b[_a]; - if (!decl.initializer) { - continue; - } - if (!started) { - started = true; - } - else { - write(", "); - } - emit(decl); - } - return started; - } - function shouldConvertLoopBody(node) { - return languageVersion < 2 && - (resolver.getNodeCheckFlags(node) & 65536) !== 0; - } - function emitLoop(node, loopEmitter) { - var shouldConvert = shouldConvertLoopBody(node); - if (!shouldConvert) { - loopEmitter(node, undefined); - } - else { - var loop = convertLoopBody(node); - if (node.parent.kind === 214) { - emitLabelAndColon(node.parent); - } - loopEmitter(node, loop); - } - } - function convertLoopBody(node) { - var functionName = makeUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206: - case 207: - case 208: - var initializer = node.initializer; - if (initializer && initializer.kind === 219) { - loopInitializer = node.initializer; - } - break; - } - var loopParameters; - var loopOutParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072)) { - loopParameters = []; - for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { - var varDeclaration = _b[_a]; - processVariableDeclaration(varDeclaration.name); - } - } - var bodyIsBlock = node.statement.kind === 199; - var paramList = loopParameters ? loopParameters.join(", ") : ""; - writeLine(); - write("var " + functionName + " = function(" + paramList + ")"); - var convertedOuterLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (convertedOuterLoopState) { - if (convertedOuterLoopState.argumentsName) { - convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; - } - if (convertedOuterLoopState.thisName) { - convertedLoopState.thisName = convertedOuterLoopState.thisName; - } - if (convertedOuterLoopState.hoistedLocalVariables) { - convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; - } - } - write(" {"); - writeLine(); - increaseIndent(); - if (bodyIsBlock) { - emitLines(node.statement.statements); - } - else { - emit(node.statement); - } - writeLine(); - copyLoopOutParameters(convertedLoopState, 1, true); - decreaseIndent(); - writeLine(); - write("};"); - writeLine(); - if (loopOutParameters) { - write("var "); - for (var i = 0; i < loopOutParameters.length; i++) { - if (i !== 0) { - write(", "); - } - write(loopOutParameters[i].outParamName); - } - write(";"); - writeLine(); - } - if (convertedLoopState.argumentsName) { - if (convertedOuterLoopState) { - convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; - } - else { - write("var " + convertedLoopState.argumentsName + " = arguments;"); - writeLine(); - } - } - if (convertedLoopState.thisName) { - if (convertedOuterLoopState) { - convertedOuterLoopState.thisName = convertedLoopState.thisName; - } - else { - write("var " + convertedLoopState.thisName + " = this;"); - writeLine(); - } - } - if (convertedLoopState.hoistedLocalVariables) { - if (convertedOuterLoopState) { - convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; - } - else { - write("var "); - var seen = void 0; - for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { - var id = _d[_c]; - if (!seen) { - seen = {}; - } - else { - write(", "); - } - if (!ts.hasProperty(seen, id.text)) { - emit(id); - seen[id.text] = id.text; - } - } - write(";"); - writeLine(); - } - } - var currentLoopState = convertedLoopState; - convertedLoopState = convertedOuterLoopState; - return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function processVariableDeclaration(name) { - if (name.kind === 69) { - var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) - ? getGeneratedNameForNode(name) - : name.text; - loopParameters.push(nameText); - if (resolver.getNodeCheckFlags(name.parent) & 2097152) { - var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; - (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); - } - } - else { - for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { - var element = _b[_a]; - processVariableDeclaration(element.name); - } - } - } - } - function emitNormalLoopBody(node, emitAsEmbeddedStatement) { - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 | 4; - } - if (emitAsEmbeddedStatement) { - emitEmbeddedStatement(node.statement); - } - else if (node.statement.kind === 199) { - emitLines(node.statement.statements); - } - else { - writeLine(); - emit(node.statement); - } - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function copyLoopOutParameters(state, copyDirection, emitAsStatements) { - if (state.loopOutParameters) { - for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { - var outParam = _b[_a]; - if (copyDirection === 0) { - emitIdentifier(outParam.originalName); - write(" = " + outParam.outParamName); - } - else { - write(outParam.outParamName + " = "); - emitIdentifier(outParam.originalName); - } - if (emitAsStatements) { - write(";"); - writeLine(); - } - else { - write(", "); - } - } - } - } - function emitConvertedLoopCall(loop, emitAsBlock) { - if (emitAsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } - var isSimpleLoop = !(loop.state.nonLocalJumps & ~4) && - !loop.state.labeledNonLocalBreaks && - !loop.state.labeledNonLocalContinues; - var loopResult = makeUniqueName("state"); - if (!isSimpleLoop) { - write("var " + loopResult + " = "); - } - write(loop.functionName + "(" + loop.paramList + ");"); - writeLine(); - copyLoopOutParameters(loop.state, 0, true); - if (!isSimpleLoop) { - writeLine(); - if (loop.state.nonLocalJumps & 8) { - write("if (typeof " + loopResult + " === \"object\") "); - if (convertedLoopState) { - write("return " + loopResult + ";"); - convertedLoopState.nonLocalJumps |= 8; - } - else { - write("return " + loopResult + ".value;"); - } - writeLine(); - } - if (loop.state.nonLocalJumps & 2) { - write("if (" + loopResult + " === \"break\") break;"); - writeLine(); - } - emitDispatchTableForLabeledJumps(loopResult, loop.state, convertedLoopState); - } - if (emitAsBlock) { - writeLine(); - decreaseIndent(); - write("}"); - } - function emitDispatchTableForLabeledJumps(loopResultVariable, currentLoop, outerLoop) { - if (!currentLoop.labeledNonLocalBreaks && !currentLoop.labeledNonLocalContinues) { - return; - } - write("switch(" + loopResultVariable + ") {"); - increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, false, loopResultVariable, outerLoop); - decreaseIndent(); - writeLine(); - write("}"); - } - function emitDispatchEntriesForLabeledJumps(table, isBreak, loopResultVariable, outerLoop) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - writeLine(); - write("case \"" + labelMarker + "\": "); - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - if (isBreak) { - write("break "); - } - else { - write("continue "); - } - write(labelText + ";"); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - write("return " + loopResultVariable + ";"); - } - } - } - } - function emitForStatement(node) { - emitLoop(node, emitForStatementWorker); - } - function emitForStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - if (node.initializer && node.initializer.kind === 219) { - var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); - if (startIsEmitted) { - emitCommaList(variableDeclarationList.declarations); - } - else { - emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList); - } - } - else if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.incrementor); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 208) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } - else { - emitLoop(node, emitForInOrForOfStatementWorker); - } - } - function emitForInOrForOfStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - if (node.initializer.kind === 219) { - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList); - emit(variableDeclarationList.declarations[0]); - } - } - else { - emit(node.initializer); - } - if (node.kind === 207) { - write(" in "); - } - else { - write(" of "); - } - emit(node.expression); - emitToken(18, node.expression.end); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function emitDownLevelForOfStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - var counter = createTempVariable(268435456); - var rhsReference = ts.createSynthesizedNode(69); - rhsReference.text = node.expression.kind === 69 ? - makeUniqueName(node.expression.text) : - makeTempVariableName(0); - emitStart(node.expression); - write("var "); - emitNodeWithoutSourceMap(counter); - write(" = 0"); - emitEnd(node.expression); - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - write("; "); - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write(" < "); - emitNodeWithCommentsAndWithoutSourcemap(rhsReference); - write(".length"); - emitEnd(node.expression); - write("; "); - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write("++"); - emitEnd(node.expression); - emitToken(18, node.expression.end); - write(" {"); - writeLine(); - increaseIndent(); - var rhsIterationValue = createElementAccessExpression(rhsReference, counter); - emitStart(node.initializer); - if (node.initializer.kind === 219) { - write("var "); - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length > 0) { - var declaration = variableDeclarationList.declarations[0]; - if (ts.isBindingPattern(declaration.name)) { - emitDestructuring(declaration, false, rhsIterationValue); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(declaration); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - emitNodeWithoutSourceMap(createTempVariable(0)); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - var assignmentExpression = createBinaryExpression(node.initializer, 56, rhsIterationValue, false); - if (node.initializer.kind === 170 || node.initializer.kind === 171) { - emitDestructuring(assignmentExpression, true, undefined); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression); - } - } - emitEnd(node.initializer); - write(";"); - if (loop) { - writeLine(); - emitConvertedLoopCall(loop, false); - } - else { - emitNormalLoopBody(node, false); - } - writeLine(); - decreaseIndent(); - write("}"); - } - function emitBreakOrContinueStatement(node) { - if (convertedLoopState) { - var jump = node.kind === 210 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - write("return "); - copyLoopOutParameters(convertedLoopState, 1, false); - if (!node.label) { - if (node.kind === 210) { - convertedLoopState.nonLocalJumps |= 2; - write("\"break\";"); - } - else { - convertedLoopState.nonLocalJumps |= 4; - write("\"continue\";"); - } - } - else { - var labelMarker = void 0; - if (node.kind === 210) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); - } - write("\"" + labelMarker + "\";"); - } - return; - } - } - emitToken(node.kind === 210 ? 70 : 75, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - if (convertedLoopState) { - convertedLoopState.nonLocalJumps |= 8; - write("return { value: "); - if (node.expression) { - emit(node.expression); - } - else { - write("void 0"); - } - write(" };"); - return; - } - emitToken(94, node.pos); - emitOptional(" ", node.expression); - write(";"); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(96, node.pos); - write(" "); - emitToken(17, endPos); - emit(node.expression); - endPos = emitToken(18, node.expression.end); - write(" "); - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps |= 2; - } - emitCaseBlock(node.caseBlock, endPos); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function emitCaseBlock(node, startPos) { - emitToken(15, startPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(16, node.clauses.end); - } - function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); - } - function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 249) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(72, node.pos); - write(" "); - emitToken(17, endPos); - emit(node.variableDeclaration); - emitToken(18, node.variableDeclaration ? node.variableDeclaration.end : endPos); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(76, node.pos); - write(";"); - } - function emitLabelAndColon(node) { - emit(node.label); - write(": "); - } - function emitLabeledStatement(node) { - if (!ts.isIterationStatement(node.statement, false) || !shouldConvertLoopBody(node.statement)) { - emitLabelAndColon(node); - } - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - emit(node.statement); - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 225); - return node; - } - function emitContainingModuleName(node) { - var container = getContainingModule(node); - write(container ? getGeneratedNameForNode(container) : "exports"); - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1) { - var container = getContainingModule(node); - if (container) { - write(getGeneratedNameForNode(container)); - write("."); - } - else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - emitNodeWithCommentsAndWithoutSourcemap(node.name); - emitEnd(node.name); - } - function createVoidZero() { - var zero = ts.createSynthesizedNode(8); - zero.text = "0"; - var result = ts.createSynthesizedNode(183); - result.expression = zero; - return result; - } - function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 256) { - ts.Debug.assert(!!(node.flags & 512) || node.kind === 235); - if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { - if (!isEs6Module) { - if (languageVersion !== 0) { - write('Object.defineProperty(exports, "__esModule", { value: true });'); - writeLine(); - } - else { - write("exports.__esModule = true;"); - writeLine(); - } - } - } - } - } - function emitExportMemberAssignment(node) { - if (node.flags & 1) { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { - write(exportFunctionForFile + "(\""); - if (node.flags & 512) { - write("default"); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - write("\", "); - emitDeclarationName(node); - write(")"); - } - else { - if (node.flags & 512) { - emitEs6ExportDefaultCompat(node); - if (languageVersion === 0) { - write('exports["default"]'); - } - else { - write("exports.default"); - } - } - else { - emitModuleMemberName(node); - } - write(" = "); - emitDeclarationName(node); - } - emitEnd(node); - write(";"); - } - } - function emitExportMemberAssignments(name) { - if (modulekind === ts.ModuleKind.System) { - return; - } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - writeLine(); - emitStart(specifier.name); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - emitEnd(specifier.name); - write(" = "); - emitExpressionIdentifier(name); - write(";"); - } - } - } - function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === ts.ModuleKind.System); - if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { - return; - } - writeLine(); - emitStart(specifier.name); - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write("\", "); - emitExpressionIdentifier(specifier.propertyName || specifier.name); - write(")"); - emitEnd(specifier.name); - write(";"); - } - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { - if (shouldEmitCommaBeforeAssignment) { - write(", "); - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(name); - write("\", "); - } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 218 || name.parent.kind === 169); - emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); - withTemporaryNoSourceMap(function () { - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - }); - emitEnd(nodeForSourceMap, true); - if (exportChanged) { - write(")"); - } - } - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { - var identifier = createTempVariable(0); - if (!canDefineTempVariablesInPlace) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); - return identifier; - } - function isFirstVariableDeclaration(root) { - return root.kind === 218 && - root.parent.kind === 219 && - root.parent.declarations[0] === root; - } - function emitDestructuring(root, isAssignmentExpressionStatement, value) { - var emitCount = 0; - var canDefineTempVariablesInPlace = false; - if (root.kind === 218) { - var isExported = ts.getCombinedNodeFlags(root) & 1; - var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); - canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; - } - else if (root.kind === 142) { - canDefineTempVariablesInPlace = true; - } - if (root.kind === 187) { - emitAssignmentExpression(root); - } - else { - ts.Debug.assert(!isAssignmentExpressionStatement); - if (isFirstVariableDeclaration(root)) { - sourceMap.changeEmitSourcePos(); - } - emitBindingElement(root, value); - } - function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { - if (expr.kind === 69 && reuseIdentifierExpressions) { - return expr; - } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); - emitCount++; - return identifier; - } - function createDefaultValueCheck(value, defaultValue, sourceMapNode) { - value = ensureIdentifier(value, true, sourceMapNode); - var equals = ts.createSynthesizedNode(187); - equals.left = value; - equals.operatorToken = ts.createSynthesizedNode(32); - equals.right = createVoidZero(); - return createConditionalExpression(equals, defaultValue, value); - } - function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(188); - cond.condition = condition; - cond.questionToken = ts.createSynthesizedNode(53); - cond.whenTrue = whenTrue; - cond.colonToken = ts.createSynthesizedNode(54); - cond.whenFalse = whenFalse; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createSynthesizedNode(8); - node.text = "" + value; - return node; - } - function createPropertyAccessForDestructuringProperty(object, propName) { - var index; - var nameIsComputed = propName.kind === 140; - if (nameIsComputed) { - index = ensureIdentifier(propName.expression, false, propName); - } - else { - index = ts.createSynthesizedNode(propName.kind); - index.text = ts.unescapeIdentifier(propName.text); - } - return !nameIsComputed && index.kind === 69 - ? createPropertyAccessExpression(object, index) - : createElementAccessExpression(object, index); - } - function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(174); - var sliceIdentifier = ts.createSynthesizedNode(69); - sliceIdentifier.text = "slice"; - call.expression = createPropertyAccessExpression(value, sliceIdentifier); - call.arguments = ts.createSynthesizedNodeArray(); - call.arguments[0] = createNumericLiteral(sliceIndex); - return call; - } - function emitObjectLiteralAssignment(target, value, sourceMapNode) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value, true, sourceMapNode); - } - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var p = properties_5[_a]; - if (p.kind === 253 || p.kind === 254) { - var propName = p.name; - var target_1 = p.kind === 254 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, sourceMapNode) { - var elements = target.elements; - if (elements.length !== 1) { - value = ensureIdentifier(value, true, sourceMapNode); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 193) { - if (e.kind !== 191) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); - } - else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); - } - } - } - } - function emitDestructuringAssignment(target, value, sourceMapNode) { - if (target.kind === 254) { - if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); - } - target = target.name; - } - else if (target.kind === 187 && target.operatorToken.kind === 56) { - value = createDefaultValueCheck(value, target.right, sourceMapNode); - target = target.left; - } - if (target.kind === 171) { - emitObjectLiteralAssignment(target, value, sourceMapNode); - } - else if (target.kind === 170) { - emitArrayLiteralAssignment(target, value, sourceMapNode); - } - else { - emitAssignment(target, value, emitCount > 0, sourceMapNode); - emitCount++; - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) { - emit(value); - } - else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); - } - else { - if (root.parent.kind !== 178) { - write("("); - } - value = ensureIdentifier(value, true, root); - emitDestructuringAssignment(target, value, root); - write(", "); - emit(value); - if (root.parent.kind !== 178) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - if (target.initializer) { - value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; - } - else if (!value) { - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0, target); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (pattern.kind === 167) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); - } - else if (element.kind !== 193) { - if (!element.dotDotDotToken) { - emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); - } - else if (i === numElements - 1) { - emitBindingElement(element, createSliceCall(value, i)); - } - } - } - } - else { - emitAssignment(target.name, value, emitCount > 0, target); - emitCount++; - } - } - } - function emitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name)) { - var isExported = ts.getCombinedNodeFlags(node) & 1; - if (languageVersion >= 2 && (!isExported || modulekind === ts.ModuleKind.ES6)) { - var isTopLevelDeclarationInSystemModule = modulekind === ts.ModuleKind.System && - shouldHoistVariable(node, true); - if (isTopLevelDeclarationInSystemModule) { - write("("); - } - emit(node.name); - emitOptional(" = ", node.initializer); - if (isTopLevelDeclarationInSystemModule) { - write(")"); - } - } - else { - emitDestructuring(node, false); - } - } - else { - var initializer = node.initializer; - if (!initializer && - languageVersion < 2 && - node.name.kind === 69) { - var container = ts.getEnclosingBlockScopeContainer(node); - var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || - (isCapturedInFunction && isDeclaredInLoop && container.kind === 199 && ts.isIterationStatement(container.parent, false)); - var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 && - !emittedAsTopLevel; - var emitExplicitInitializer = emittedAsNestedLetDeclaration && - container.kind !== 207 && - container.kind !== 208 && - (!resolver.isDeclarationWithCollidingName(node) || - (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, false))); - if (emitExplicitInitializer) { - initializer = createVoidZero(); - } - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(node.name); - write("\", "); - } - emitModuleMemberName(node); - emitOptional(" = ", initializer); - if (exportChanged) { - write(")"); - } - } - } - function emitExportVariableAssignments(node) { - if (node.kind === 193) { - return; - } - var name = node.name; - if (name.kind === 69) { - emitExportMemberAssignments(name); - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, emitExportVariableAssignments); - } - } - function isES6ExportedDeclaration(node) { - return !!(node.flags & 1) && - modulekind === ts.ModuleKind.ES6 && - node.parent.kind === 256; - } - function emitVariableStatement(node) { - var startIsEmitted = false; - if (node.flags & 1) { - if (isES6ExportedDeclaration(node)) { - write("export "); - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - } - else { - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - if (startIsEmitted) { - emitCommaList(node.declarationList.declarations); - write(";"); - } - else { - var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); - if (atLeastOneItem) { - write(";"); - } - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); - } - } - function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - if (!(node.flags & 1)) { - return true; - } - if (isES6ExportedDeclaration(node)) { - return true; - } - for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { - var declaration = _b[_a]; - if (declaration.initializer) { - return true; - } - } - return false; - } - function emitParameter(node) { - if (languageVersion < 2) { - if (ts.isBindingPattern(node.name)) { - var name_30 = createTempVariable(0); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name_30); - emit(name_30); - } - else { - emit(node.name); - } - } - else { - if (node.dotDotDotToken) { - write("..."); - } - emit(node.name); - emitOptional(" = ", node.initializer); - } - } - function emitDefaultValueAssignments(node) { - if (languageVersion < 2) { - var tempIndex_1 = 0; - ts.forEach(node.parameters, function (parameter) { - if (parameter.dotDotDotToken) { - return; - } - var paramName = parameter.name, initializer = parameter.initializer; - if (ts.isBindingPattern(paramName)) { - var hasBindingElements = paramName.elements.length > 0; - if (hasBindingElements || initializer) { - writeLine(); - write("var "); - if (hasBindingElements) { - emitDestructuring(parameter, false, tempParameters[tempIndex_1]); - } - else { - emit(tempParameters[tempIndex_1]); - write(" = "); - emit(initializer); - } - write(";"); - } - tempIndex_1++; - } - else if (initializer) { - writeLine(); - emitStart(parameter); - write("if ("); - emitNodeWithoutSourceMap(paramName); - write(" === void 0)"); - emitEnd(parameter); - write(" { "); - emitStart(parameter); - emitNodeWithCommentsAndWithoutSourcemap(paramName); - write(" = "); - emitNodeWithCommentsAndWithoutSourcemap(initializer); - emitEnd(parameter); - write("; }"); - } - }); - } - } - function emitRestParameter(node) { - if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - if (ts.isBindingPattern(restParam.name)) { - return; - } - var tempName = createTempVariable(268435456).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - write(node.kind === 149 ? "get " : "set "); - emit(node.name); - emitSignatureAndBody(node); - } - function shouldEmitAsArrowFunction(node) { - return node.kind === 180 && languageVersion >= 2; - } - function emitDeclarationName(node) { - if (node.name) { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - else { - write(getGeneratedNameForNode(node)); - } - } - function shouldEmitFunctionName(node) { - if (node.kind === 179) { - return !!node.name; - } - if (node.kind === 220) { - return !!node.name || modulekind !== ts.ModuleKind.ES6; - } - } - function emitFunctionDeclaration(node) { - if (ts.nodeIsMissing(node.body)) { - return emitCommentsOnNotEmittedNode(node); - } - var kind = node.kind, parent = node.parent; - if (kind !== 147 && - kind !== 146 && - parent && - parent.kind !== 253 && - parent.kind !== 174 && - parent.kind !== 170) { - emitLeadingComments(node); - } - emitStart(node); - if (!shouldEmitAsArrowFunction(node)) { - if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512) { - write("default "); - } - } - write("function"); - if (languageVersion >= 2 && node.asteriskToken) { - write("*"); - } - write(" "); - } - if (shouldEmitFunctionName(node)) { - emitDeclarationName(node); - } - emitSignatureAndBody(node); - if (modulekind !== ts.ModuleKind.ES6 && kind === 220 && parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - emitEnd(node); - if (kind !== 147 && - kind !== 146 && - kind !== 180) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; - var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; - emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); - } - write(")"); - decreaseIndent(); - } - function emitSignatureParametersForArrow(node) { - if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { - emit(node.parameters[0]); - return; - } - emitSignatureParameters(node); - } - function emitAsyncFunctionBodyForES6(node) { - var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 180; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; - if (!isArrowFunction) { - write(" {"); - increaseIndent(); - writeLine(); - if (resolver.getNodeCheckFlags(node) & 4096) { - writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); - writeLine(); - } - else if (resolver.getNodeCheckFlags(node) & 2048) { - write("const _super = name => super[name];"); - writeLine(); - } - write("return"); - } - write(" __awaiter(this"); - if (hasLexicalArguments) { - write(", arguments, "); - } - else { - write(", void 0, "); - } - if (languageVersion >= 2 || !promiseConstructor) { - write("void 0"); - } - else { - emitEntityNameAsExpression(promiseConstructor, false); - } - write(", function* ()"); - emitFunctionBody(node); - write(")"); - if (!isArrowFunction) { - write(";"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitFunctionBody(node) { - if (!node.body) { - write(" { }"); - } - else { - if (node.body.kind === 199) { - emitBlockFunctionBody(node, node.body); - } - else { - emitExpressionFunctionBody(node, node.body); - } - } - } - function emitSignatureAndBody(node) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - if (shouldEmitAsArrowFunction(node)) { - emitSignatureParametersForArrow(node); - write(" =>"); - } - else { - emitSignatureParameters(node); - } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAsyncFunctionBodyForES6(node); - } - else { - emitFunctionBody(node); - } - if (!isES6ExportedDeclaration(node)) { - emitExportMemberAssignment(node); - } - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitFunctionBodyPreamble(node) { - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - } - function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 || node.flags & 256) { - emitDownLevelExpressionFunctionBody(node, body); - return; - } - write(" "); - var current = body; - while (current.kind === 177) { - current = current.expression; - } - emitParenthesizedIf(body, current.kind === 171); - } - function emitDownLevelExpressionFunctionBody(node, body) { - write(" {"); - increaseIndent(); - var outPos = writer.getTextPos(); - emitDetachedCommentsAndUpdateCommentsInfo(node.body); - emitFunctionBodyPreamble(node); - var preambleEmitted = writer.getTextPos() !== outPos; - decreaseIndent(); - if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) { - write(" "); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTempDeclarations(false); - write(" "); - } - else { - increaseIndent(); - writeLine(); - emitLeadingComments(node.body); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTrailingComments(node.body); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - } - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - function emitBlockFunctionBody(node, body) { - write(" {"); - var initialTextPos = writer.getTextPos(); - increaseIndent(); - emitDetachedCommentsAndUpdateCommentsInfo(body.statements); - var startIndex = emitDirectivePrologues(body.statements, true); - emitFunctionBodyPreamble(node); - decreaseIndent(); - var preambleEmitted = writer.getTextPos() !== initialTextPos; - if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { - var statement = _b[_a]; - write(" "); - emit(statement); - } - emitTempDeclarations(false); - write(" "); - emitLeadingCommentsOfPosition(body.statements.end); - } - else { - increaseIndent(); - emitLinesStartingAt(body.statements, startIndex); - emitTempDeclarations(true); - writeLine(); - emitLeadingCommentsOfPosition(body.statements.end); - decreaseIndent(); - } - emitToken(16, body.statements.end); - } - function getSuperCallAtGivenIndex(ctor, index) { - if (!ctor.body) { - return undefined; - } - var statements = ctor.body.statements; - if (!statements || index >= statements.length) { - return undefined; - } - var statement = statements[index]; - if (statement.kind === 202) { - return ts.isSuperCallExpression(statement.expression) ? statement : undefined; - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 92) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNodeWithoutSourceMap(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - if (memberName.kind === 9 || memberName.kind === 8) { - write("["); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - write("]"); - } - else if (memberName.kind === 140) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - } - } - function getInitializedProperties(node, isStatic) { - var properties = []; - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 145 && isStatic === ((member.flags & 32) !== 0) && member.initializer) { - properties.push(member); - } - } - return properties; - } - function emitPropertyDeclarations(node, properties) { - for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { - var property = properties_6[_a]; - emitPropertyDeclaration(node, property); - } - } - function emitPropertyDeclaration(node, property, receiver, isExpression) { - writeLine(); - emitLeadingComments(property); - emitStart(property); - emitStart(property.name); - if (receiver) { - write(receiver); - } - else { - if (property.flags & 32) { - emitDeclarationName(node); - } - else { - write("this"); - } - } - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - emit(property.initializer); - if (!isExpression) { - write(";"); - } - emitEnd(property); - emitTrailingComments(property); - } - function emitMemberFunctionsForES5AndLower(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 198) { - writeLine(); - write(";"); - } - else if (member.kind === 147 || node.kind === 146) { - if (!member.body) { - return emitCommentsOnNotEmittedNode(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitClassMemberPrefix(node, member); - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitFunctionDeclaration(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 149 || member.kind === 150) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitMemberFunctionsForES6AndHigher(node) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.kind === 147 || node.kind === 146) && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - else if (member.kind === 147 || - member.kind === 149 || - member.kind === 150) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - if (member.flags & 32) { - write("static "); - } - if (member.kind === 149) { - write("get "); - } - else if (member.kind === 150) { - write("set "); - } - if (member.asteriskToken) { - write("*"); - } - emit(member.name); - emitSignatureAndBody(member); - emitEnd(member); - emitTrailingComments(member); - } - else if (member.kind === 198) { - writeLine(); - write(";"); - } - } - } - function emitConstructor(node, baseTypeElement) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - emitConstructorWorker(node, baseTypeElement); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitConstructorWorker(node, baseTypeElement) { - var hasInstancePropertyWithInitializer = false; - ts.forEach(node.members, function (member) { - if (member.kind === 148 && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - if (member.kind === 145 && member.initializer && (member.flags & 32) === 0) { - hasInstancePropertyWithInitializer = true; - } - }); - var ctor = ts.getFirstConstructorWithBody(node); - if (languageVersion >= 2 && !ctor && !hasInstancePropertyWithInitializer) { - return; - } - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - if (languageVersion < 2) { - write("function "); - emitDeclarationName(node); - emitSignatureParameters(ctor); - } - else { - write("constructor"); - if (ctor) { - emitSignatureParameters(ctor); - } - else { - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } - } - } - var startIndex = 0; - write(" {"); - increaseIndent(); - if (ctor) { - startIndex = emitDirectivePrologues(ctor.body.statements, true); - emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - var superCall; - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeElement) { - superCall = getSuperCallAtGivenIndex(ctor, startIndex); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeElement) { - writeLine(); - emitStart(baseTypeElement); - if (languageVersion < 2) { - write("_super.apply(this, arguments);"); - } - else { - write("super(...args);"); - } - emitEnd(baseTypeElement); - } - } - emitPropertyDeclarations(node, getInitializedProperties(node, false)); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) { - statements = statements.slice(1); - } - emitLinesStartingAt(statements, startIndex); - } - emitTempDeclarations(true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(16, ctor ? ctor.body.statements.end : node.members.end); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - } - function emitClassExpression(node) { - return emitClassLikeDeclaration(node); - } - function emitClassDeclaration(node) { - return emitClassLikeDeclaration(node); - } - function emitClassLikeDeclaration(node) { - if (languageVersion < 2) { - emitClassLikeDeclarationBelowES6(node); - } - else { - emitClassLikeDeclarationForES6AndHigher(node); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - } - function emitClassLikeDeclarationForES6AndHigher(node) { - var decoratedClassAlias; - var isHoistedDeclarationInSystemModule = shouldHoistDeclarationInSystemJsModule(node); - var isDecorated = ts.nodeIsDecorated(node); - var rewriteAsClassExpression = isDecorated || isHoistedDeclarationInSystemModule; - if (node.kind === 221) { - if (rewriteAsClassExpression) { - if (isDecorated && resolver.getNodeCheckFlags(node) & 524288) { - decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); - decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; - } - if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) { - write("export "); - } - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } - if (decoratedClassAlias !== undefined) { - write("" + decoratedClassAlias); - } - else { - emitDeclarationName(node); - } - write(" = "); - } - else if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512) { - write("default "); - } - } - } - var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; - var generatedName; - if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); - var synthesizedNode = ts.createSynthesizedNode(69); - synthesizedNode.text = generatedName; - recordTempDeclaration(synthesizedNode); - write("("); - increaseIndent(); - emit(synthesizedNode); - write(" = "); - } - write("class"); - if (node.name || (node.flags & 512 && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !rewriteAsClassExpression)) { - write(" "); - emitDeclarationName(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write(" extends "); - emit(baseTypeNode.expression); - } - write(" {"); - increaseIndent(); - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES6AndHigher(node); - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - if (rewriteAsClassExpression) { - if (decoratedClassAlias !== undefined) { - write(";"); - writeLine(); - if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { - write("export "); - } - write("let "); - emitDeclarationName(node); - write(" = " + decoratedClassAlias); - } - decoratedClassAliases[ts.getNodeId(node)] = undefined; - write(";"); - } - if (isClassExpressionWithStaticProperties) { - for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { - var property = staticProperties_1[_a]; - write(","); - writeLine(); - emitPropertyDeclaration(node, property, generatedName, true); - } - write(","); - writeLine(); - write(generatedName); - decreaseIndent(); - write(")"); - } - else { - writeLine(); - emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node, decoratedClassAlias); - } - if (!(node.flags & 1)) { - return; - } - if (modulekind !== ts.ModuleKind.ES6) { - emitExportMemberAssignment(node); - } - else { - if (node.flags & 512) { - if (isDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - else if (node.parent.kind !== 256) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); - } - } - } - function emitClassLikeDeclarationBelowES6(node) { - var isES6ExportedClass = isES6ExportedDeclaration(node); - if (node.kind === 221) { - if (isES6ExportedClass && !(node.flags & 512)) { - write("export "); - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - write("var "); - } - emitDeclarationName(node); - write(" = "); - } - write("(function ("); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - var saveConvertedLoopState = convertedLoopState; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - computedPropertyNamesToGeneratedNames = undefined; - increaseIndent(); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emitDeclarationName(node); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, true)); - writeLine(); - emitDecoratorsOfClass(node, undefined); - writeLine(); - emitToken(16, node.members.end, function () { - write("return "); - emitDeclarationName(node); - }); - write(";"); - emitTempDeclarations(true); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames; - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - emitStart(node); - write("("); - if (baseTypeNode) { - emit(baseTypeNode.expression); - } - write("))"); - if (node.kind === 221) { - write(";"); - } - emitEnd(node); - if (node.kind === 221 && !isES6ExportedClass) { - emitExportMemberAssignment(node); - } - else if (isES6ExportedClass && (node.flags & 512)) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - function emitClassMemberPrefix(node, member) { - emitDeclarationName(node); - if (!(member.flags & 32)) { - write(".prototype"); - } - } - function emitDecoratorsOfClass(node, decoratedClassAlias) { - emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 32); - emitDecoratorsOfConstructor(node, decoratedClassAlias); - } - function emitDecoratorsOfConstructor(node, decoratedClassAlias) { - var decorators = node.decorators; - var constructor = ts.getFirstConstructorWithBody(node); - var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); - if (!decorators && !firstParameterDecorator) { - return; - } - writeLine(); - emitStart(node.decorators || firstParameterDecorator); - emitDeclarationName(node); - if (decoratedClassAlias !== undefined) { - write(" = " + decoratedClassAlias); - } - write(" = __decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); - } - emitSerializedTypeMetadata(node, argumentsWritten >= 0); - decreaseIndent(); - writeLine(); - write("], "); - emitDeclarationName(node); - write(")"); - emitEnd(node.decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - function emitDecoratorsOfMembers(node, staticFlag) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.flags & 32) !== staticFlag) { - continue; - } - if (!ts.nodeCanBeDecorated(member)) { - continue; - } - var decorators = void 0; - var functionLikeMember = void 0; - if (ts.isAccessor(member)) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member !== accessors.firstAccessor) { - continue; - } - decorators = accessors.firstAccessor.decorators; - if (!decorators && accessors.secondAccessor) { - decorators = accessors.secondAccessor.decorators; - } - functionLikeMember = accessors.setAccessor; - } - else { - decorators = member.decorators; - if (member.kind === 147) { - functionLikeMember = member; - } - } - var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); - if (!decorators && !firstParameterDecorator) { - continue; - } - writeLine(); - emitStart(decorators || firstParameterDecorator); - write("__decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); - } - emitSerializedTypeMetadata(member, argumentsWritten > 0); - decreaseIndent(); - writeLine(); - write("], "); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - if (languageVersion > 0) { - if (member.kind !== 145) { - write(", null"); - } - else { - write(", void 0"); - } - } - write(")"); - emitEnd(decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - } - function emitDecoratorsOfParameters(node, leadingComma) { - var argumentsWritten = 0; - if (node) { - var parameterIndex_1 = 0; - for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { - var parameter = _b[_a]; - if (ts.nodeIsDecorated(parameter)) { - var decorators = parameter.decorators; - argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - write("__param(" + parameterIndex_1 + ", "); - emit(decorator.expression); - write(")"); - }); - leadingComma = true; - } - parameterIndex_1++; - } - } - return argumentsWritten; - } - function shouldEmitTypeMetadata(node) { - switch (node.kind) { - case 147: - case 149: - case 150: - case 145: - return true; - } - return false; - } - function shouldEmitReturnTypeMetadata(node) { - switch (node.kind) { - case 147: - return true; - } - return false; - } - function shouldEmitParamTypesMetadata(node) { - switch (node.kind) { - case 221: - case 147: - case 150: - return true; - } - return false; - } - function emitSerializedTypeOfNode(node) { - switch (node.kind) { - case 221: - write("Function"); - return; - case 145: - emitSerializedTypeNode(node.type); - return; - case 142: - emitSerializedTypeNode(node.type); - return; - case 149: - emitSerializedTypeNode(node.type); - return; - case 150: - emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - return; - } - if (ts.isFunctionLike(node)) { - write("Function"); - return; - } - write("void 0"); - } - function emitSerializedTypeNode(node) { - if (node) { - switch (node.kind) { - case 103: - write("void 0"); - return; - case 164: - emitSerializedTypeNode(node.type); - return; - case 156: - case 157: - write("Function"); - return; - case 160: - case 161: - write("Array"); - return; - case 154: - case 120: - write("Boolean"); - return; - case 132: - case 166: - write("String"); - return; - case 130: - write("Number"); - return; - case 133: - write("Symbol"); - return; - case 155: - emitSerializedTypeReferenceNode(node); - return; - case 158: - case 159: - case 162: - case 163: - case 117: - case 165: - break; - default: - ts.Debug.fail("Cannot serialize unexpected type node."); - break; - } - } - write("Object"); - } - function emitSerializedTypeReferenceNode(node) { - var location = node.parent; - while (ts.isDeclaration(location) || ts.isTypeNode(location)) { - location = location.parent; - } - var typeName = ts.cloneEntityName(node.typeName, location); - var result = resolver.getTypeReferenceSerializationKind(typeName); - switch (result) { - case ts.TypeReferenceSerializationKind.Unknown: - var temp = createAndRecordTempVariable(0); - write("(typeof ("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(typeName, true); - write(") === 'function' && "); - emitNodeWithoutSourceMap(temp); - write(") || Object"); - break; - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - emitEntityNameAsExpression(typeName, false); - break; - case ts.TypeReferenceSerializationKind.VoidType: - write("void 0"); - break; - case ts.TypeReferenceSerializationKind.BooleanType: - write("Boolean"); - break; - case ts.TypeReferenceSerializationKind.NumberLikeType: - write("Number"); - break; - case ts.TypeReferenceSerializationKind.StringLikeType: - write("String"); - break; - case ts.TypeReferenceSerializationKind.ArrayLikeType: - write("Array"); - break; - case ts.TypeReferenceSerializationKind.ESSymbolType: - if (languageVersion < 2) { - write("typeof Symbol === 'function' ? Symbol : Object"); - } - else { - write("Symbol"); - } - break; - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - write("Function"); - break; - case ts.TypeReferenceSerializationKind.ObjectType: - write("Object"); - break; - } - } - function emitSerializedParameterTypesOfNode(node) { - if (node) { - var valueDeclaration = void 0; - if (node.kind === 221) { - valueDeclaration = ts.getFirstConstructorWithBody(node); - } - else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { - valueDeclaration = node; - } - if (valueDeclaration) { - var parameters = valueDeclaration.parameters; - var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { - write(", "); - } - if (parameters[i].dotDotDotToken) { - var parameterType = parameters[i].type; - if (parameterType && parameterType.kind === 160) { - parameterType = parameterType.elementType; - } - else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { - parameterType = parameterType.typeArguments[0]; - } - else { - parameterType = undefined; - } - emitSerializedTypeNode(parameterType); - } - else { - emitSerializedTypeOfNode(parameters[i]); - } - } - } - } - } - } - function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node)) { - if (node.type) { - emitSerializedTypeNode(node.type); - return; - } - else if (ts.isAsyncFunctionLike(node)) { - write("Promise"); - return; - } - } - write("void 0"); - } - function emitSerializedTypeMetadata(node, writeComma) { - var argumentsWritten = 0; - if (compilerOptions.emitDecoratorMetadata) { - if (shouldEmitTypeMetadata(node)) { - if (writeComma) { - write(", "); - } - writeLine(); - write("__metadata('design:type', "); - emitSerializedTypeOfNode(node); - write(")"); - argumentsWritten++; - } - if (shouldEmitParamTypesMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:paramtypes', ["); - emitSerializedParameterTypesOfNode(node); - write("])"); - argumentsWritten++; - } - if (shouldEmitReturnTypeMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:returntype', "); - emitSerializedReturnTypeOfNode(node); - write(")"); - argumentsWritten++; - } - } - return argumentsWritten; - } - function emitInterfaceDeclaration(node) { - emitCommentsOnNotEmittedNode(node); - } - function shouldEmitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; - } - function emitEnumDeclaration(node) { - if (!shouldEmitEnumDeclaration(node)) { - return; - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - var isES6ExportedEnum = isES6ExportedDeclaration(node); - if (!(node.flags & 1) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 224))) { - emitStart(node); - if (isES6ExportedEnum) { - write("export "); - } - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 && !shouldHoistDeclarationInSystemJsModule(node)) { - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function emitEnumMember(node) { - var enumParent = node.parent; - emitStart(node); - write(getGeneratedNameForNode(enumParent)); - write("["); - write(getGeneratedNameForNode(enumParent)); - write("["); - emitExpressionForPropertyName(node.name); - write("] = "); - writeEnumMemberDeclarationValue(node); - write("] = "); - emitExpressionForPropertyName(node.name); - emitEnd(node); - write(";"); - } - function writeEnumMemberDeclarationValue(member) { - var value = resolver.getConstantValue(member); - if (value !== undefined) { - write(value.toString()); - return; - } - else if (member.initializer) { - emit(member.initializer); - } - else { - write("undefined"); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); - } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 32768); - } - function isFirstDeclarationOfKind(node, declarations, kind) { - return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); - } - function emitModuleDeclaration(node) { - var shouldEmit = shouldEmitModuleDeclaration(node); - if (!shouldEmit) { - return emitCommentsOnNotEmittedNode(node); - } - var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); - var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); - if (emitVarForModule) { - var isES6ExportedNamespace = isES6ExportedDeclaration(node); - if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 225)) { - emitStart(node); - if (isES6ExportedNamespace) { - write("export "); - } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - } - } - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") "); - ts.Debug.assert(node.body !== undefined); - if (node.body.kind === 226) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - emit(node.body); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(16, moduleBlock.statements.end); - } - write(")("); - if ((node.flags & 1) && !isES6ExportedDeclaration(node)) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.name.kind === 69 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { - return "\"" + renamedDependencies[moduleName.text] + "\""; - } - return undefined; - } - function emitRequire(moduleName) { - if (moduleName.kind === 9) { - write("require("); - var text = tryRenameExternalModule(moduleName); - if (text) { - write(text); - } - else { - emitStart(moduleName); - emitLiteral(moduleName); - emitEnd(moduleName); - } - emitToken(18, moduleName.end); - } - else { - write("require()"); - } - } - function getNamespaceDeclarationNode(node) { - if (node.kind === 229) { - return node; - } - var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { - return importClause.namedBindings; - } - } - function isDefaultImport(node) { - return node.kind === 230 && node.importClause && !!node.importClause.name; - } - function emitExportImportAssignments(node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - emitExportMemberAssignments(node.name); - } - ts.forEachChild(node, emitExportImportAssignments); - } - function emitImportDeclaration(node) { - if (modulekind !== ts.ModuleKind.ES6) { - return emitExternalImportDeclaration(node); - } - if (node.importClause) { - var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, true); - if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { - write("import "); - emitStart(node.importClause); - if (shouldEmitDefaultBindings) { - emit(node.importClause.name); - if (shouldEmitNamedBindings) { - write(", "); - } - } - if (shouldEmitNamedBindings) { - emitLeadingComments(node.importClause.namedBindings); - emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 232) { - write("* as "); - emit(node.importClause.namedBindings.name); - } - else { - write("{ "); - emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration); - write(" }"); - } - emitEnd(node.importClause.namedBindings); - emitTrailingComments(node.importClause.namedBindings); - } - emitEnd(node.importClause); - write(" from "); - emit(node.moduleSpecifier); - write(";"); - } - } - else { - write("import "); - emit(node.moduleSpecifier); - write(";"); - } - } - function emitExternalImportDeclaration(node) { - if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 229 && (node.flags & 1) !== 0; - var namespaceDeclaration = getNamespaceDeclarationNode(node); - var varOrConst = (languageVersion <= 1) ? "var " : "const "; - if (modulekind !== ts.ModuleKind.AMD) { - emitLeadingComments(node); - emitStart(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - if (!isExportedImport) { - write(varOrConst); - } - ; - emitModuleMemberName(namespaceDeclaration); - write(" = "); - } - else { - var isNakedImport = 230 && !node.importClause; - if (!isNakedImport) { - write(varOrConst); - write(getGeneratedNameForNode(node)); - write(" = "); - } - } - emitRequire(ts.getExternalModuleName(node)); - if (namespaceDeclaration && isDefaultImport(node)) { - write(", "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - else { - if (isExportedImport) { - emitModuleMemberName(namespaceDeclaration); - write(" = "); - emit(namespaceDeclaration.name); - write(";"); - } - else if (namespaceDeclaration && isDefaultImport(node)) { - write(varOrConst); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - write(";"); - } - emitExportImportAssignments(node); - } - } - } - function emitImportEqualsDeclaration(node) { - if (ts.isExternalModuleImportEqualsDeclaration(node)) { - emitExternalImportDeclaration(node); - return; - } - if (resolver.isReferencedAliasDeclaration(node) || - (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { - emitLeadingComments(node); - emitStart(node); - var variableDeclarationIsHoisted = shouldHoistVariable(node, true); - var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, true); - if (!variableDeclarationIsHoisted) { - ts.Debug.assert(!isExported); - if (isES6ExportedDeclaration(node)) { - write("export "); - write("var "); - } - else if (!(node.flags & 1)) { - write("var "); - } - } - if (isExported) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.name); - write("\", "); - } - emitModuleMemberName(node); - write(" = "); - emit(node.moduleReference); - if (isExported) { - write(")"); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - } - function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== ts.ModuleKind.System); - if (modulekind !== ts.ModuleKind.ES6) { - if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { - emitStart(node); - var generatedName = getGeneratedNameForNode(node); - if (node.exportClause) { - if (modulekind !== ts.ModuleKind.AMD) { - write("var "); - write(generatedName); - write(" = "); - emitRequire(ts.getExternalModuleName(node)); - write(";"); - } - for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) { - var specifier = _b[_a]; - if (resolver.isValueAliasDeclaration(specifier)) { - writeLine(); - emitStart(specifier); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write(" = "); - write(generatedName); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name); - write(";"); - emitEnd(specifier); - } - } - } - else { - if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - writeLine(); - write("__export("); - if (modulekind !== ts.ModuleKind.AMD) { - emitRequire(ts.getExternalModuleName(node)); - } - else { - write(generatedName); - } - write(");"); - } - } - emitEnd(node); - } - } - else { - if (!node.exportClause || resolver.isValueAliasDeclaration(node)) { - write("export "); - if (node.exportClause) { - write("{ "); - emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emit(node.moduleSpecifier); - } - write(";"); - } - } - } - function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === ts.ModuleKind.ES6); - var needsComma = false; - for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { - var specifier = specifiers_1[_a]; - if (shouldEmit(specifier)) { - if (needsComma) { - write(", "); - } - if (specifier.propertyName) { - emit(specifier.propertyName); - write(" as "); - } - emit(specifier.name); - needsComma = true; - } - } - } - function emitExportAssignment(node) { - if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === ts.ModuleKind.ES6) { - writeLine(); - emitStart(node); - write("export default "); - var expression = node.expression; - emit(expression); - if (expression.kind !== 220 && - expression.kind !== 221) { - write(";"); - } - emitEnd(node); - } - else { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System) { - write(exportFunctionForFile + "(\"default\","); - emit(node.expression); - write(")"); - } - else { - emitEs6ExportDefaultCompat(node); - emitContainingModuleName(node); - if (languageVersion === 0) { - write('["default"] = '); - } - else { - write(".default = "); - } - emit(node.expression); - } - write(";"); - emitEnd(node); - } - } - } - function collectExternalModuleInfo(sourceFile) { - externalImports = []; - exportSpecifiers = {}; - exportEquals = undefined; - hasExportStarsToExportValues = false; - for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { - var node = _b[_a]; - switch (node.kind) { - case 230: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, true)) { - externalImports.push(node); - } - break; - case 229: - if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { - externalImports.push(node); - } - break; - case 236: - if (node.moduleSpecifier) { - if (!node.exportClause) { - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - externalImports.push(node); - } - } - else { - for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { - var specifier = _d[_c]; - var name_31 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); - } - } - break; - case 235: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; - } - } - } - function emitExportStarHelper() { - if (hasExportStarsToExportValues) { - writeLine(); - write("function __export(m) {"); - increaseIndent(); - writeLine(); - write("for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function getLocalNameForExternalImport(node) { - var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); - } - if (node.kind === 230 && node.importClause) { - return getGeneratedNameForNode(node); - } - if (node.kind === 236 && node.moduleSpecifier) { - return getGeneratedNameForNode(node); - } - } - function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { - if (emitRelativePathAsModuleName) { - var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_32) { - return "\"" + name_32 + "\""; - } - } - var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 9) { - return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); - } - return undefined; - } - function emitVariableDeclarationsForImports() { - if (externalImports.length === 0) { - return; - } - writeLine(); - var started = false; - for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { - var importNode = externalImports_1[_a]; - var skipNode = importNode.kind === 236 || - (importNode.kind === 230 && !importNode.importClause); - if (skipNode) { - continue; - } - if (!started) { - write("var "); - started = true; - } - else { - write(", "); - } - write(getLocalNameForExternalImport(importNode)); - } - if (started) { - write(";"); - } - } - function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - if (!hasExportStarsToExportValues) { - return undefined; - } - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { - var hasExportDeclarationWithExportClause = false; - for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { - var externalImport = externalImports_2[_a]; - if (externalImport.kind === 236 && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - return emitExportStarFunction(undefined); - } - } - var exportedNamesStorageRef = makeUniqueName("exportedNames"); - writeLine(); - write("var " + exportedNamesStorageRef + " = {"); - increaseIndent(); - var started = false; - if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; i++) { - writeExportedName(exportedDeclarations[i]); - } - } - if (exportSpecifiers) { - for (var n in exportSpecifiers) { - for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) { - var specifier = _c[_b]; - writeExportedName(specifier.name); - } - } - } - for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { - var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 236) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - continue; - } - for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) { - var element = _f[_e]; - writeExportedName(element.name || element.propertyName); - } - } - decreaseIndent(); - writeLine(); - write("};"); - return emitExportStarFunction(exportedNamesStorageRef); - function emitExportStarFunction(localNames) { - var exportStarFunction = makeUniqueName("exportStar"); - writeLine(); - write("function " + exportStarFunction + "(m) {"); - increaseIndent(); - writeLine(); - write("var exports = {};"); - writeLine(); - write("for(var n in m) {"); - increaseIndent(); - writeLine(); - write("if (n !== \"default\""); - if (localNames) { - write("&& !" + localNames + ".hasOwnProperty(n)"); - } - write(") exports[n] = m[n];"); - decreaseIndent(); - writeLine(); - write("}"); - writeLine(); - write(exportFunctionForFile + "(exports);"); - decreaseIndent(); - writeLine(); - write("}"); - return exportStarFunction; - } - function writeExportedName(node) { - if (node.kind !== 69 && node.flags & 512) { - return; - } - if (started) { - write(","); - } - else { - started = true; - } - writeLine(); - write("'"); - if (node.kind === 69) { - emitNodeWithCommentsAndWithoutSourcemap(node); - } - else { - emitDeclarationName(node); - } - write("': true"); - } - } - function processTopLevelVariableAndFunctionDeclarations(node) { - var hoistedVars; - var hoistedFunctionDeclarations; - var exportedDeclarations; - visit(node); - if (hoistedVars) { - writeLine(); - write("var "); - var seen = {}; - for (var i = 0; i < hoistedVars.length; i++) { - var local = hoistedVars[i]; - var name_33 = local.kind === 69 - ? local - : local.name; - if (name_33) { - var text = ts.unescapeIdentifier(name_33.text); - if (ts.hasProperty(seen, text)) { - continue; - } - else { - seen[text] = text; - } - } - if (i !== 0) { - write(", "); - } - if (local.kind === 221 || local.kind === 225 || local.kind === 224) { - emitDeclarationName(local); - } - else { - emit(local); - } - var flags = ts.getCombinedNodeFlags(local.kind === 69 ? local.parent : local); - if (flags & 1) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(local); - } - } - write(";"); - } - if (hoistedFunctionDeclarations) { - for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { - var f = hoistedFunctionDeclarations_1[_a]; - writeLine(); - emit(f); - if (f.flags & 1) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(f); - } - } - } - return exportedDeclarations; - function visit(node) { - if (node.flags & 2) { - return; - } - if (node.kind === 220) { - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = []; - } - hoistedFunctionDeclarations.push(node); - return; - } - if (node.kind === 221) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - return; - } - if (node.kind === 224) { - if (shouldEmitEnumDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 225) { - if (shouldEmitModuleDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 218 || node.kind === 169) { - if (shouldHoistVariable(node, false)) { - var name_34 = node.name; - if (name_34.kind === 69) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(name_34); - } - else { - ts.forEachChild(name_34, visit); - } - } - return; - } - if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node.name); - return; - } - if (ts.isBindingPattern(node)) { - ts.forEach(node.elements, visit); - return; - } - if (!ts.isDeclaration(node)) { - ts.forEachChild(node, visit); - } - } - } - function shouldHoistVariable(node, checkIfSourceFileLevelDecl) { - if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { - return false; - } - return (ts.getCombinedNodeFlags(node) & 3072) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 256; - } - function isCurrentFileSystemExternalModule() { - return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; - } - function emitSystemModuleBody(node, dependencyGroups, startIndex) { - emitVariableDeclarationsForImports(); - writeLine(); - var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); - writeLine(); - write("return {"); - increaseIndent(); - writeLine(); - emitSetters(exportStarFunction, dependencyGroups); - writeLine(); - emitExecute(node, startIndex); - decreaseIndent(); - writeLine(); - write("}"); - emitTempDeclarations(true); - } - function emitSetters(exportStarFunction, dependencyGroups) { - write("setters:["); - for (var i = 0; i < dependencyGroups.length; i++) { - if (i !== 0) { - write(","); - } - writeLine(); - increaseIndent(); - var group = dependencyGroups[i]; - var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); - write("function (" + parameterName + ") {"); - increaseIndent(); - for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { - var entry = group_1[_a]; - var importVariableName = getLocalNameForExternalImport(entry) || ""; - switch (entry.kind) { - case 230: - if (!entry.importClause) { - break; - } - case 229: - ts.Debug.assert(importVariableName !== ""); - writeLine(); - write(importVariableName + " = " + parameterName + ";"); - writeLine(); - break; - case 236: - ts.Debug.assert(importVariableName !== ""); - if (entry.exportClause) { - writeLine(); - write(exportFunctionForFile + "({"); - writeLine(); - increaseIndent(); - for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { - if (i_1 !== 0) { - write(","); - writeLine(); - } - var e = entry.exportClause.elements[i_1]; - write("\""); - emitNodeWithCommentsAndWithoutSourcemap(e.name); - write("\": " + parameterName + "[\""); - emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name); - write("\"]"); - } - decreaseIndent(); - writeLine(); - write("});"); - } - else { - writeLine(); - write(exportStarFunction + "(" + parameterName + ");"); - } - writeLine(); - break; - } - } - decreaseIndent(); - write("}"); - decreaseIndent(); - } - write("],"); - } - function emitExecute(node, startIndex) { - write("execute: function() {"); - increaseIndent(); - writeLine(); - for (var i = startIndex; i < node.statements.length; i++) { - var statement = node.statements[i]; - switch (statement.kind) { - case 220: - case 230: - continue; - case 236: - if (!statement.moduleSpecifier) { - for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { - var element = _b[_a]; - emitExportSpecifierInSystemModule(element); - } - } - continue; - case 229: - if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { - continue; - } - default: - writeLine(); - emit(statement); - } - } - decreaseIndent(); - writeLine(); - write("}"); - } - function writeModuleName(node, emitRelativePathAsModuleName) { - var moduleName = node.moduleName; - if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { - write("\"" + moduleName + "\", "); - } - } - function emitSystemModule(node, emitRelativePathAsModuleName) { - collectExternalModuleInfo(node); - ts.Debug.assert(!exportFunctionForFile); - exportFunctionForFile = makeUniqueName("exports"); - contextObjectForFile = makeUniqueName("context"); - writeLine(); - write("System.register("); - writeModuleName(node, emitRelativePathAsModuleName); - write("["); - var groupIndices = {}; - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); - if (text === undefined) { - continue; - } - var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { - var groupIndex = groupIndices[key]; - dependencyGroups[groupIndex].push(externalImports[i]); - continue; - } - else { - groupIndices[key] = dependencyGroups.length; - dependencyGroups.push([externalImports[i]]); - } - if (i !== 0) { - write(", "); - } - write(text); - } - write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); - writeLine(); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - writeLine(); - write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); - writeLine(); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitSystemModuleBody(node, dependencyGroups, startIndex); - decreaseIndent(); - writeLine(); - write("});"); - } - function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - var aliasedModuleNames = []; - var unaliasedModuleNames = []; - var importAliasNames = []; - for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) { - var amdDependency = _b[_a]; - if (amdDependency.name) { - aliasedModuleNames.push('"' + amdDependency.path + '"'); - importAliasNames.push(amdDependency.name); - } - else { - unaliasedModuleNames.push('"' + amdDependency.path + '"'); - } - } - for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { - var importNode = externalImports_4[_c]; - var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); - var importAliasName = getLocalNameForExternalImport(importNode); - if (includeNonAmdDependencies && importAliasName) { - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(importAliasName); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); - emitAMDDependencyList(dependencyNames); - write(", "); - emitAMDFactoryHeader(dependencyNames); - } - function emitAMDDependencyList(_a) { - var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames; - write('["require", "exports"'); - if (aliasedModuleNames.length) { - write(", "); - write(aliasedModuleNames.join(", ")); - } - if (unaliasedModuleNames.length) { - write(", "); - write(unaliasedModuleNames.join(", ")); - } - write("]"); - } - function emitAMDFactoryHeader(_a) { - var importAliasNames = _a.importAliasNames; - write("function (require, exports"); - if (importAliasNames.length) { - write(", "); - write(importAliasNames.join(", ")); - } - write(") {"); - } - function emitAMDModule(node, emitRelativePathAsModuleName) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - writeLine(); - write("define("); - writeModuleName(node, emitRelativePathAsModuleName); - emitAMDDependencies(node, true, emitRelativePathAsModuleName); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(true); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, false, !compilerOptions.noImplicitUseStrict); - emitEmitHelpers(node); - collectExternalModuleInfo(node); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(false); - emitTempDeclarations(true); - } - function emitUMDModule(node) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - var dependencyNames = getAMDDependencyNames(node, false); - writeLines("(function (factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define("); - emitAMDDependencyList(dependencyNames); - write(", factory);"); - writeLines(" }\n})("); - emitAMDFactoryHeader(dependencyNames); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(true); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitES6Module(node) { - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - var startIndex = emitDirectivePrologues(node.statements, false); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - } - function emitExportEquals(emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - writeLine(); - emitStart(exportEquals); - write(emitAsReturn ? "return " : "module.exports = "); - emit(exportEquals.expression); - write(";"); - emitEnd(exportEquals); - } - } - function emitJsxElement(node) { - switch (compilerOptions.jsx) { - case 2: - jsxEmitReact(node); - break; - case 1: - default: - jsxEmitPreserve(node); - break; - } - } - function trimReactWhitespaceAndApplyEntities(node) { - var result = undefined; - var text = ts.getTextOfNode(node, true); - var firstNonWhitespace = 0; - var lastNonWhitespace = -1; - for (var i = 0; i < text.length; i++) { - var c = text.charCodeAt(i); - if (ts.isLineBreak(c)) { - if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { - var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - firstNonWhitespace = -1; - } - else if (!ts.isWhiteSpaceSingleLine(c)) { - lastNonWhitespace = i; - if (firstNonWhitespace === -1) { - firstNonWhitespace = i; - } - } - } - if (firstNonWhitespace !== -1) { - var part = text.substr(firstNonWhitespace); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - if (result) { - result = result.replace(/&(\w+);/g, function (s, m) { - if (entities[m] !== undefined) { - var ch = String.fromCharCode(entities[m]); - return ch === '"' ? "\\\"" : ch; - } - else { - return s; - } - }); - } - return result; - } - function isJsxChildEmittable(child) { - if (child.kind === 248) { - return !!child.expression; - } - else if (child.kind === 244) { - return !!getTextToEmit(child); - } - return true; - } - ; - function getTextToEmit(node) { - switch (compilerOptions.jsx) { - case 2: - var text = trimReactWhitespaceAndApplyEntities(node); - if (text === undefined || text.length === 0) { - return undefined; - } - else { - return text; - } - case 1: - default: - return ts.getTextOfNode(node, true); - } - } - function emitJsxText(node) { - switch (compilerOptions.jsx) { - case 2: - write('"'); - write(trimReactWhitespaceAndApplyEntities(node)); - write('"'); - break; - case 1: - default: - writer.writeLiteral(ts.getTextOfNode(node, true)); - break; - } - } - function emitJsxExpression(node) { - if (node.expression) { - switch (compilerOptions.jsx) { - case 1: - default: - write("{"); - emit(node.expression); - write("}"); - break; - case 2: - emit(node.expression); - break; - } - } - } - function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; - } - function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { - if (writeUseStrict) { - if (startWithNewLine) { - writeLine(); - } - write("\"use strict\";"); - } - } - function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { - var foundUseStrict = false; - for (var i = 0; i < statements.length; i++) { - if (ts.isPrologueDirective(statements[i])) { - if (isUseStrictPrologue(statements[i])) { - foundUseStrict = true; - } - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); - return i; - } - } - ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); - return statements.length; - } - function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line.length) { - writeLine(); - write(line); - } - } - } - function emitEmitHelpers(node) { - if (!compilerOptions.noEmitHelpers) { - if (languageVersion < 2 && !extendsEmitted && node.flags & 262144) { - writeLines(extendsHelper); - extendsEmitted = true; - } - if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 1073741824)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 524288) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); - } - decorateEmitted = true; - } - if (!paramEmitted && node.flags & 1048576) { - writeLines(paramHelper); - paramEmitted = true; - } - if (!awaiterEmitted && node.flags & 2097152) { - writeLines(awaiterHelper); - awaiterEmitted = true; - } - } - } - function emitSourceFileNode(node) { - writeLine(); - emitShebang(); - emitDetachedCommentsAndUpdateCommentsInfo(node); - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; - emitModule(node); - } - else { - bundleEmitDelegates[modulekind](node, true); - } - } - else { - var startIndex = emitDirectivePrologues(node.statements, false); - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - } - emitLeadingComments(node.endOfFileToken); - } - function emit(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - function emitNodeWithCommentsAndWithoutSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); - } - function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { - if (node) { - if (node.flags & 2) { - return emitCommentsOnNotEmittedNode(node); - } - if (isSpecializedCommentHandling(node)) { - return emitNodeWithoutSourceMap(node); - } - var emitComments_1 = shouldEmitLeadingAndTrailingComments(node); - if (emitComments_1) { - emitLeadingComments(node); - } - emitNodeConsideringSourcemap(node); - if (emitComments_1) { - emitTrailingComments(node); - } - } - } - function emitNodeWithSourceMap(node) { - if (node) { - emitStart(node); - emitNodeWithoutSourceMap(node); - emitEnd(node); - } - } - function emitNodeWithoutSourceMap(node) { - if (node) { - emitJavaScriptWorker(node); - } - } - function changeSourceMapEmit(writer) { - sourceMap = writer; - emitStart = writer.emitStart; - emitEnd = writer.emitEnd; - emitPos = writer.emitPos; - setSourceFile = writer.setSourceFile; - } - function withTemporaryNoSourceMap(callback) { - var prevSourceMap = sourceMap; - setSourceMapWriterEmit(ts.getNullSourceMapWriter()); - callback(); - setSourceMapWriterEmit(prevSourceMap); - } - function isSpecializedCommentHandling(node) { - switch (node.kind) { - case 222: - case 220: - case 230: - case 229: - case 223: - case 235: - return true; - } - } - function shouldEmitLeadingAndTrailingComments(node) { - switch (node.kind) { - case 200: - return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 225: - return shouldEmitModuleDeclaration(node); - case 224: - return shouldEmitEnumDeclaration(node); - } - ts.Debug.assert(!isSpecializedCommentHandling(node)); - if (node.kind !== 199 && - node.parent && - node.parent.kind === 180 && - node.parent.body === node && - languageVersion <= 1) { - return false; - } - return true; - } - function emitJavaScriptWorker(node) { - switch (node.kind) { - case 69: - return emitIdentifier(node); - case 142: - return emitParameter(node); - case 147: - case 146: - return emitMethod(node); - case 149: - case 150: - return emitAccessor(node); - case 97: - return emitThis(node); - case 95: - return emitSuper(node); - case 93: - return write("null"); - case 99: - return write("true"); - case 84: - return write("false"); - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - return emitLiteral(node); - case 189: - return emitTemplateExpression(node); - case 197: - return emitTemplateSpan(node); - case 241: - case 242: - return emitJsxElement(node); - case 244: - return emitJsxText(node); - case 248: - return emitJsxExpression(node); - case 139: - return emitQualifiedName(node); - case 167: - return emitObjectBindingPattern(node); - case 168: - return emitArrayBindingPattern(node); - case 169: - return emitBindingElement(node); - case 170: - return emitArrayLiteral(node); - case 171: - return emitObjectLiteral(node); - case 253: - return emitPropertyAssignment(node); - case 254: - return emitShorthandPropertyAssignment(node); - case 140: - return emitComputedPropertyName(node); - case 172: - return emitPropertyAccess(node); - case 173: - return emitIndexedAccess(node); - case 174: - return emitCallExpression(node); - case 175: - return emitNewExpression(node); - case 176: - return emitTaggedTemplateExpression(node); - case 177: - case 195: - case 196: - return emit(node.expression); - case 178: - return emitParenExpression(node); - case 220: - case 179: - case 180: - return emitFunctionDeclaration(node); - case 181: - return emitDeleteExpression(node); - case 182: - return emitTypeOfExpression(node); - case 183: - return emitVoidExpression(node); - case 184: - return emitAwaitExpression(node); - case 185: - return emitPrefixUnaryExpression(node); - case 186: - return emitPostfixUnaryExpression(node); - case 187: - return emitBinaryExpression(node); - case 188: - return emitConditionalExpression(node); - case 191: - return emitSpreadElementExpression(node); - case 190: - return emitYieldExpression(node); - case 193: - return; - case 199: - case 226: - return emitBlock(node); - case 200: - return emitVariableStatement(node); - case 201: - return write(";"); - case 202: - return emitExpressionStatement(node); - case 203: - return emitIfStatement(node); - case 204: - return emitDoStatement(node); - case 205: - return emitWhileStatement(node); - case 206: - return emitForStatement(node); - case 208: - case 207: - return emitForInOrForOfStatement(node); - case 209: - case 210: - return emitBreakOrContinueStatement(node); - case 211: - return emitReturnStatement(node); - case 212: - return emitWithStatement(node); - case 213: - return emitSwitchStatement(node); - case 249: - case 250: - return emitCaseOrDefaultClause(node); - case 214: - return emitLabeledStatement(node); - case 215: - return emitThrowStatement(node); - case 216: - return emitTryStatement(node); - case 252: - return emitCatchClause(node); - case 217: - return emitDebuggerStatement(node); - case 218: - return emitVariableDeclaration(node); - case 192: - return emitClassExpression(node); - case 221: - return emitClassDeclaration(node); - case 222: - return emitInterfaceDeclaration(node); - case 224: - return emitEnumDeclaration(node); - case 255: - return emitEnumMember(node); - case 225: - return emitModuleDeclaration(node); - case 230: - return emitImportDeclaration(node); - case 229: - return emitImportEqualsDeclaration(node); - case 236: - return emitExportDeclaration(node); - case 235: - return emitExportAssignment(node); - case 256: - return emitSourceFileNode(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - function isTripleSlashComment(comment) { - if (currentText.charCodeAt(comment.pos + 1) === 47 && - comment.pos + 2 < comment.end && - currentText.charCodeAt(comment.pos + 2) === 47) { - var textSubStr = currentText.substring(comment.pos, comment.end); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; - } - function getLeadingCommentsToEmit(node) { - if (node.parent) { - if (node.parent.kind === 256 || node.pos !== node.parent.pos) { - if (hasDetachedComments(node.pos)) { - return getLeadingCommentsWithoutDetachedComments(); - } - else { - return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); - } - } - } - } - function getTrailingCommentsToEmit(node) { - if (node.parent) { - if (node.parent.kind === 256 || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentText, node.end); - } - } - } - function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, false); - } - function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, true); - } - function emitLeadingCommentsWorker(node, isEmittedNode) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (isEmittedNode) { - leadingComments = getLeadingCommentsToEmit(node); - } - else { - if (node.pos === 0) { - leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); - } - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); - ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); - } - function emitTrailingComments(node) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = getTrailingCommentsToEmit(node); - ts.emitComments(currentText, currentLineMap, writer, trailingComments, false, newLine, writeComment); - } - function emitTrailingCommentsOfPosition(pos) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = ts.getTrailingCommentRanges(currentText, pos); - ts.emitComments(currentText, currentLineMap, writer, trailingComments, true, newLine, writeComment); - } - function emitLeadingCommentsOfPositionWorker(pos) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (hasDetachedComments(pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - leadingComments = ts.getLeadingCommentRanges(currentText, pos); - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); - ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); - } - function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, comment, newLine) { - emitPos(comment.pos); - ts.writeCommentRange(text, lineMap, writer, comment, newLine); - emitPos(comment.end); - } - function emitShebang() { - var shebang = ts.getShebang(currentText); - if (shebang) { - write(shebang); - writeLine(); - } - } - var _a, _b; - } - function emitFile(_a, sourceFiles, isBundledEmit) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { emittedFilesList.push(jsFilePath); @@ -36705,21 +44387,2015 @@ var ts; } } } + function printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNameSet = ts.createMap(); + isOwnFileEmit = !isBundledEmit; + if (isBundledEmit && moduleKind) { + for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { + var sourceFile = sourceFiles_4[_a]; + emitEmitHelpers(sourceFile); + } + } + ts.forEach(sourceFiles, printSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + } + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); + } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); + } + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + sourceMap.reset(); + comments.reset(); + writer.reset(); + tempFlags = 0; + currentSourceFile = undefined; + currentText = undefined; + extendsEmitted = false; + assignEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + isOwnFileEmit = false; + } + function printSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + currentFileIdentifiers = node.identifiers; + sourceMap.setSourceFile(node); + comments.setSourceFile(node); + emitNodeWithNotification(node, emitWorker); + } + function emit(node) { + emitNodeWithNotification(node, emitWithComments); + } + function emitWithComments(node) { + emitNodeWithComments(node, emitWithSourceMap); + } + function emitWithSourceMap(node) { + emitNodeWithSourceMap(node, emitWorker); + } + function emitIdentifierName(node) { + if (node) { + emitNodeWithNotification(node, emitIdentifierNameWithComments); + } + } + function emitIdentifierNameWithComments(node) { + emitNodeWithComments(node, emitWorker); + } + function emitExpression(node) { + emitNodeWithNotification(node, emitExpressionWithComments); + } + function emitExpressionWithComments(node) { + emitNodeWithComments(node, emitExpressionWithSourceMap); + } + function emitExpressionWithSourceMap(node) { + emitNodeWithSourceMap(node, emitExpressionWorker); + } + function emitNodeWithNotification(node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(node, emitCallback); + } + else { + emitCallback(node); + } + } + } + function emitNodeWithSourceMap(node, emitCallback) { + if (node) { + emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + emitCallback(node); + emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + function shouldSkipLeadingCommentsForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 16384) !== 0; + } + function shouldSkipLeadingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 512) !== 0; + } + function shouldSkipTrailingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 1024) !== 0; + } + function shouldSkipSourceMapForChildren(node) { + return (node.emitFlags & 2048) !== 0; + } + function emitWorker(node) { + if (tryEmitSubstitute(node, emitWorker, false)) { + return; + } + var kind = node.kind; + switch (kind) { + case 12: + case 13: + case 14: + return emitLiteral(node); + case 69: + return emitIdentifier(node); + case 74: + case 77: + case 82: + case 103: + case 110: + case 111: + case 112: + case 113: + case 115: + case 117: + case 118: + case 120: + case 122: + case 130: + case 128: + case 132: + case 133: + case 137: + return writeTokenNode(node); + case 139: + return emitQualifiedName(node); + case 140: + return emitComputedPropertyName(node); + case 141: + return emitTypeParameter(node); + case 142: + return emitParameter(node); + case 143: + return emitDecorator(node); + case 144: + return emitPropertySignature(node); + case 145: + return emitPropertyDeclaration(node); + case 146: + return emitMethodSignature(node); + case 147: + return emitMethodDeclaration(node); + case 148: + return emitConstructor(node); + case 149: + case 150: + return emitAccessorDeclaration(node); + case 151: + return emitCallSignature(node); + case 152: + return emitConstructSignature(node); + case 153: + return emitIndexSignature(node); + case 154: + return emitTypePredicate(node); + case 155: + return emitTypeReference(node); + case 156: + return emitFunctionType(node); + case 157: + return emitConstructorType(node); + case 158: + return emitTypeQuery(node); + case 159: + return emitTypeLiteral(node); + case 160: + return emitArrayType(node); + case 161: + return emitTupleType(node); + case 162: + return emitUnionType(node); + case 163: + return emitIntersectionType(node); + case 164: + return emitParenthesizedType(node); + case 194: + return emitExpressionWithTypeArguments(node); + case 165: + return emitThisType(node); + case 166: + return emitLiteralType(node); + case 167: + return emitObjectBindingPattern(node); + case 168: + return emitArrayBindingPattern(node); + case 169: + return emitBindingElement(node); + case 197: + return emitTemplateSpan(node); + case 198: + return emitSemicolonClassElement(node); + case 199: + return emitBlock(node); + case 200: + return emitVariableStatement(node); + case 201: + return emitEmptyStatement(node); + case 202: + return emitExpressionStatement(node); + case 203: + return emitIfStatement(node); + case 204: + return emitDoStatement(node); + case 205: + return emitWhileStatement(node); + case 206: + return emitForStatement(node); + case 207: + return emitForInStatement(node); + case 208: + return emitForOfStatement(node); + case 209: + return emitContinueStatement(node); + case 210: + return emitBreakStatement(node); + case 211: + return emitReturnStatement(node); + case 212: + return emitWithStatement(node); + case 213: + return emitSwitchStatement(node); + case 214: + return emitLabeledStatement(node); + case 215: + return emitThrowStatement(node); + case 216: + return emitTryStatement(node); + case 217: + return emitDebuggerStatement(node); + case 218: + return emitVariableDeclaration(node); + case 219: + return emitVariableDeclarationList(node); + case 220: + return emitFunctionDeclaration(node); + case 221: + return emitClassDeclaration(node); + case 222: + return emitInterfaceDeclaration(node); + case 223: + return emitTypeAliasDeclaration(node); + case 224: + return emitEnumDeclaration(node); + case 225: + return emitModuleDeclaration(node); + case 226: + return emitModuleBlock(node); + case 227: + return emitCaseBlock(node); + case 229: + return emitImportEqualsDeclaration(node); + case 230: + return emitImportDeclaration(node); + case 231: + return emitImportClause(node); + case 232: + return emitNamespaceImport(node); + case 233: + return emitNamedImports(node); + case 234: + return emitImportSpecifier(node); + case 235: + return emitExportAssignment(node); + case 236: + return emitExportDeclaration(node); + case 237: + return emitNamedExports(node); + case 238: + return emitExportSpecifier(node); + case 239: + return; + case 240: + return emitExternalModuleReference(node); + case 244: + return emitJsxText(node); + case 243: + return emitJsxOpeningElement(node); + case 245: + return emitJsxClosingElement(node); + case 246: + return emitJsxAttribute(node); + case 247: + return emitJsxSpreadAttribute(node); + case 248: + return emitJsxExpression(node); + case 249: + return emitCaseClause(node); + case 250: + return emitDefaultClause(node); + case 251: + return emitHeritageClause(node); + case 252: + return emitCatchClause(node); + case 253: + return emitPropertyAssignment(node); + case 254: + return emitShorthandPropertyAssignment(node); + case 255: + return emitEnumMember(node); + case 256: + return emitSourceFile(node); + } + if (ts.isExpression(node)) { + return emitExpressionWorker(node); + } + } + function emitExpressionWorker(node) { + if (tryEmitSubstitute(node, emitExpressionWorker, true)) { + return; + } + var kind = node.kind; + switch (kind) { + case 8: + return emitNumericLiteral(node); + case 9: + case 10: + case 11: + return emitLiteral(node); + case 69: + return emitIdentifier(node); + case 84: + case 93: + case 95: + case 99: + case 97: + return writeTokenNode(node); + case 170: + return emitArrayLiteralExpression(node); + case 171: + return emitObjectLiteralExpression(node); + case 172: + return emitPropertyAccessExpression(node); + case 173: + return emitElementAccessExpression(node); + case 174: + return emitCallExpression(node); + case 175: + return emitNewExpression(node); + case 176: + return emitTaggedTemplateExpression(node); + case 177: + return emitTypeAssertionExpression(node); + case 178: + return emitParenthesizedExpression(node); + case 179: + return emitFunctionExpression(node); + case 180: + return emitArrowFunction(node); + case 181: + return emitDeleteExpression(node); + case 182: + return emitTypeOfExpression(node); + case 183: + return emitVoidExpression(node); + case 184: + return emitAwaitExpression(node); + case 185: + return emitPrefixUnaryExpression(node); + case 186: + return emitPostfixUnaryExpression(node); + case 187: + return emitBinaryExpression(node); + case 188: + return emitConditionalExpression(node); + case 189: + return emitTemplateExpression(node); + case 190: + return emitYieldExpression(node); + case 191: + return emitSpreadElementExpression(node); + case 192: + return emitClassExpression(node); + case 193: + return; + case 195: + return emitAsExpression(node); + case 196: + return emitNonNullExpression(node); + case 241: + return emitJsxElement(node); + case 242: + return emitJsxSelfClosingElement(node); + case 288: + return emitPartiallyEmittedExpression(node); + } + } + function emitNumericLiteral(node) { + emitLiteral(node); + if (node.trailingComment) { + write(" /*" + node.trailingComment + "*/"); + } + } + function emitLiteral(node) { + var text = getLiteralTextOfNode(node); + if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) + && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else { + write(text); + } + } + function emitIdentifier(node) { + if (node.emitFlags & 16) { + writeLines(umdHelper); + } + else { + write(getTextOfNode(node, false)); + } + } + function emitQualifiedName(node) { + emitEntityName(node.left); + write("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + write("["); + emitExpression(node.expression); + write("]"); + } + function emitTypeParameter(node) { + emit(node.name); + emitWithPrefix(" extends ", node.constraint); + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitExpressionWithPrefix(" = ", node.initializer); + emitWithPrefix(": ", node.type); + } + function emitDecorator(decorator) { + write("@"); + emitExpression(decorator.expression); + } + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emitWithPrefix(": ", node.type); + emitExpressionWithPrefix(" = ", node.initializer); + write(";"); + } + function emitMethodSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.asteriskToken, "*"); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + write("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.kind === 149 ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitConstructSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitSemicolonClassElement(node) { + write(";"); + } + function emitTypePredicate(node) { + emit(node.parameterName); + write(" is "); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitConstructorType(node) { + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitTypeQuery(node) { + write("typeof "); + emit(node.exprName); + } + function emitTypeLiteral(node) { + write("{"); + emitList(node, node.members, 65); + write("}"); + } + function emitArrayType(node) { + emit(node.elementType); + write("[]"); + } + function emitTupleType(node) { + write("["); + emitList(node, node.elementTypes, 336); + write("]"); + } + function emitUnionType(node) { + emitList(node, node.types, 260); + } + function emitIntersectionType(node) { + emitList(node, node.types, 264); + } + function emitParenthesizedType(node) { + write("("); + emit(node.type); + write(")"); + } + function emitThisType(node) { + write("this"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitObjectBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("{}"); + } + else { + write("{"); + emitList(node, elements, 432); + write("}"); + } + } + function emitArrayBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + write("["); + emitList(node, node.elements, 304); + write("]"); + } + } + function emitBindingElement(node) { + emitWithSuffix(node.propertyName, ": "); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitArrayLiteralExpression(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + var preferNewLine = node.multiLine ? 32768 : 0; + emitExpressionList(node, elements, 4466 | preferNewLine); + } + } + function emitObjectLiteralExpression(node) { + var properties = node.properties; + if (properties.length === 0) { + write("{}"); + } + else { + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 32768 : 0; + var allowTrailingComma = languageVersion >= 1 ? 32 : 0; + emitList(node, properties, 978 | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + } + function emitPropertyAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(node.emitFlags & 1048576)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot); + write(shouldEmitDotDot ? ".." : "."); + increaseIndentIf(indentAfterDot); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + function needsDotDotForPropertyAccess(expression) { + if (expression.kind === 8) { + var text = getLiteralTextOfNode(expression); + return text.indexOf(ts.tokenToString(21)) < 0; + } + else { + var constantValue = tryGetConstEnumValue(expression); + return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + function emitElementAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + emitExpression(node.expression); + write("["); + emitExpression(node.argumentExpression); + write("]"); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 1296); + } + function emitNewExpression(node) { + write("new "); + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 9488); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + write(" "); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + if (node.type) { + write("<"); + emit(node.type); + write(">"); + } + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + write("("); + emitExpression(node.expression); + write(")"); + } + function emitFunctionExpression(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitWithPrefix(": ", node.type); + write(" =>"); + } + function emitDeleteExpression(node) { + write("delete "); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + write("typeof "); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + write("void "); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + write("await "); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + write(" "); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + var operand = node.operand; + return operand.kind === 185 + && ((node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) + || (node.operator === 36 && (operand.operator === 36 || operand.operator === 42))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 24; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + writeTokenText(node.operatorToken.kind); + increaseIndentIf(indentAfterOperator, " "); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, " "); + write("?"); + increaseIndentIf(indentAfterQuestion, " "); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, " "); + write(":"); + increaseIndentIf(indentAfterColon, " "); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 131072); + } + function emitYieldExpression(node) { + write(node.asteriskToken ? "yield*" : "yield"); + emitExpressionWithPrefix(" ", node.expression); + } + function emitSpreadElementExpression(node) { + write("..."); + emitExpression(node.expression); + } + function emitClassExpression(node) { + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + write(" as "); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + write("!"); + } + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + function emitBlock(node, format) { + if (isSingleLineEmptyBlock(node)) { + writeToken(15, node.pos, node); + write(" "); + writeToken(16, node.statements.end, node); + } + else { + writeToken(15, node.pos, node); + emitBlockStatements(node); + writeToken(16, node.statements.end, node); + } + } + function emitBlockStatements(node) { + if (node.emitFlags & 32) { + emitList(node, node.statements, 384); + } + else { + emitList(node, node.statements, 65); + } + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + write(";"); + } + function emitEmptyStatement(node) { + write(";"); + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + write(";"); + } + function emitIfStatement(node) { + var openParenPos = writeToken(88, node.pos, node); + write(" "); + writeToken(17, openParenPos, node); + emitExpression(node.expression); + writeToken(18, node.expression.end, node); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + writeToken(80, node.thenStatement.end, node); + if (node.elseStatement.kind === 203) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (ts.isBlock(node.statement)) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emitExpression(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos, node); + emitForBinding(node.initializer); + write(";"); + emitExpressionWithPrefix(" ", node.condition); + write(";"); + emitExpressionWithPrefix(" ", node.incrementor); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos); + emitForBinding(node.initializer); + write(" in "); + emitExpression(node.expression); + writeToken(18, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForOfStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos); + emitForBinding(node.initializer); + write(" of "); + emitExpression(node.expression); + writeToken(18, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 219) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + writeToken(75, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitBreakStatement(node) { + writeToken(70, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + writeToken(94, node.pos, node); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitWithStatement(node) { + write("with ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = writeToken(96, node.pos); + write(" "); + writeToken(17, openParenPos); + emitExpression(node.expression); + writeToken(18, node.expression.end); + write(" "); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function emitThrowStatement(node) { + write("throw"); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(76, node.pos); + write(";"); + } + function emitVariableDeclaration(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitVariableDeclarationList(node) { + write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + emitList(node, node.declarations, 272); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.asteriskToken ? "function* " : "function "); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + if (node.emitFlags & 4194304) { + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + tempFlags = savedTempFlags; + } + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + write(" "); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + write(";"); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { + if (body.emitFlags & 32) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2) + || shouldWriteClosingLineTerminator(body, body.statements, 2)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(parentNode, body) { + write(" {"); + increaseIndent(); + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker); + decreaseIndent(); + writeToken(16, body.statements.end, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + var statementOffset = emitPrologueDirectives(body.statements, true); + var helpersEmitted = emitHelpers(body); + if (statementOffset === 0 && !helpersEmitted && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 384); + increaseIndent(); + } + else { + emitList(body, body.statements, 1, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("class"); + emitNodeWithPrefix(" ", node.name, emitIdentifierName); + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 65); + write("}"); + if (indentedFlag) { + decreaseIndent(); + } + tempFlags = savedTempFlags; + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("interface "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256); + write(" {"); + emitList(node, node.members, 65); + write("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("type "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + write(" = "); + emit(node.type); + write(";"); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + write("enum "); + emit(node.name); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 81); + write("}"); + tempFlags = savedTempFlags; + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + write(node.flags & 16 ? "namespace " : "module "); + emit(node.name); + var body = node.body; + while (body.kind === 225) { + write("."); + emit(body.name); + body = body.body; + } + write(" "); + emit(body); + } + function emitModuleBlock(node) { + if (isSingleLineEmptyBlock(node)) { + write("{ }"); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + write("{"); + increaseIndent(); + emitBlockStatements(node); + write("}"); + tempFlags = savedTempFlags; + } + } + function emitCaseBlock(node) { + writeToken(15, node.pos); + emitList(node, node.clauses, 65); + writeToken(16, node.clauses.end); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + emit(node.name); + write(" = "); + emitModuleReference(node.moduleReference); + write(";"); + } + function emitModuleReference(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + if (node.importClause) { + emit(node.importClause); + write(" from "); + } + emitExpression(node.moduleSpecifier); + write(";"); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + write(", "); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + write("* as "); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + write(node.isExportEquals ? "export = " : "export default "); + emitExpression(node.expression); + write(";"); + } + function emitExportDeclaration(node) { + write("export "); + if (node.exportClause) { + emit(node.exportClause); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + emitExpression(node.moduleSpecifier); + } + write(";"); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + write("{"); + emitList(node, node.elements, 432); + write("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + write(" as "); + } + emit(node.name); + } + function emitExternalModuleReference(node) { + write("require("); + emitExpression(node.expression); + write(")"); + } + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 131072); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + write("<"); + emitJsxTagName(node.tagName); + write(" "); + emitList(node, node.attributes, 131328); + write("/>"); + } + function emitJsxOpeningElement(node) { + write("<"); + emitJsxTagName(node.tagName); + writeIfAny(node.attributes, " "); + emitList(node, node.attributes, 131328); + write(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, true)); + } + function emitJsxClosingElement(node) { + write(""); + } + function emitJsxAttribute(node) { + emit(node.name); + emitWithPrefix("=", node.initializer); + } + function emitJsxSpreadAttribute(node) { + write("{..."); + emitExpression(node.expression); + write("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + write("{"); + emitExpression(node.expression); + write("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitCaseClause(node) { + write("case "); + emitExpression(node.expression); + write(":"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitDefaultClause(node) { + write("default:"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitCaseOrDefaultClauseStatements(parentNode, statements) { + var emitAsSingleStatement = statements.length === 1 && + (ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (emitAsSingleStatement) { + write(" "); + emit(statements[0]); + } + else { + emitList(parentNode, statements, 81985); + } + } + function emitHeritageClause(node) { + write(" "); + writeTokenText(node.token); + write(" "); + emitList(node, node.types, 272); + } + function emitCatchClause(node) { + writeLine(); + var openParenPos = writeToken(72, node.pos); + write(" "); + writeToken(17, openParenPos); + emit(node.variableDeclaration); + writeToken(18, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + write(" "); + emit(node.block); + } + function emitPropertyAssignment(node) { + emit(node.name); + write(": "); + var initializer = node.initializer; + if (!shouldSkipLeadingCommentsForNode(initializer)) { + var commentRange = initializer.commentRange || initializer; + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + write(" = "); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitEnumMember(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitSourceFile(node) { + writeLine(); + emitShebang(); + emitBodyWithDetachedComments(node, node.statements, emitSourceFileWorker); + } + function emitSourceFileWorker(node) { + var statements = node.statements; + var statementOffset = emitPrologueDirectives(statements); + var savedTempFlags = tempFlags; + tempFlags = 0; + emitHelpers(node); + emitList(node, statements, 1, statementOffset); + tempFlags = savedTempFlags; + } + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitPrologueDirectives(statements, startWithNewLine) { + for (var i = 0; i < statements.length; i++) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + return i; + } + } + return statements.length; + } + function emitHelpers(node) { + var emitFlags = node.emitFlags; + var helpersEmitted = false; + if (emitFlags & 1) { + helpersEmitted = emitEmitHelpers(currentSourceFile); + } + if (emitFlags & 2) { + writeLines(exportStarHelper); + helpersEmitted = true; + } + if (emitFlags & 4) { + writeLines(superHelper); + helpersEmitted = true; + } + if (emitFlags & 8) { + writeLines(advancedSuperHelper); + helpersEmitted = true; + } + return helpersEmitted; + } + function emitEmitHelpers(node) { + if (compilerOptions.noEmitHelpers) { + return false; + } + if (compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + return false; + } + var helpersEmitted = false; + if ((languageVersion < 2) && (!extendsEmitted && node.flags & 1024)) { + writeLines(extendsHelper); + extendsEmitted = true; + helpersEmitted = true; + } + if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 16384)) { + writeLines(assignHelper); + assignEmitted = true; + } + if (!decorateEmitted && node.flags & 2048) { + writeLines(decorateHelper); + if (compilerOptions.emitDecoratorMetadata) { + writeLines(metadataHelper); + } + decorateEmitted = true; + helpersEmitted = true; + } + if (!paramEmitted && node.flags & 4096) { + writeLines(paramHelper); + paramEmitted = true; + helpersEmitted = true; + } + if (!awaiterEmitted && node.flags & 8192) { + writeLines(awaiterHelper); + if (languageVersion < 2) { + writeLines(generatorHelper); + } + awaiterEmitted = true; + helpersEmitted = true; + } + if (helpersEmitted) { + writeLine(); + } + return helpersEmitted; + } + function writeLines(text) { + var lines = text.split(/\r\n|\r|\n/g); + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line.length) { + if (i > 0) { + writeLine(); + } + write(line); + } + } + } + function emitShebang() { + var shebang = ts.getShebang(currentText); + if (shebang) { + write(shebang); + writeLine(); + } + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 256); + write(" "); + } + } + function emitWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emit); + } + function emitExpressionWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emitExpression); + } + function emitNodeWithPrefix(prefix, node, emit) { + if (node) { + write(prefix); + emit(node); + } + } + function emitWithSuffix(node, suffix) { + if (node) { + emit(node); + write(suffix); + } + } + function tryEmitSubstitute(node, emitNode, isExpression) { + if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { + var substitute = onSubstituteNode(node, isExpression); + if (substitute !== node) { + substitute.emitFlags |= 128; + emitNode(substitute); + return true; + } + } + return false; + } + function tryEmitConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + write(String(constantValue)); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : getTextOfNode(node.argumentExpression); + write(" /* " + propertyName + " */"); + } + return true; + } + return false; + } + function emitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + write(" "); + emit(node); + } + else { + writeLine(); + increaseIndent(); + emit(node); + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 24577); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 26960); + } + function emitTypeParameters(parentNode, typeParameters) { + emitList(parentNode, typeParameters, 26960); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 1360); + } + function emitParametersForArrow(parentNode, parameters) { + if (parameters && + parameters.length === 1 && + parameters[0].type === undefined && + parameters[0].pos === parentNode.pos) { + emit(parameters[0]); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 4432); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 8192) { + return; + } + var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + if (isEmpty && format & 16384) { + return; + } + if (format & 7680) { + write(getOpeningBracket(format)); + } + if (isEmpty) { + if (format & 1) { + writeLine(); + } + else if (format & 128) { + write(" "); + } + } + else { + var mayEmitInterveningComments = (format & 131072) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 128) { + write(" "); + } + if (format & 64) { + increaseIndent(); + } + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = void 0; + var delimiter = getDelimiter(format); + for (var i = 0; i < count; i++) { + var child = children[start + i]; + if (previousSibling) { + write(delimiter); + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + if ((format & (3 | 64)) === 0) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 256) { + write(" "); + } + } + if (shouldEmitInterveningComments) { + var commentRange = child.commentRange || child; + emitTrailingCommentsOfPosition(commentRange.pos); + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + var hasTrailingComma = (format & 32) && children.hasTrailingComma; + if (format & 16 && hasTrailingComma) { + write(","); + } + if (format & 64) { + decreaseIndent(); + } + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 128) { + write(" "); + } + } + if (format & 7680) { + write(getClosingBracket(format)); + } + } + function writeIfAny(nodes, text) { + if (nodes && nodes.length > 0) { + write(text); + } + } + function writeIfPresent(node, text) { + if (node !== undefined) { + write(text); + } + } + function writeToken(token, pos, contextNode) { + var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); + var tokenEndPos = writeTokenText(token, tokenStartPos); + return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); + } + function shouldSkipLeadingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 4096) !== 0; + } + function shouldSkipTrailingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 8192) !== 0; + } + function writeTokenText(token, pos) { + var tokenString = ts.tokenToString(token); + write(tokenString); + return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; + } + function writeTokenNode(node) { + if (node) { + emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + writeTokenText(node.kind); + emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (valueToWriteWhenNotIndenting) { + write(valueToWriteWhenNotIndenting); + } + } + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1) { + return true; + } + if (format & 2) { + if (format & 32768) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1) { + return true; + } + else if (format & 2) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return nextNode.startsOnNewLine; + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1) { + return (format & 65536) === 0; + } + else if (format & 2) { + if (format & 32768) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = node.startsOnNewLine; + if (startsOnNewLine === undefined) { + return (format & 32768) !== 0; + } + return startsOnNewLine; + } + return (format & 32768) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + if (node2.startsOnNewLine) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 178 && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return getGeneratedIdentifier(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return ts.unescapeIdentifier(node.text); + } + else if (node.kind === 9 && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node) { + if (node.kind === 9 && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode); + } + } + return ts.getLiteralText(node, currentSourceFile, languageVersion); + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } + function isSingleLineEmptyBlock(block) { + return !block.multiLine + && block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function isUniqueName(name) { + return !resolver.hasGlobalName(name) && + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); + } + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals && ts.hasProperty(node.locals, name)) { + if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { + return false; + } + } + } + return true; + } + function makeTempVariableName(flags) { + if (flags && !(tempFlags & flags)) { + var name_43 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_43)) { + tempFlags |= flags; + return name_43; + } + } + while (true) { + var count = tempFlags & 268435455; + tempFlags++; + if (count !== 8 && count !== 13) { + var name_44 = count < 26 + ? "_" + String.fromCharCode(97 + count) + : "_" + (count - 26); + if (isUniqueName(name_44)) { + return name_44; + } + } + } + } + function makeUniqueName(baseName) { + if (baseName.charCodeAt(baseName.length - 1) !== 95) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (isUniqueName(generatedName)) { + return generatedNameSet[generatedName] = generatedName; + } + i++; + } + } + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); + var baseName = expr.kind === 9 ? + ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + return makeUniqueName(baseName); + } + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForNode(node) { + switch (node.kind) { + case 69: + return makeUniqueName(getTextOfNode(node)); + case 225: + case 224: + return generateNameForModuleOrEnum(node); + case 230: + case 236: + return generateNameForImportOrExportDeclaration(node); + case 220: + case 221: + case 235: + return generateNameForExportDefault(); + case 192: + return generateNameForClassExpression(); + default: + return makeTempVariableName(0); + } + } + function generateName(name) { + switch (name.autoGenerateKind) { + case 1: + return makeTempVariableName(0); + case 2: + return makeTempVariableName(268435456); + case 3: + return makeUniqueName(name.text); + } + ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + if (ts.isIdentifier(node) + && node.autoGenerateKind === 4 + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + return node; + } + function getGeneratedIdentifier(name) { + if (name.autoGenerateKind === 4) { + var node = getNodeForGeneratedName(name); + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + } + else { + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(generateName(name))); + } + } + function createDelimiterMap() { + var delimiters = []; + delimiters[0] = ""; + delimiters[16] = ","; + delimiters[4] = " |"; + delimiters[8] = " &"; + return delimiters; + } + function getDelimiter(format) { + return delimiters[format & 28]; + } + function createBracketsMap() { + var brackets = []; + brackets[512] = ["{", "}"]; + brackets[1024] = ["(", ")"]; + brackets[2048] = ["<", ">"]; + brackets[4096] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 7680][0]; + } + function getClosingBracket(format) { + return brackets[format & 7680][1]; + } } ts.emitFiles = emitFiles; })(ts || (ts = {})); var ts; (function (ts) { - ts.programTime = 0; - ts.emitTime = 0; - ts.ioReadTime = 0; - ts.ioWriteTime = 0; - ts.version = "2.0.0"; + ts.version = "2.1.0"; var emptyArray = []; - var defaultTypeRoots = ["node_modules/@types"]; - function findConfigFile(searchPath, fileExists) { + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } while (true) { - var fileName = ts.combinePaths(searchPath, "tsconfig.json"); + var fileName = ts.combinePaths(searchPath, configName); if (fileExists(fileName)) { return fileName; } @@ -36794,51 +46470,29 @@ var ts; return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; } function moduleHasNonRelativeName(moduleName) { - if (ts.isRootedDiskPath(moduleName)) { - return false; - } - var i = moduleName.lastIndexOf("./", 1); - var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); - return !startsWithDotSlashOrDotDotSlash; + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent; - try { - var jsonText = state.host.readFile(packageJsonPath); - jsonContent = jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - jsonContent = {}; - } - var typesFile; - var fieldName; - if (jsonContent.typings) { - if (typeof jsonContent.typings === "string") { - fieldName = "typings"; - typesFile = jsonContent.typings; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } } } } - if (!typesFile && jsonContent.types) { - if (typeof jsonContent.types === "string") { - fieldName = "types"; - typesFile = jsonContent.types; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); - } - } - } - if (typesFile) { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { return typesFilePath; } if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { @@ -36850,6 +46504,15 @@ var ts; } return undefined; } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -36862,11 +46525,28 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - if (!currentDirectory) { - return undefined; - } - return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); + return currentDirectory && getDefaultTypeRoots(currentDirectory, host); } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_15 = ts.getDirectoryPath(currentDirectory); + if (parent_15 === currentDirectory) { + break; + } + currentDirectory = parent_15; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -37072,7 +46752,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); @@ -37188,7 +46868,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } function directoryProbablyExists(directoryName, host) { @@ -37196,9 +46876,9 @@ var ts; } ts.directoryProbablyExists = directoryProbablyExists; function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingOrKeepingExtension) { - return resolvedByAddingOrKeepingExtension; + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; } if (ts.hasJavaScriptFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); @@ -37206,39 +46886,37 @@ var ts; var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); } } - function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } - return ts.forEach(extensions, tryLoad); - function tryLoad(ext) { - if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { - return undefined; + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } - var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } + failedLookupLocation.push(fileName); + return undefined; } } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var packageJsonPath = pathToPackageJson(candidate); var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { @@ -37246,7 +46924,9 @@ var ts; } var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); if (typesFile) { - var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); if (result) { return result; } @@ -37265,6 +46945,9 @@ var ts; } return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); @@ -37337,14 +47020,8 @@ var ts; : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } ts.classicNameResolver = classicNameResolver; - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1, - noImplicitAny: false, - sourceMap: false - }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = {}; + var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } @@ -37352,9 +47029,10 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - var start = new Date().getTime(); + ts.performance.mark("beforeIORead"); text = ts.sys.readFile(fileName, options.charset); - ts.ioReadTime += new Date().getTime() - start; + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } catch (e) { if (onError) { @@ -37367,7 +47045,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (ts.hasProperty(existingDirectories, directoryPath)) { + if (directoryPath in existingDirectories) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -37386,11 +47064,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = {}; + outputFingerprints = ts.createMap(); } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { + if (mtimeBefore && fileName in outputFingerprints) { var fingerprint = outputFingerprints[fileName]; if (fingerprint.byteOrderMark === writeByteOrderMark && fingerprint.hash === hash && @@ -37408,7 +47086,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - var start = new Date().getTime(); + ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -37416,7 +47094,8 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.ioWriteTime += new Date().getTime() - start; + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } catch (e) { if (onError) { @@ -37442,6 +47121,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -37455,6 +47135,22 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; + } + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -37483,25 +47179,17 @@ var ts; return []; } var resolutions = []; - var cache = {}; - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_35 = names_1[_i]; - var result = void 0; - if (ts.hasProperty(cache, name_35)) { - result = cache[name_35]; - } - else { - result = loader(name_35, containingFile); - cache[name_35] = result; - } + var cache = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_45 = names_2[_i]; + var result = name_45 in cache + ? cache[name_45] + : cache[name_45] = loader(name_45, containingFile); resolutions.push(result); } return resolutions; } - function getInferredTypesRoot(options, rootFiles, host) { - return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - } - function getAutomaticTypeDirectiveNames(options, rootFiles, host) { + function getAutomaticTypeDirectiveNames(options, host) { if (options.types) { return options.types; } @@ -37512,7 +47200,15 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - result = result.concat(host.getDirectories(root)); + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } } } } @@ -37527,13 +47223,13 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; - var currentNodeModulesJsDepth = 0; - var modulesWithElidedImports = {}; - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + var modulesWithElidedImports = ts.createMap(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -37560,10 +47256,9 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, host); if (typeReferences) { - var inferredRoot = getInferredTypesRoot(options, rootNames, host); - var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -37607,7 +47302,8 @@ var ts; getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.programTime += new Date().getTime() - start; + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -37626,10 +47322,10 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = {}; + classifiableNames = ts.createMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyMap(sourceFile.classifiableNames, classifiableNames); + ts.copyProperties(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -37652,7 +47348,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { + !ts.equalOwnProperties(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -37742,7 +47438,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, + isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -37754,8 +47450,7 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } function emit(sourceFile, writeFileCallback, cancellationToken) { - var _this = this; - return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); @@ -37780,9 +47475,10 @@ var ts; } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - var start = new Date().getTime(); + ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); - ts.emitTime += new Date().getTime() - start; + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; } function getSourceFile(fileName) { @@ -37921,16 +47617,16 @@ var ts; case 175: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start_2 = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142: var parameter = node; if (parameter.modifiers) { - var start_3 = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -37974,8 +47670,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start_4 = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -38055,6 +47751,14 @@ var ts; var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + var externalHelpersModuleReference = ts.createNode(9); + externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; + externalHelpersModuleReference.parent = file; + imports = [externalHelpersModuleReference]; + } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, false); @@ -38082,7 +47786,7 @@ var ts; } break; case 225: - if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); @@ -38162,8 +47866,17 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { - if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { + sourceFilesFoundSearchingNodeModules[file_1.path] = false; + if (!options.noResolve) { + processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processTypeReferenceDirectives(file_1); + } + modulesWithElidedImports[file_1.path] = false; + processImportedModules(file_1, ts.getDirectoryPath(fileName)); + } + else if (file_1 && modulesWithElidedImports[file_1.path]) { + if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -38180,6 +47893,7 @@ var ts; }); filesByName.set(path, file); if (file) { + sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -38213,13 +47927,14 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; - ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -38236,7 +47951,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } saveResolution = false; } @@ -38270,7 +47985,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = {}; + file.resolvedModules = ts.createMap(); var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -38280,12 +47995,9 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - sourceFilesFoundSearchingNodeModules[resolvedPath] = true; + currentNodeModulesDepth++; } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth++; - } - var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -38293,8 +48005,8 @@ var ts; else if (shouldAddFile) { findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth--; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; } } } @@ -38305,8 +48017,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var file = sourceFiles_5[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -38317,8 +48029,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -38365,6 +48077,9 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { + if (options.paths[key].length === 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; @@ -38410,28 +48125,28 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -38449,7 +48164,7 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } if (!options.noEmit && !options.suppressOutputPathCheck) { @@ -38483,6 +48198,1310 @@ var ts; ts.createProgram = createProgram; })(ts || (ts = {})); var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + var TextChange = (function () { + function TextChange() { + } + return TextChange; + }()); + ts.TextChange = TextChange; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind.none = "none"; + HighlightSpanKind.definition = "definition"; + HighlightSpanKind.reference = "reference"; + HighlightSpanKind.writtenReference = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(ts.IndentStyle || (ts.IndentStyle = {})); + var IndentStyle = ts.IndentStyle; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + })(ts.TokenClass || (ts.TokenClass = {})); + var TokenClass = ts.TokenClass; + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind.unknown = ""; + ScriptElementKind.warning = "warning"; + ScriptElementKind.keyword = "keyword"; + ScriptElementKind.scriptElement = "script"; + ScriptElementKind.moduleElement = "module"; + ScriptElementKind.classElement = "class"; + ScriptElementKind.localClassElement = "local class"; + ScriptElementKind.interfaceElement = "interface"; + ScriptElementKind.typeElement = "type"; + ScriptElementKind.enumElement = "enum"; + ScriptElementKind.enumMemberElement = "const"; + ScriptElementKind.variableElement = "var"; + ScriptElementKind.localVariableElement = "local var"; + ScriptElementKind.functionElement = "function"; + ScriptElementKind.localFunctionElement = "local function"; + ScriptElementKind.memberFunctionElement = "method"; + ScriptElementKind.memberGetAccessorElement = "getter"; + ScriptElementKind.memberSetAccessorElement = "setter"; + ScriptElementKind.memberVariableElement = "property"; + ScriptElementKind.constructorImplementationElement = "constructor"; + ScriptElementKind.callSignatureElement = "call"; + ScriptElementKind.indexSignatureElement = "index"; + ScriptElementKind.constructSignatureElement = "construct"; + ScriptElementKind.parameterElement = "parameter"; + ScriptElementKind.typeParameterElement = "type parameter"; + ScriptElementKind.primitiveType = "primitive type"; + ScriptElementKind.label = "label"; + ScriptElementKind.alias = "alias"; + ScriptElementKind.constElement = "const"; + ScriptElementKind.letElement = "let"; + ScriptElementKind.directory = "directory"; + ScriptElementKind.externalModuleName = "external module name"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier.none = ""; + ScriptElementKindModifier.publicMemberModifier = "public"; + ScriptElementKindModifier.privateMemberModifier = "private"; + ScriptElementKindModifier.protectedMemberModifier = "protected"; + ScriptElementKindModifier.exportedModifier = "export"; + ScriptElementKindModifier.ambientModifier = "declare"; + ScriptElementKindModifier.staticModifier = "static"; + ScriptElementKindModifier.abstractModifier = "abstract"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames = (function () { + function ClassificationTypeNames() { + } + return ClassificationTypeNames; + }()); + ClassificationTypeNames.comment = "comment"; + ClassificationTypeNames.identifier = "identifier"; + ClassificationTypeNames.keyword = "keyword"; + ClassificationTypeNames.numericLiteral = "number"; + ClassificationTypeNames.operator = "operator"; + ClassificationTypeNames.stringLiteral = "string"; + ClassificationTypeNames.whiteSpace = "whitespace"; + ClassificationTypeNames.text = "text"; + ClassificationTypeNames.punctuation = "punctuation"; + ClassificationTypeNames.className = "class name"; + ClassificationTypeNames.enumName = "enum name"; + ClassificationTypeNames.interfaceName = "interface name"; + ClassificationTypeNames.moduleName = "module name"; + ClassificationTypeNames.typeParameterName = "type parameter name"; + ClassificationTypeNames.typeAliasName = "type alias name"; + ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; + ts.ClassificationTypeNames = ClassificationTypeNames; +})(ts || (ts = {})); +var ts; +(function (ts) { + ts.scanner = ts.createScanner(2, true); + ts.emptyArray = []; + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 142: + case 218: + case 169: + case 145: + case 144: + case 253: + case 254: + case 255: + case 147: + case 146: + case 148: + case 149: + case 150: + case 220: + case 179: + case 180: + case 252: + return 1; + case 141: + case 222: + case 223: + case 159: + return 2; + case 221: + case 224: + return 1 | 2; + case 225: + if (ts.isAmbientModule(node)) { + return 4 | 1; + } + else if (ts.getModuleInstanceState(node) === 1) { + return 4 | 1; + } + else { + return 4; + } + case 233: + case 234: + case 229: + case 230: + case 235: + case 236: + return 1 | 2 | 4; + case 256: + return 4 | 1; + } + return 1 | 2 | 4; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.parent.kind === 235) { + return 1 | 2 | 4; + } + else if (isInRightSideOfImport(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2; + } + else if (isNamespaceReference(node)) { + return 4; + } + else { + return 1; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + ts.Debug.assert(node.kind === 69); + if (node.parent.kind === 139 && + node.parent.right === node && + node.parent.parent.kind === 229) { + return 1 | 2 | 4; + } + return 4; + } + function isInRightSideOfImport(node) { + while (node.parent.kind === 139) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 139) { + while (root.parent && root.parent.kind === 139) { + root = root.parent; + } + isLastClause = root.right === node; + } + return root.parent.kind === 155 && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 172) { + while (root.parent && root.parent.kind === 172) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 194 && root.parent.parent.kind === 251) { + var decl = root.parent.parent.parent; + return (decl.kind === 221 && root.parent.parent.token === 106) || + (decl.kind === 222 && root.parent.parent.token === 83); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + return node.parent.kind === 155 || + (node.parent.kind === 194 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 && !ts.isPartOfExpression(node)) || + node.kind === 165; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 174); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 175); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node, kind) { + var target = climbPastPropertyAccess(node); + return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 214 && referenceNode.label.text === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function isJumpStatementTarget(node) { + return node.kind === 69 && + (node.parent.kind === 210 || node.parent.kind === 209) && + node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 69 && + node.parent.kind === 214 && + node.parent.label === node; + } + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 139 && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 172 && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 225 && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 69 && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + if (node.kind === 9 || node.kind === 8) { + switch (node.parent.kind) { + case 145: + case 144: + case 253: + case 255: + case 147: + case 146: + case 149: + case 150: + case 225: + return node.parent.name === node; + case 173: + return node.parent.argumentExpression === node; + case 140: + return true; + } + } + return false; + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + function isInsideComment(sourceFile, token, position) { + return position <= token.getStart(sourceFile) && + (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || + isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); + function isInsideCommentRange(comments) { + return ts.forEach(comments, function (comment) { + if (comment.pos < position && position < comment.end) { + return true; + } + else if (position === comment.end) { + var text = sourceFile.text; + var width = comment.end - comment.pos; + if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { + return true; + } + else { + return !(text.charCodeAt(comment.end - 1) === 47 && + text.charCodeAt(comment.end - 2) === 42); + } + } + return false; + }); + } + } + ts.isInsideComment = isInsideComment; + function getContainerNode(node) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 256: + case 147: + case 146: + case 220: + case 179: + case 149: + case 150: + case 221: + case 222: + case 224: + case 225: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 256: + return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + case 225: + return ts.ScriptElementKind.moduleElement; + case 221: + case 192: + return ts.ScriptElementKind.classElement; + case 222: return ts.ScriptElementKind.interfaceElement; + case 223: return ts.ScriptElementKind.typeElement; + case 224: return ts.ScriptElementKind.enumElement; + case 218: + return getKindOfVariableDeclaration(node); + case 169: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180: + case 220: + case 179: + return ts.ScriptElementKind.functionElement; + case 149: return ts.ScriptElementKind.memberGetAccessorElement; + case 150: return ts.ScriptElementKind.memberSetAccessorElement; + case 147: + case 146: + return ts.ScriptElementKind.memberFunctionElement; + case 145: + case 144: + return ts.ScriptElementKind.memberVariableElement; + case 153: return ts.ScriptElementKind.indexSignatureElement; + case 152: return ts.ScriptElementKind.constructSignatureElement; + case 151: return ts.ScriptElementKind.callSignatureElement; + case 148: return ts.ScriptElementKind.constructorImplementationElement; + case 141: return ts.ScriptElementKind.typeParameterElement; + case 255: return ts.ScriptElementKind.enumMemberElement; + case 142: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + case 229: + case 234: + case 231: + case 238: + case 232: + return ts.ScriptElementKind.alias; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ts.ScriptElementKind.constElement + : ts.isLet(v) + ? ts.ScriptElementKind.letElement + : ts.ScriptElementKind.variableElement; + } + } + ts.getNodeKind = getNodeKind; + function getStringLiteralTypeForNode(node, typeChecker) { + var searchNode = node.parent.kind === 166 ? node.parent : node; + var type = typeChecker.getTypeAtLocation(searchNode); + if (type && type.flags & 32) { + return type; + } + return undefined; + } + ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; + function isThis(node) { + switch (node.kind) { + case 97: + return true; + case 69: + return node.originalKeywordKind === 97 && node.parent.kind === 142; + default: + return false; + } + } + ts.isThis = isThis; + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + function positionBelongsToNode(candidate, position, sourceFile) { + return candidate.end > position || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 221: + case 222: + case 224: + case 171: + case 167: + case 159: + case 199: + case 226: + case 227: + case 233: + case 237: + return nodeEndsWith(n, 16, sourceFile); + case 252: + return isCompletedNode(n.block, sourceFile); + case 175: + if (!n.arguments) { + return true; + } + case 174: + case 178: + case 164: + return nodeEndsWith(n, 18, sourceFile); + case 156: + case 157: + return isCompletedNode(n.type, sourceFile); + case 148: + case 149: + case 150: + case 220: + case 179: + case 147: + case 146: + case 152: + case 151: + case 180: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 18, sourceFile); + case 225: + return n.body && isCompletedNode(n.body, sourceFile); + case 203: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 202: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 23); + case 170: + case 168: + case 173: + case 140: + case 161: + return nodeEndsWith(n, 20, sourceFile); + case 153: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 20, sourceFile); + case 249: + case 250: + return false; + case 206: + case 207: + case 208: + case 205: + return isCompletedNode(n.statement, sourceFile); + case 204: + var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); + if (hasWhileKeyword) { + return nodeEndsWith(n, 18, sourceFile); + } + return isCompletedNode(n.statement, sourceFile); + case 158: + return isCompletedNode(n.exprName, sourceFile); + case 182: + case 181: + case 183: + case 190: + case 191: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 176: + return isCompletedNode(n.template, sourceFile); + case 189: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 197: + return ts.nodeIsPresent(n.literal); + case 236: + case 230: + return ts.nodeIsPresent(n.moduleSpecifier); + case 185: + return isCompletedNode(n.operand, sourceFile); + case 187: + return isCompletedNode(n.right, sourceFile); + case 188: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + ts.isCompletedNode = isCompletedNode; + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var last = ts.lastOrUndefined(children); + if (last.kind === expectedLastToken) { + return true; + } + else if (last.kind === 23 && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOf(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { + if (c.kind === 286 && c.pos <= node.pos && c.end >= node.end) { + return c; + } + }); + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + function getTouchingWord(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + } + ts.getTouchingWord = getTouchingWord; + function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); + } + ts.getTouchingToken = getTouchingToken; + function getTokenAtPosition(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); + } + ts.getTokenAtPosition = getTokenAtPosition; + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + var current = sourceFile; + outer: while (true) { + if (isToken(current)) { + return current; + } + if (includeJsDocComment) { + var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); + for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { + var jsDocChild = jsDocChildren_1[_i]; + var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = jsDocChild.getEnd(); + if (position < end || (position === end && jsDocChild.kind === 1)) { + current = jsDocChild; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } + } + } + } + } + for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { + var child = current.getChildAt(i); + if (ts.isJSDocNode(child)) { + continue; + } + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } + } + } + } + return current; + } + } + function findTokenOnLeftOfPosition(file, position) { + var tokenAtPosition = getTokenAtPosition(file, position); + if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent) { + return find(parent); + function find(n) { + if (isToken(n) && n.pos === previousToken.end) { + return n; + } + var children = n.getChildren(); + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || + (child.pos === previousToken.end); + if (shouldDiveInChildNode && nodeHasTokens(child)) { + return find(child); + } + } + return undefined; + } + } + ts.findNextToken = findNextToken; + function findPrecedingToken(position, sourceFile, startNode) { + return find(startNode || sourceFile); + function findRightmostToken(n) { + if (isToken(n) || n.kind === 244) { + return n; + } + var children = n.getChildren(); + var candidate = findRightmostChildNodeWithTokens(children, children.length); + return candidate && findRightmostToken(candidate); + } + function find(n) { + if (isToken(n) || n.kind === 244) { + return n; + } + var children = n.getChildren(); + for (var i = 0, len = children.length; i < len; i++) { + var child = children[i]; + if (position < child.end && (nodeHasTokens(child) || child.kind === 244)) { + var start = child.getStart(sourceFile); + var lookInPreviousChild = (start >= position) || + (child.kind === 244 && start === child.end); + if (lookInPreviousChild) { + var candidate = findRightmostChildNodeWithTokens(children, i); + return candidate && findRightmostToken(candidate); + } + else { + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 256); + if (children.length) { + var candidate = findRightmostChildNodeWithTokens(children, children.length); + return candidate && findRightmostToken(candidate); + } + } + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + if (nodeHasTokens(children[i])) { + return children[i]; + } + } + } + } + ts.findPrecedingToken = findPrecedingToken; + function isInString(sourceFile, position) { + var previousToken = findPrecedingToken(position, sourceFile); + if (previousToken && previousToken.kind === 9) { + var start = previousToken.getStart(); + var end = previousToken.getEnd(); + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + function isInComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, undefined); + } + ts.isInComment = isInComment; + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 244) { + return true; + } + if (token.kind === 25 && token.parent.kind === 244) { + return true; + } + if (token.kind === 25 && token.parent.kind === 248) { + return true; + } + if (token && token.kind === 16 && token.parent.kind === 248) { + return true; + } + if (token.kind === 25 && token.parent.kind === 245) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + function isInCommentHelper(sourceFile, position, predicate) { + var token = getTokenAtPosition(sourceFile, position); + if (token && position <= token.getStart(sourceFile)) { + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + return predicate ? + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 ? position <= c.end : position < c.end) && + predicate(c); }) : + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 ? position <= c.end : position < c.end); }); + } + return false; + } + ts.isInCommentHelper = isInCommentHelper; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + return ts.forEach(commentRanges, jsDocPrefix); + function jsDocPrefix(c) { + var text = sourceFile.text; + return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; + } + } + ts.hasDocComment = hasDocComment; + function getJsDocTagAtPosition(sourceFile, position) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (isToken(node)) { + switch (node.kind) { + case 102: + case 108: + case 74: + node = node.parent === undefined ? undefined : node.parent.parent; + break; + default: + node = node.parent; + break; + } + } + if (node) { + if (node.jsDocComments) { + for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + if (jsDocComment.tags) { + for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.pos <= position && position <= tag.end) { + return tag; + } + } + } + } + } + } + return undefined; + } + ts.getJsDocTagAtPosition = getJsDocTagAtPosition; + function nodeHasTokens(n) { + return n.getWidth() !== 0; + } + function getNodeModifiers(node) { + var flags = ts.getCombinedModifierFlags(node); + var result = []; + if (flags & 8) + result.push(ts.ScriptElementKindModifier.privateMemberModifier); + if (flags & 16) + result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + if (flags & 4) + result.push(ts.ScriptElementKindModifier.publicMemberModifier); + if (flags & 32) + result.push(ts.ScriptElementKindModifier.staticModifier); + if (flags & 128) + result.push(ts.ScriptElementKindModifier.abstractModifier); + if (flags & 1) + result.push(ts.ScriptElementKindModifier.exportedModifier); + if (ts.isInAmbientContext(node)) + result.push(ts.ScriptElementKindModifier.ambientModifier); + return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 155 || node.kind === 174) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 221 || node.kind === 222) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isToken(n) { + return n.kind >= 0 && n.kind <= 138; + } + ts.isToken = isToken; + function isWord(kind) { + return kind === 69 || ts.isKeyword(kind); + } + ts.isWord = isWord; + function isPropertyName(kind) { + return kind === 9 || kind === 8 || isWord(kind); + } + function isComment(kind) { + return kind === 2 || kind === 3; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 9 + || kind === 10 + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 15 <= kind && kind <= 68; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 112: + case 110: + case 111: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 170 || + node.kind === 171) { + if (node.parent.kind === 187 && + node.parent.left === node && + node.parent.operatorToken.kind === 56) { + return true; + } + if (node.parent.kind === 208 && + node.parent.initializer === node) { + return true; + } + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function hasTrailingDirectorySeparator(path) { + var lastCharacter = path.charAt(path.length - 1); + return lastCharacter === "/" || lastCharacter === "\\"; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function isInReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isReferenceComment); + function isReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isNonReferenceComment); + function isNonReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return !tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInNonReferenceComment = isInNonReferenceComment; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var displayParts; + var lineStart; + var indent; + resetWriter(); + return { + displayParts: function () { return displayParts; }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: function () { }, + reportInaccessibleThisError: function () { } + }; + function writeIndent() { + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + writeIndent(); + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + writeIndent(); + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol), symbol); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 8388608) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind, symbol) { + return { + text: text, + kind: ts.SymbolDisplayPartKind[kind] + }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + function getNewLineOrDefaultFromHost(host) { + return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + writeDisplayParts(displayPartWriter); + var result = displayPartWriter.displayParts(); + displayPartWriter.clear(); + return result; + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + return mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function getDeclaredName(typeChecker, symbol, location) { + if (isImportOrExportSpecifierName(location)) { + return location.getText(); + } + else if (ts.isStringOrNumericLiteral(location.kind) && + location.parent.kind === 140) { + return location.text; + } + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); + return name; + } + ts.getDeclaredName = getDeclaredName; + function isImportOrExportSpecifierName(location) { + return location.parent && + (location.parent.kind === 234 || location.parent.kind === 238) && + location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && + name.charCodeAt(0) === name.charCodeAt(length - 1) && + (name.charCodeAt(0) === 34 || name.charCodeAt(0) === 39)) { + return name.substring(1, length - 1); + } + ; + return name; + } + ts.stripQuotes = stripQuotes; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + var scriptKind; + if (host && host.getScriptKind) { + scriptKind = host.getScriptKind(fileName); + } + if (!scriptKind) { + scriptKind = ts.getScriptKindFromFileName(fileName); + } + return ts.ensureScriptKind(fileName, scriptKind); + } + ts.getScriptKind = getScriptKind; + function parseAndReEmitConfigJSONFile(content) { + var options = { + fileName: "config.js", + compilerOptions: { + target: 2, + removeComments: true + }, + reportDiagnostics: true + }; + var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; + var trimmedOutput = outputText.trim(); + var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; +})(ts || (ts = {})); +var ts; (function (ts) { var BreakpointResolver; (function (BreakpointResolver) { @@ -38665,7 +49684,7 @@ var ts; return spanInNode(binaryExpression.left); } } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { case 204: return spanInPreviousNode(node); @@ -38734,7 +49753,7 @@ var ts; return spanInBindingPattern(variableDeclaration.name); } if (variableDeclaration.initializer || - (variableDeclaration.flags & 1) || + ts.hasModifier(variableDeclaration, 1) || variableDeclaration.parent.parent.kind === 208) { return textSpanFromVariableDeclaration(variableDeclaration); } @@ -38745,7 +49764,7 @@ var ts; } function canHaveSpanInParameterDeclaration(parameter) { return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 4) || !!(parameter.flags & 8); + ts.hasModifier(parameter, 4 | 8); } function spanInParameterDeclaration(parameter) { if (ts.isBindingPattern(parameter.name)) { @@ -38766,7 +49785,7 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1) || + return ts.hasModifier(functionDeclaration, 1) || (functionDeclaration.parent.kind === 221 && functionDeclaration.kind !== 148); } function spanInFunctionDeclaration(functionDeclaration) { @@ -38969,188 +49988,4154 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var OutliningElementsCollector; - (function (OutliningElementsCollector) { - function collectElements(sourceFile) { - var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { - if (hintSpanNode && startElement && endElement) { - var span = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), - hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + function createClassifier() { + var scanner = ts.createScanner(2, false); + var noRegexTable = []; + noRegexTable[69] = true; + noRegexTable[9] = true; + noRegexTable[8] = true; + noRegexTable[10] = true; + noRegexTable[97] = true; + noRegexTable[41] = true; + noRegexTable[42] = true; + noRegexTable[18] = true; + noRegexTable[20] = true; + noRegexTable[16] = true; + noRegexTable[99] = true; + noRegexTable[84] = true; + var templateStack = []; + function canFollow(keyword1, keyword2) { + if (ts.isAccessibilityModifier(keyword1)) { + if (keyword2 === 123 || + keyword2 === 131 || + keyword2 === 121 || + keyword2 === 113) { + return true; } + return false; } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + return true; + } + function convertClassifications(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0, n = dense.length; i < n; i += 3) { + var start = dense[i]; + var length_4 = dense[i + 1]; + var type = dense[i + 2]; + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } } + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var currentComment = comments_2[_i]; - if (currentComment.kind === 2) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; - } - else if (currentComment.kind === 3) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1: return ts.TokenClass.Comment; + case 3: return ts.TokenClass.Keyword; + case 4: return ts.TokenClass.NumberLiteral; + case 5: return ts.TokenClass.Operator; + case 6: return ts.TokenClass.StringLiteral; + case 8: return ts.TokenClass.Whitespace; + case 10: return ts.TokenClass.Punctuation; + case 2: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 9: + case 17: + default: + return ts.TokenClass.Identifier; + } + } + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + } + function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var offset = 0; + var token = 0; + var lastNonTriviaToken = 0; + while (templateStack.length > 0) { + templateStack.pop(); + } + switch (lexState) { + case 3: + text = "\"\\\n" + text; + offset = 3; + break; + case 2: + text = "'\\\n" + text; + offset = 3; + break; + case 1: + text = "/*\n" + text; + offset = 3; + break; + case 4: + text = "`\n" + text; + offset = 2; + break; + case 5: + text = "}\n" + text; + offset = 2; + case 6: + templateStack.push(12); + break; + } + scanner.setText(text); + var result = { + endOfLineState: 0, + spans: [] + }; + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + if ((token === 39 || token === 61) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 10) { + token = 10; } } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + else if (lastNonTriviaToken === 21 && isKeyword(token)) { + token = 69; + } + else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + token = 69; + } + else if (lastNonTriviaToken === 69 && + token === 25) { + angleBracketStack++; + } + else if (token === 27 && angleBracketStack > 0) { + angleBracketStack--; + } + else if (token === 117 || + token === 132 || + token === 130 || + token === 120 || + token === 133) { + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + token = 69; + } + } + else if (token === 12) { + templateStack.push(token); + } + else if (token === 15) { + if (templateStack.length > 0) { + templateStack.push(token); + } + } + else if (token === 16) { + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 12) { + token = scanner.reScanTemplateToken(); + if (token === 14) { + templateStack.pop(); + } + else { + ts.Debug.assert(token === 13, "Should have been a template middle. Was " + token); + } + } + else { + ts.Debug.assert(lastTemplateStackToken === 15, "Should have been an open brace. Was: " + token); + templateStack.pop(); + } + } + } + lastNonTriviaToken = token; + } + processToken(); + } while (token !== 1); + return result; + function processToken() { + var start = scanner.getTokenPos(); + var end = scanner.getTextPos(); + addResult(start, end, classFromKind(token)); + if (end >= text.length) { + if (token === 9) { + var tokenText = scanner.getTokenText(); + if (scanner.isUnterminated()) { + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92) { + numBackslashes++; + } + if (numBackslashes & 1) { + var quoteChar = tokenText.charCodeAt(0); + result.endOfLineState = quoteChar === 34 + ? 3 + : 2; + } + } + } + else if (token === 3) { + if (scanner.isUnterminated()) { + result.endOfLineState = 1; + } + } + else if (ts.isTemplateLiteralKind(token)) { + if (scanner.isUnterminated()) { + if (token === 14) { + result.endOfLineState = 5; + } + else if (token === 11) { + result.endOfLineState = 4; + } + else { + ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + } + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12) { + result.endOfLineState = 6; + } } } - function combineAndAddMultipleSingleLineComments(count, start, end) { - if (count > 1) { - var multipleSingleLineComments = { - pos: start, - end: end, - kind: 2 - }; - addOutliningSpanComments(multipleSingleLineComments, false); - } - } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180; - } - var depth = 0; - var maxDepth = 20; - function walk(n) { - if (depth > maxDepth) { + function addResult(start, end, classification) { + if (classification === 8) { return; } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); + if (start === 0 && offset > 0) { + start += offset; } - switch (n.kind) { - case 199: - if (!ts.isFunctionBlock(n)) { - var parent_15 = n.parent; - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_15.kind === 204 || - parent_15.kind === 207 || - parent_15.kind === 208 || - parent_15.kind === 206 || - parent_15.kind === 203 || - parent_15.kind === 205 || - parent_15.kind === 212 || - parent_15.kind === 252) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + start -= offset; + end -= offset; + var length = end - start; + if (length > 0) { + result.spans.push(start); + result.spans.push(length); + result.spans.push(classification); + } + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 37: + case 39: + case 40: + case 35: + case 36: + case 43: + case 44: + case 45: + case 25: + case 27: + case 28: + case 29: + case 91: + case 90: + case 116: + case 30: + case 31: + case 32: + case 33: + case 46: + case 48: + case 47: + case 51: + case 52: + case 67: + case 66: + case 68: + case 63: + case 64: + case 65: + case 57: + case 58: + case 59: + case 61: + case 62: + case 56: + case 24: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 35: + case 36: + case 50: + case 49: + case 41: + case 42: + return true; + default: + return false; + } + } + function isKeyword(token) { + return token >= 70 && token <= 138; + } + function classFromKind(token) { + if (isKeyword(token)) { + return 3; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5; + } + else if (token >= 15 && token <= 68) { + return 10; + } + switch (token) { + case 8: + return 4; + case 9: + return 6; + case 10: + return 7; + case 7: + case 3: + case 2: + return 1; + case 5: + case 4: + return 8; + case 69: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6; + } + return 2; + } + } + return { + getClassificationsForLine: getClassificationsForLine, + getEncodedLexicalClassifications: getEncodedLexicalClassifications + }; + } + ts.createClassifier = createClassifier; + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + switch (kind) { + case 225: + case 221: + case 222: + case 220: + cancellationToken.throwIfCancellationRequested(); + } + } + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var result = []; + processNode(sourceFile); + return { spans: result, endOfLineState: 0 }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifySymbol(symbol, meaningAtPosition) { + var flags = symbol.getFlags(); + if ((flags & 788448) === 0) { + return; + } + if (flags & 32) { + return 11; + } + else if (flags & 384) { + return 12; + } + else if (flags & 524288) { + return 16; + } + else if (meaningAtPosition & 2) { + if (flags & 64) { + return 13; + } + else if (flags & 262144) { + return 15; + } + } + else if (flags & 1536) { + if (meaningAtPosition & 4 || + (meaningAtPosition & 1 && hasValueSideModule(symbol))) { + return 14; + } + } + return undefined; + function hasValueSideModule(symbol) { + return ts.forEach(symbol.declarations, function (declaration) { + return declaration.kind === 225 && + ts.getModuleInstanceState(declaration) === 1; + }); + } + } + function processNode(node) { + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + var kind = node.kind; + checkForClassificationCancellation(cancellationToken, kind); + if (kind === 69 && !ts.nodeIsMissing(node)) { + var identifier = node; + if (classifiableNames[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); } - if (parent_15.kind === 216) { - var tryStatement = parent_15; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + } + } + } + ts.forEachChild(node, processNode); + } + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function getClassificationTypeName(type) { + switch (type) { + case 1: return ts.ClassificationTypeNames.comment; + case 2: return ts.ClassificationTypeNames.identifier; + case 3: return ts.ClassificationTypeNames.keyword; + case 4: return ts.ClassificationTypeNames.numericLiteral; + case 5: return ts.ClassificationTypeNames.operator; + case 6: return ts.ClassificationTypeNames.stringLiteral; + case 8: return ts.ClassificationTypeNames.whiteSpace; + case 9: return ts.ClassificationTypeNames.text; + case 10: return ts.ClassificationTypeNames.punctuation; + case 11: return ts.ClassificationTypeNames.className; + case 12: return ts.ClassificationTypeNames.enumName; + case 13: return ts.ClassificationTypeNames.interfaceName; + case 14: return ts.ClassificationTypeNames.moduleName; + case 15: return ts.ClassificationTypeNames.typeParameterName; + case 16: return ts.ClassificationTypeNames.typeAliasName; + case 17: return ts.ClassificationTypeNames.parameterName; + case 18: return ts.ClassificationTypeNames.docCommentTagName; + case 19: return ts.ClassificationTypeNames.jsxOpenTagName; + case 20: return ts.ClassificationTypeNames.jsxCloseTagName; + case 21: return ts.ClassificationTypeNames.jsxSelfClosingTagName; + case 22: return ts.ClassificationTypeNames.jsxAttribute; + case 23: return ts.ClassificationTypeNames.jsxText; + case 24: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + } + } + function convertClassifications(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0, n = dense.length; i < n; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + var triviaScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + if (!ts.isTrivia(kind)) { + return start; + } + if (kind === 4 || kind === 5) { + continue; + } + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + triviaScanner.setTextPos(end); + continue; + } + if (kind === 7) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + if (ch === 60 || ch === 62) { + pushClassification(start, width, 1); + continue; + } + ts.Debug.assert(ch === 61); + classifyDisabledMergeCode(text, start, end); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3) { + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10); + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); + pos = tag.tagName.end; + switch (tag.kind) { + case 275: + processJSDocParameterTag(tag); + break; + case 278: + processJSDocTemplateTag(tag); + break; + case 277: + processElement(tag.typeExpression); + break; + case 276: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.preParameterName) { + pushCommentRange(pos, tag.preParameterName.pos - pos); + pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17); + pos = tag.preParameterName.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (tag.postParameterName) { + pushCommentRange(pos, tag.postParameterName.pos - pos); + pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17); + pos = tag.postParameterName.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + function tryClassifyNode(node) { + if (ts.isJSDocTag(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 244 && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 244 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 243: + if (token.parent.tagName === token) { + return 19; + } + break; + case 245: + if (token.parent.tagName === token) { + return 20; + } + break; + case 242: + if (token.parent.tagName === token) { + return 21; + } + break; + case 246: + if (token.parent.name === token) { + return 22; + } + break; + } + return undefined; + } + function classifyTokenType(tokenKind, token) { + if (ts.isKeyword(tokenKind)) { + return 3; + } + if (tokenKind === 25 || tokenKind === 27) { + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + if (tokenKind === 56) { + if (token.parent.kind === 218 || + token.parent.kind === 145 || + token.parent.kind === 142 || + token.parent.kind === 246) { + return 5; + } + } + if (token.parent.kind === 187 || + token.parent.kind === 185 || + token.parent.kind === 186 || + token.parent.kind === 188) { + return 5; + } + } + return 10; + } + else if (tokenKind === 8) { + return 4; + } + else if (tokenKind === 9) { + return token.parent.kind === 246 ? 24 : 6; + } + else if (tokenKind === 10) { + return 6; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + return 6; + } + else if (tokenKind === 244) { + return 23; + } + else if (tokenKind === 69) { + if (token) { + switch (token.parent.kind) { + case 221: + if (token.parent.name === token) { + return 11; + } + return; + case 141: + if (token.parent.name === token) { + return 15; + } + return; + case 222: + if (token.parent.name === token) { + return 13; + } + return; + case 224: + if (token.parent.name === token) { + return 12; + } + return; + case 225: + if (token.parent.name === token) { + return 14; + } + return; + case 142: + if (token.parent.name === token) { + var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; + return isThis_1 ? 3 : 17; + } + return; + } + } + return 2; + } + } + function processElement(element) { + if (!element) { + return; + } + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; + if (!tryClassifyNode(child)) { + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +var ts; +(function (ts) { + var Completions; + (function (Completions) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + if (ts.isInReferenceComment(sourceFile, position)) { + return getTripleSlashReferenceCompletion(sourceFile, position); + } + if (ts.isInString(sourceFile, position)) { + return getStringLiteralCompletionEntries(sourceFile, position); + } + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + if (isJsDocTagName) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + } + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); + } + else { + if (!symbols || symbols.length === 0) { + if (sourceFile.languageVariant === 1 && + location.parent && location.parent.kind === 245) { + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } + } + getCompletionEntriesFromSymbols(symbols, entries, location, true); + } + if (!isMemberCompletion && !isJsDocTagName) { + ts.addRange(entries, keywordCompletions); + } + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { + var entries = []; + var nameTable = ts.getNameTable(sourceFile); + for (var name_46 in nameTable) { + if (nameTable[name_46] === position) { + continue; + } + if (!uniqueNames[name_46]) { + uniqueNames[name_46] = name_46; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (displayName) { + var entry = { + name: displayName, + kind: ts.ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); + } + } + } + return entries; + } + function createCompletionEntry(symbol, location, performCharacterChecks) { + var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, compilerOptions.target, performCharacterChecks, location); + if (!displayName) { + return undefined; + } + return { + name: displayName, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0" + }; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { + var start = ts.timestamp(); + var uniqueNames = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var entry = createCompletionEntry(symbol, location, performCharacterChecks); + if (entry) { + var id = ts.escapeIdentifier(entry.name); + if (!uniqueNames[id]) { + entries.push(entry); + uniqueNames[id] = id; + } + } + } + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniqueNames; + } + function getStringLiteralCompletionEntries(sourceFile, position) { + var node = ts.findPrecedingToken(position, sourceFile); + if (!node || node.kind !== 9) { + return undefined; + } + if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); + } + else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { + return getStringLiteralCompletionEntriesFromElementAccess(node.parent); + } + else if (node.parent.kind === 230 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + return getStringLiteralCompletionEntriesFromModuleNames(node); + } + else { + var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); + if (argumentInfo) { + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + } + return getStringLiteralCompletionEntriesFromContextualType(node); + } + } + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var type = typeChecker.getContextualType(element.parent); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + } + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + var candidates = []; + var entries = []; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); + for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { + var candidate = candidates_3[_i]; + if (candidate.parameters.length > argumentInfo.argumentIndex) { + var parameter = candidate.parameters[argumentInfo.argumentIndex]; + addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); + } + } + if (entries.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + } + return undefined; + } + function getStringLiteralCompletionEntriesFromElementAccess(node) { + var type = typeChecker.getTypeAtLocation(node.expression); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + return undefined; + } + function getStringLiteralCompletionEntriesFromContextualType(node) { + var type = typeChecker.getContextualType(node); + if (type) { + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + } + } + return undefined; + } + function addStringLiteralCompletionsFromType(type, result) { + if (!type) { + return; + } + if (type.flags & 524288) { + ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); + } + else { + if (type.flags & 32) { + result.push({ + name: type.text, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } + } + } + function getStringLiteralCompletionEntriesFromModuleNames(node) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = node.getSourceFile().path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var entries; + if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { + if (compilerOptions.rootDirs) { + entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), false, span, scriptPath); + } + else { + entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), false, span, scriptPath); + } + } + else { + entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries + }; + } + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + var relativeDirectory; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDirectory = rootDirs_1[_i]; + if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { + relativeDirectory = scriptPath.substr(rootDirectory.length); + break; + } + } + return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); + var result = []; + for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { + var baseDirectory = baseDirectories_1[_i]; + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, exclude, result); + } + return result; + } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { + if (result === void 0) { result = []; } + fragment = ts.getDirectoryPath(fragment); + if (!fragment) { + fragment = "./"; + } + else { + fragment = ts.ensureTrailingDirectorySeparator(fragment); + } + var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); + var baseDirectory = ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (tryDirectoryExists(host, baseDirectory)) { + var files = tryReadDirectory(host, baseDirectory, extensions, undefined, ["./*"]); + if (files) { + var foundFiles = ts.createMap(); + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0) { + continue; + } + var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + if (!foundFiles[foundFileName]) { + foundFiles[foundFileName] = true; + } + } + for (var foundFile in foundFiles) { + result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + } + } + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { + var directory = directories_2[_a]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + } + } + } + return result; + } + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result; + if (baseUrl) { + var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); + result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span); + if (paths) { + for (var path in paths) { + if (paths.hasOwnProperty(path)) { + if (path === "*") { + if (paths[path]) { + for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { + var pattern = _a[_i]; + for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions); _b < _c.length; _b++) { + var match = _c[_b]; + result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + } + } + } } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); - break; + else if (ts.startsWith(path, fragment)) { + var entry = paths[path] && paths[path].length === 1 && paths[path][0]; + if (entry) { + result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); } } } - var span = ts.createTextSpanFromBounds(n.getStart(), n.end); - elements.push({ - textSpan: span, - hintSpan: span, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); + } + } + } + else { + result = []; + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions); _d < _e.length; _d++) { + var moduleName = _e[_d]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + return result; + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions) { + if (host.readDirectory) { + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (parsed) { + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); + if (matches) { + var result = []; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + continue; + } + var start = completePrefix.length; + var length_5 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_5))); + } + return result; + } + } + } + return undefined; + } + function enumeratePotentialNonRelativeModules(fragment, scriptPath, options) { + var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; + var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + if (isNestedModule) { + var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); + nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { + if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { + return moduleName.substr(moduleNameWithSeperator_1.length); + } + return moduleName; + }); + } + if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { + var visibleModule = _a[_i]; + if (!isNestedModule) { + nonRelativeModules.push(visibleModule.moduleName); + } + else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { + var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, undefined, ["./*"]); + if (nestedFiles) { + for (var _b = 0, nestedFiles_1 = nestedFiles; _b < nestedFiles_1.length; _b++) { + var f = nestedFiles_1[_b]; + f = ts.normalizePath(f); + var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); + nonRelativeModules.push(nestedModule); + } + } + } + } + } + return ts.deduplicate(nonRelativeModules); + } + function getTripleSlashReferenceCompletion(sourceFile, position) { + var token = ts.getTokenAtPosition(sourceFile, position); + if (!token) { + return undefined; + } + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + if (!commentRanges || !commentRanges.length) { + return undefined; + } + var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.substr(range.pos, position - range.pos); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (match) { + var prefix = match[1]; + var kind = match[2]; + var toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var entries_3; + if (kind === "path") { + var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); + entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + } + else { + var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; + entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries_3 + }; + } + return undefined; + } + function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + if (result === void 0) { result = []; } + if (options.types) { + for (var _i = 0, _a = options.types; _i < _a.length; _i++) { + var moduleName = _a[_i]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + } + else if (host.getDirectories) { + var typeRoots = void 0; + try { + typeRoots = ts.getEffectiveTypeRoots(options, host); + } + catch (e) { } + if (typeRoots) { + for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { + var root = typeRoots_2[_b]; + getCompletionEntriesFromDirectories(host, options, root, span, result); + } + } + } + if (host.getDirectories) { + for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { + var packageJson = _d[_c]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + } + } + return result; + } + function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + if (host.getDirectories && tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { + var typeDirectory = directories_3[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + } + } + } + } + function findPackageJsons(currentDir) { + var paths = []; + var currentConfigPath; + while (true) { + currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); + if (currentConfigPath) { + paths.push(currentConfigPath); + currentDir = ts.getDirectoryPath(currentConfigPath); + var parent_16 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_16) { break; } - case 226: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + currentDir = parent_16; + } + else { break; } - case 221: - case 222: - case 224: - case 171: - case 227: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); - break; - } - case 170: - var openBracket = ts.findChildOfKind(n, 19, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); - break; } - depth++; - ts.forEachChild(n, walk); - depth--; + return paths; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + var result = []; + if (host.readFile && host.fileExists) { + for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = tryReadingPackageJson(packageJson); + if (!contents) { + return; + } + var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); + var foundModuleNames = []; + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + addPotentialPackageNames(contents[key], foundModuleNames); + } + for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { + var moduleName = foundModuleNames_1[_c]; + var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); + result.push({ + moduleName: moduleName, + moduleDir: moduleDir + }); + } + } + } + return result; + function tryReadingPackageJson(filePath) { + try { + var fileText = tryReadFile(host, filePath); + return fileText ? JSON.parse(fileText) : undefined; + } + catch (e) { + return undefined; + } + } + function addPotentialPackageNames(dependencies, result) { + if (dependencies) { + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + } + function createCompletionEntryForModule(name, kind, replacementSpan) { + return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + } + function getDirectoryFragmentTextSpan(text, textStart) { + var index = text.lastIndexOf(ts.directorySeparator); + var offset = index !== -1 ? index + 1 : 0; + return { start: textStart + offset, length: text.length - offset }; + } + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 || slashCharCode === 92; + } + return false; + } + function normalizeAndPreserveTrailingSlash(path) { + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); } - walk(sourceFile); - return elements; } - OutliningElementsCollector.collectElements = collectElements; - })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_2 = completionData.location; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_2) === entryName ? s : undefined; }); + if (symbol) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + return { + name: entryName, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + kind: symbolKind, + displayParts: displayParts, + documentation: documentation + }; + } + } + var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + if (keywordCompletion) { + return { + name: entryName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined + }; + } + return undefined; + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_3 = completionData.location; + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); + } + return undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + function getCompletionData(typeChecker, log, sourceFile, position) { + var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + var isJsDocTagName = false; + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + if (insideComment) { + if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64) { + isJsDocTagName = true; + } + var insideJsDocTagExpression = false; + var tag = ts.getJsDocTagAtPosition(sourceFile, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + isJsDocTagName = true; + } + switch (tag.kind) { + case 277: + case 275: + case 276: + var tagWithExpression = tag; + if (tagWithExpression.typeExpression) { + insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; + } + break; + } + } + if (isJsDocTagName) { + return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + } + if (!insideJsDocTagExpression) { + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile); + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + var contextToken = previousToken; + if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { + var start_2 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + } + var node = currentToken; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent_17 = contextToken.parent, kind = contextToken.kind; + if (kind === 21) { + if (parent_17.kind === 172) { + node = contextToken.parent.expression; + isRightOfDot = true; + } + else if (parent_17.kind === 139) { + node = contextToken.parent.left; + isRightOfDot = true; + } + else { + return undefined; + } + } + else if (sourceFile.languageVariant === 1) { + if (kind === 25) { + isRightOfOpenTag = true; + location = contextToken; + } + else if (kind === 39 && contextToken.parent.kind === 245) { + isStartingCloseTag = true; + location = contextToken; + } + } + } + var semanticStart = ts.timestamp(); + var isMemberCompletion; + var isNewIdentifierLocation; + var symbols = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); + if (tryGetGlobalSymbols()) { + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 8388608)); })); + } + else { + symbols = tagSymbols; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else { + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + function getTypeScriptMemberSymbols() { + isMemberCompletion = true; + isNewIdentifierLocation = false; + if (node.kind === 69 || node.kind === 139 || node.kind === 172) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol && symbol.flags & 8388608) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol && symbol.flags & 1952) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + ts.forEach(exportedSymbols, function (symbol) { + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + }); + } + } + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { + if (type) { + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + } + if (isJavaScriptFile && type.flags & 524288) { + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); + } + } + } + } + function tryGetGlobalSymbols() { + var objectLikeContainer; + var namedImportsOrExports; + var jsxContainer; + if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { + return tryGetObjectLikeCompletionSymbols(objectLikeContainer); + } + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); + } + if (jsxContainer = tryGetContainingJsxElement(contextToken)) { + var attrsType = void 0; + if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { + attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + if (attrsType) { + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); + isMemberCompletion = true; + isNewIdentifierLocation = false; + return true; + } + } + } + isMemberCompletion = false; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + var symbolMeanings = 793064 | 107455 | 1920 | 8388608; + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + return true; + } + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 244) { + return true; + } + if (contextToken.kind === 27 && contextToken.parent) { + if (contextToken.parent.kind === 243) { + return true; + } + if (contextToken.parent.kind === 245 || contextToken.parent.kind === 242) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 241; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + switch (previousToken.kind) { + case 24: + return containingNodeKind === 174 + || containingNodeKind === 148 + || containingNodeKind === 175 + || containingNodeKind === 170 + || containingNodeKind === 187 + || containingNodeKind === 156; + case 17: + return containingNodeKind === 174 + || containingNodeKind === 148 + || containingNodeKind === 175 + || containingNodeKind === 178 + || containingNodeKind === 164; + case 19: + return containingNodeKind === 170 + || containingNodeKind === 153 + || containingNodeKind === 140; + case 125: + case 126: + return true; + case 21: + return containingNodeKind === 225; + case 15: + return containingNodeKind === 221; + case 56: + return containingNodeKind === 218 + || containingNodeKind === 187; + case 12: + return containingNodeKind === 189; + case 13: + return containingNodeKind === 197; + case 112: + case 110: + case 111: + return containingNodeKind === 145; + } + switch (previousToken.getText()) { + case "public": + case "protected": + case "private": + return true; + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + if (contextToken.kind === 9 + || contextToken.kind === 10 + || ts.isTemplateLiteralKind(contextToken.kind)) { + var start_3 = contextToken.getStart(); + var end = contextToken.getEnd(); + if (start_3 < position && position < end) { + return true; + } + if (position === end) { + return !!contextToken.isUnterminated + || contextToken.kind === 10; + } + } + return false; + } + function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + isMemberCompletion = true; + var typeForObject; + var existingMembers; + if (objectLikeContainer.kind === 171) { + isNewIdentifierLocation = true; + typeForObject = typeChecker.getContextualType(objectLikeContainer); + typeForObject = typeForObject && typeForObject.getNonNullableType(); + existingMembers = objectLikeContainer.properties; + } + else if (objectLikeContainer.kind === 167) { + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (ts.isVariableLike(rootDeclaration)) { + var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); + if (!canGetType && rootDeclaration.kind === 142) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 147 || rootDeclaration.parent.kind === 150) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + existingMembers = objectLikeContainer.elements; + } + } + else { + ts.Debug.fail("Root declaration is not variable-like."); + } + } + else { + ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); + } + if (!typeForObject) { + return false; + } + var typeMembers = typeChecker.getPropertiesOfType(typeForObject); + if (typeMembers && typeMembers.length > 0) { + symbols = filterObjectMembersList(typeMembers, existingMembers); + } + return true; + } + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 233 ? + 230 : + 236; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); + } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : ts.emptyArray; + return true; + } + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15: + case 24: + var parent_18 = contextToken.parent; + if (parent_18 && (parent_18.kind === 171 || parent_18.kind === 167)) { + return parent_18; + } + break; + } + } + return undefined; + } + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15: + case 24: + switch (contextToken.parent.kind) { + case 233: + case 237: + return contextToken.parent; + } + } + } + return undefined; + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent_19 = contextToken.parent; + switch (contextToken.kind) { + case 26: + case 39: + case 69: + case 246: + case 247: + if (parent_19 && (parent_19.kind === 242 || parent_19.kind === 243)) { + return parent_19; + } + else if (parent_19.kind === 246) { + return parent_19.parent; + } + break; + case 9: + if (parent_19 && ((parent_19.kind === 246) || (parent_19.kind === 247))) { + return parent_19.parent; + } + break; + case 16: + if (parent_19 && + parent_19.kind === 248 && + parent_19.parent && + (parent_19.parent.kind === 246)) { + return parent_19.parent.parent; + } + if (parent_19 && parent_19.kind === 247) { + return parent_19.parent; + } + break; + } + } + return undefined; + } + function isFunction(kind) { + switch (kind) { + case 179: + case 180: + case 220: + case 147: + case 146: + case 149: + case 150: + case 151: + case 152: + case 153: + return true; + } + return false; + } + function isSolelyIdentifierDefinitionLocation(contextToken) { + var containingNodeKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 24: + return containingNodeKind === 218 || + containingNodeKind === 219 || + containingNodeKind === 200 || + containingNodeKind === 224 || + isFunction(containingNodeKind) || + containingNodeKind === 221 || + containingNodeKind === 192 || + containingNodeKind === 222 || + containingNodeKind === 168 || + containingNodeKind === 223; + case 21: + return containingNodeKind === 168; + case 54: + return containingNodeKind === 169; + case 19: + return containingNodeKind === 168; + case 17: + return containingNodeKind === 252 || + isFunction(containingNodeKind); + case 15: + return containingNodeKind === 224 || + containingNodeKind === 222 || + containingNodeKind === 159; + case 23: + return containingNodeKind === 144 && + contextToken.parent && contextToken.parent.parent && + (contextToken.parent.parent.kind === 222 || + contextToken.parent.parent.kind === 159); + case 25: + return containingNodeKind === 221 || + containingNodeKind === 192 || + containingNodeKind === 222 || + containingNodeKind === 223 || + isFunction(containingNodeKind); + case 113: + return containingNodeKind === 145; + case 22: + return containingNodeKind === 142 || + (contextToken.parent && contextToken.parent.parent && + contextToken.parent.parent.kind === 168); + case 112: + case 110: + case 111: + return containingNodeKind === 142; + case 116: + return containingNodeKind === 234 || + containingNodeKind === 238 || + containingNodeKind === 232; + case 73: + case 81: + case 107: + case 87: + case 102: + case 123: + case 131: + case 89: + case 108: + case 74: + case 114: + case 134: + return true; + } + switch (contextToken.getText()) { + case "abstract": + case "async": + case "class": + case "const": + case "declare": + case "enum": + case "function": + case "interface": + case "let": + case "private": + case "protected": + case "public": + case "static": + case "var": + case "yield": + return true; + } + return false; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var existingImportsOrExports = ts.createMap(); + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_i]; + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_47 = element.propertyName || element.name; + existingImportsOrExports[name_47.text] = true; + } + if (!ts.someProperties(existingImportsOrExports)) { + return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + } + return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); + } + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (!existingMembers || existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + if (m.kind !== 253 && + m.kind !== 254 && + m.kind !== 169 && + m.kind !== 147) { + continue; + } + if (m.getStart() <= position && position <= m.getEnd()) { + continue; + } + var existingName = void 0; + if (m.kind === 169 && m.propertyName) { + if (m.propertyName.kind === 69) { + existingName = m.propertyName.text; + } + } + else { + existingName = m.name.text; + } + existingMemberNames[existingName] = true; + } + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); + } + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + if (attr.getStart() <= position && position <= attr.getEnd()) { + continue; + } + if (attr.kind === 246) { + seenNames[attr.name.text] = true; + } + } + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); + } + } + function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { + var displayName = ts.getDeclaredName(typeChecker, symbol, location); + if (displayName) { + var firstCharCode = displayName.charCodeAt(0); + if ((symbol.flags & 1920) && (firstCharCode === 39 || firstCharCode === 34)) { + return undefined; + } + } + return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + } + function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + if (!name) { + return undefined; + } + name = ts.stripQuotes(name); + if (!name) { + return undefined; + } + if (performCharacterChecks) { + if (!ts.isIdentifierText(name, target)) { + return undefined; + } + } + return name; + } + var keywordCompletions = []; + for (var i = 70; i <= 138; i++) { + keywordCompletions.push({ + name: ts.tokenToString(i), + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + sortText: "0" + }); + } + var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*= 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 104)) { + break; + } + } + } + } + var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70, 75); + } + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 206: + case 207: + case 208: + case 204: + case 205: + return getLoopBreakContinueOccurrences(owner); + case 213: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 96); + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 71, 77); + var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70); + } + }); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getTryCatchFinallyOccurrences(tryStatement) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 100); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 85); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getThrowOccurrences(throwStatement) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + }); + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + }); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getReturnOccurrences(returnStatement) { + var func = ts.getContainingFunction(returnStatement); + if (!(func && hasKind(func.body, 199))) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(func.body, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + }); + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getIfElseOccurrences(ifStatement) { + var keywords = []; + while (hasKind(ifStatement.parent, 203) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + while (ifStatement) { + var children = ifStatement.getChildren(); + pushKeywordIf(keywords, children[0], 88); + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 80)) { + break; + } + } + if (!hasKind(ifStatement.elseStatement, 203)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + var result = []; + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 80 && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; + var shouldCombindElseAndIf = true; + for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombindElseAndIf = false; + break; + } + } + if (shouldCombindElseAndIf) { + result.push({ + fileName: fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: ts.HighlightSpanKind.reference + }); + i++; + continue; + } + } + result.push(getHighlightSpanForNode(keywords[i])); + } + return result; + } + } + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + function isLabeledBy(node, labelName) { + for (var owner = node.parent; owner.kind === 214; owner = owner.parent) { + if (owner.label.text === labelName) { + return true; + } + } + return false; + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function getKeyForCompilationSettings(settings) { + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); + } + function getBucketForCompilationSettings(key, createIfMissing) { + var bucket = buckets[key]; + if (!bucket && createIfMissing) { + buckets[key] = bucket = ts.createFileMap(); + } + return bucket; + } + function reportStats() { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets[name]; + var sourceFiles = []; + entries.forEachValue(function (key, entry) { + sourceFiles.push({ + name: key, + refCount: entry.languageServiceRefCount, + references: entry.owners.slice(0) + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = getBucketForCompilationSettings(key, true); + var entry = bucket.get(path); + if (!entry) { + ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0, + owners: [] + }; + bucket.set(path, entry); + } + else { + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + } + } + if (acquiring) { + entry.languageServiceRefCount++; + } + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = getBucketForCompilationSettings(key, false); + ts.Debug.assert(bucket !== undefined); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.remove(path); + } + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistry = createDocumentRegistry; +})(ts || (ts = {})); +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + function findReferencedSymbols(typeChecker, cancellationToken, sourceFiles, sourceFile, position, findInStrings, findInComments) { + var node = ts.getTouchingPropertyName(sourceFile, position, true); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 8: + if (!ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + break; + } + case 69: + case 97: + case 121: + case 9: + return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, false); + } + return undefined; + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, implementations) { + if (!implementations) { + if (ts.isLabelName(node)) { + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; + } + else { + return getLabelReferencesInNode(node.parent, node); + } + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles); + } + if (node.kind === 95) { + return getReferencesForSuperKeyword(node); + } + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!implementations && !symbol && node.kind === 9) { + return getReferencesForStringLiteral(node, sourceFiles); + } + if (!symbol) { + return undefined; + } + var declarations = symbol.declarations; + if (!declarations || !declarations.length) { + return undefined; + } + var result; + var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), declarations); + var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + var scope = getSymbolScope(symbol); + var symbolToIndex = []; + if (scope) { + result = []; + getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + else { + var internedName = getInternedName(symbol, node, declarations); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + cancellationToken.throwIfCancellationRequested(); + var nameTable = ts.getNameTable(sourceFile); + if (nameTable[internedName] !== undefined) { + result = result || []; + getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + } + } + return result; + function getDefinition(symbol) { + var info = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, node.getSourceFile(), ts.getContainerNode(node), node); + var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) { + return undefined; + } + return { + containerKind: "", + containerName: "", + name: name, + kind: info.symbolKind, + fileName: declarations[0].getSourceFile().fileName, + textSpan: ts.createTextSpan(declarations[0].getStart(), 0), + displayParts: info.displayParts + }; + } + function getAliasSymbolForPropertyNameSymbol(symbol, location) { + if (symbol.flags & 8388608) { + var defaultImport = ts.getDeclarationOfKind(symbol, 231); + if (defaultImport) { + return typeChecker.getAliasedSymbol(symbol); + } + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 || + declaration.kind === 238) ? declaration : undefined; }); + if (importOrExportSpecifier && + (!importOrExportSpecifier.propertyName || + importOrExportSpecifier.propertyName === location)) { + return importOrExportSpecifier.kind === 234 ? + typeChecker.getAliasedSymbol(symbol) : + typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); + } + } + return undefined; + } + function followAliasIfNecessary(symbol, location) { + return getAliasSymbolForPropertyNameSymbol(symbol, location) || symbol; + } + function getPropertySymbolOfDestructuringAssignment(location) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && + typeChecker.getPropertySymbolOfDestructuringAssignment(location); + } + function isObjectBindingPatternElementWithoutPropertyName(symbol) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169); + return bindingElement && + bindingElement.parent.kind === 167 && + !bindingElement.propertyName; + } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169); + var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + return undefined; + } + function getInternedName(symbol, location, declarations) { + if (ts.isImportOrExportSpecifierName(location)) { + return location.getText(); + } + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + symbol = localExportDefaultSymbol || symbol; + return ts.stripQuotes(symbol.name); + } + function getSymbolScope(symbol) { + var valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 179 || valueDeclaration.kind === 192)) { + return valueDeclaration; + } + if (symbol.flags & (4 | 8192)) { + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8) ? d : undefined; }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 221); + } + } + if (symbol.flags & 8388608) { + return undefined; + } + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + return undefined; + } + if (symbol.parent || (symbol.flags & 268435456)) { + return undefined; + } + var scope; + var declarations = symbol.getDeclarations(); + if (declarations) { + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var container = ts.getContainerNode(declaration); + if (!container) { + return undefined; + } + if (scope && scope !== container) { + return undefined; + } + if (container.kind === 256 && !ts.isExternalModule(container)) { + return undefined; + } + scope = container; + } + } + return scope; + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + var positions = []; + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, start); + while (position >= 0) { + cancellationToken.throwIfCancellationRequested(); + if (position > end) + break; + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2))) { + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var references = []; + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.getWidth() !== labelName.length) { + return; + } + if (node === targetLabel || + (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = { + containerKind: "", + containerName: "", + fileName: targetLabel.getSourceFile().fileName, + kind: ts.ScriptElementKind.label, + name: labelName, + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), + displayParts: [ts.displayPart(labelName, ts.SymbolDisplayPartKind.text)] + }; + return [{ definition: definition, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + if (node) { + switch (node.kind) { + case 69: + return node.getWidth() === searchSymbolName.length; + case 9: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isNameOfExternalModuleImportOrDeclaration(node)) { + return node.getWidth() === searchSymbolName.length + 2; + } + break; + case 8: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + return node.getWidth() === searchSymbolName.length; + } + break; + } + } + return false; + } + function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { + var sourceFile = container.getSourceFile(); + var start = findInComments ? container.getFullStart() : container.getStart(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, start, container.getEnd()); + var parents = getParentSymbolsOfPropertyAccess(); + var inheritsFromCache = ts.createMap(); + if (possiblePositions.length) { + var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, searchText)) { + if (!implementations && ((findInStrings && ts.isInString(sourceFile, position)) || + (findInComments && ts.isInNonReferenceComment(sourceFile, position)))) { + result.push({ + definition: undefined, + references: [{ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpan(position, searchText.length), + isWriteAccess: false, + isDefinition: false + }] + }); + } + return; + } + if (!(ts.getMeaningFromLocation(referenceLocation) & searchMeaning)) { + return; + } + var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation); + if (referenceSymbol) { + var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, searchLocation.kind === 121, parents, inheritsFromCache); + if (relatedSymbol) { + addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); + } + else if (!(referenceSymbol.flags & 67108864) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { + addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); + } + else if (searchLocation.kind === 121) { + findAdditionalConstructorReferences(referenceSymbol, referenceLocation); + } + } + }); + } + return; + function getParentSymbolsOfPropertyAccess() { + if (implementations) { + var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(searchLocation); + if (propertyAccessExpression) { + var localParentType = typeChecker.getTypeAtLocation(propertyAccessExpression.expression); + if (localParentType) { + if (localParentType.symbol && localParentType.symbol.flags & (32 | 64) && localParentType.symbol !== searchSymbol.parent) { + return [localParentType.symbol]; + } + else if (localParentType.flags & 1572864) { + return getSymbolsForClassAndInterfaceComponents(localParentType); + } + } + } + } + } + function getPropertyAccessExpressionFromRightHandSide(node) { + return ts.isRightSideOfPropertyAccess(node) && node.parent; + } + function findAdditionalConstructorReferences(referenceSymbol, referenceLocation) { + ts.Debug.assert(ts.isClassLike(searchSymbol.valueDeclaration)); + var referenceClass = referenceLocation.parent; + if (referenceSymbol === searchSymbol && ts.isClassLike(referenceClass)) { + ts.Debug.assert(referenceClass.name === referenceLocation); + addReferences(findOwnConstructorCalls(searchSymbol)); + } + else { + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending && ts.isClassLike(classExtending) && followAliasIfNecessary(referenceSymbol, referenceLocation) === searchSymbol) { + addReferences(superConstructorAccesses(classExtending)); + } + } + } + function addReferences(references) { + if (references.length) { + var referencedSymbol = getReferencedSymbol(searchSymbol); + ts.addRange(referencedSymbol.references, ts.map(references, getReferenceEntryFromNode)); + } + } + function findOwnConstructorCalls(classSymbol) { + var result = []; + for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148); + var ctrKeyword = decl.getChildAt(0); + ts.Debug.assert(ctrKeyword.kind === 121); + result.push(ctrKeyword); + } + ts.forEachProperty(classSymbol.exports, function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 147) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 97, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + result.push(thisKeyword); + } + }); + } + } + }); + return result; + } + function superConstructorAccesses(cls) { + var symbol = cls.symbol; + var ctr = symbol.members["__constructor"]; + if (!ctr) { + return []; + } + var result = []; + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 95, function (node) { + if (ts.isCallExpressionTarget(node)) { + result.push(node); + } + }); + } + } + ; + return result; + } + function getReferencedSymbol(symbol) { + var symbolId = ts.getSymbolId(symbol); + var index = symbolToIndex[symbolId]; + if (index === undefined) { + index = result.length; + symbolToIndex[symbolId] = index; + result.push({ + definition: getDefinition(symbol), + references: [] + }); + } + return result[index]; + } + function addReferenceToRelatedSymbol(node, relatedSymbol) { + var references = getReferencedSymbol(relatedSymbol).references; + if (implementations) { + getImplementationReferenceEntryForNode(node, references); + } + else { + references.push(getReferenceEntryFromNode(node)); + } + } + } + function getImplementationReferenceEntryForNode(refNode, result) { + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + result.push(getReferenceEntryFromNode(refNode.parent)); + } + else if (refNode.kind === 69) { + if (refNode.parent.kind === 254) { + getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); + } + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + result.push(getReferenceEntryFromNode(containingClass)); + return; + } + var containingTypeReference = getContainingTypeReference(refNode); + if (containingTypeReference) { + var parent_21 = containingTypeReference.parent; + if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + } + else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { + if (parent_21.body.kind === 199) { + ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { + maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); + } + }); + } + else if (isImplementationExpression(parent_21.body)) { + maybeAdd(getReferenceEntryFromNode(parent_21.body)); + } + } + else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + } + } + } + function maybeAdd(a) { + if (!ts.forEach(result, function (b) { return a.fileName === b.fileName && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; })) { + result.push(a); + } + } + } + function getSymbolsForClassAndInterfaceComponents(type, result) { + if (result === void 0) { result = []; } + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var componentType = _a[_i]; + if (componentType.symbol && componentType.symbol.getFlags() & (32 | 64)) { + result.push(componentType.symbol); + } + if (componentType.getFlags() & 1572864) { + getSymbolsForClassAndInterfaceComponents(componentType, result); + } + } + return result; + } + function getContainingTypeReference(node) { + var topLevelTypeReference = undefined; + while (node) { + if (ts.isTypeNode(node)) { + topLevelTypeReference = node; + } + node = node.parent; + } + return topLevelTypeReference; + } + function getContainingClassIfInHeritageClause(node) { + if (node && node.parent) { + if (node.kind === 194 + && node.parent.kind === 251 + && ts.isClassLike(node.parent.parent)) { + return node.parent.parent; + } + else if (node.kind === 69 || node.kind === 172) { + return getContainingClassIfInHeritageClause(node.parent); + } + } + return undefined; + } + function isImplementationExpression(node) { + if (node.kind === 178) { + return isImplementationExpression(node.expression); + } + return node.kind === 180 || + node.kind === 179 || + node.kind === 171 || + node.kind === 192 || + node.kind === 170; + } + function explicitlyInheritsFrom(child, parent, cachedResults) { + var parentIsInterface = parent.getFlags() & 64; + return searchHierarchy(child); + function searchHierarchy(symbol) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + if (key in cachedResults) { + return cachedResults[key]; + } + cachedResults[key] = false; + var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + if (parentIsInterface) { + var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); + if (interfaceReferences) { + for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { + var typeReference = interfaceReferences_1[_i]; + if (searchTypeReference(typeReference)) { + return true; + } + } + } + } + return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + } + else if (declaration.kind === 222) { + if (parentIsInterface) { + return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); + } + } + return false; + }); + cachedResults[key] = inherits; + return inherits; + } + function searchTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type && type.symbol) { + return searchHierarchy(type.symbol); + } + } + return false; + } + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, false); + if (!searchSpaceNode) { + return undefined; + } + var staticFlag = 32; + switch (searchSpaceNode.kind) { + case 145: + case 144: + case 147: + case 146: + case 148: + case 149: + case 150: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; + break; + default: + return undefined; + } + var references = []; + var sourceFile = searchSpaceNode.getSourceFile(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.kind !== 95) { + return; + } + var container = ts.getSuperContainer(node, false); + if (container && (32 & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = getDefinition(searchSpaceNode.symbol); + return [{ definition: definition, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); + var staticFlag = 32; + switch (searchSpaceNode.kind) { + case 147: + case 146: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + case 145: + case 144: + case 148: + case 149: + case 150: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; + break; + case 256: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + case 220: + case 179: + break; + default: + return undefined; + } + var references = []; + var possiblePositions; + if (searchSpaceNode.kind === 256) { + ts.forEach(sourceFiles, function (sourceFile) { + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); + }); + } + else { + var sourceFile = searchSpaceNode.getSourceFile(); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); + } + var thisOrSuperSymbol = typeChecker.getSymbolAtLocation(thisOrSuperKeyword); + var displayParts = thisOrSuperSymbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, thisOrSuperSymbol, thisOrSuperKeyword.getSourceFile(), ts.getContainerNode(thisOrSuperKeyword), thisOrSuperKeyword).displayParts; + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: "this", + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: displayParts + }, + references: references + }]; + function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || !ts.isThis(node)) { + return; + } + var container = ts.getThisContainer(node, false); + switch (searchSpaceNode.kind) { + case 179: + case 220: + if (searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 147: + case 146: + if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 192: + case 221: + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32) === staticFlag) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 256: + if (container.kind === 256 && !ts.isExternalModule(container)) { + result.push(getReferenceEntryFromNode(node)); + } + break; + } + }); + } + } + function getReferencesForStringLiteral(node, sourceFiles) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (!type) { + return undefined; + } + var references = []; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); + getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); + } + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: type.text, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: [ts.displayPart(ts.getTextOfNode(node), ts.SymbolDisplayPartKind.stringLiteral)] + }, + references: references + }]; + function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { + for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { + var position = possiblePositions_1[_i]; + cancellationToken.throwIfCancellationRequested(); + var node_2 = ts.getTouchingWord(sourceFile, position); + if (!node_2 || node_2.kind !== 9) { + return; + } + var type_1 = ts.getStringLiteralTypeForNode(node_2, typeChecker); + if (type_1 === searchType) { + references.push(getReferenceEntryFromNode(node_2)); + } + } + } + } + function populateSearchSymbolSet(symbol, location) { + var result = [symbol]; + var containingObjectLiteralElement = getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254) { + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); + if (propertySymbol) { + result.push(propertySymbol); + } + } + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); + if (aliasSymbol) { + result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); + } + if (containingObjectLiteralElement) { + ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); + }); + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); + if (shorthandValueSymbol) { + result.push(shorthandValueSymbol); + } + } + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); + if (bindingElementPropertySymbol) { + result.push(bindingElementPropertySymbol); + } + ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + if (rootSymbol !== symbol) { + result.push(rootSymbol); + } + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap()); + } + }); + return result; + } + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + if (symbol.name in previousIterationSymbolsCache) { + return; + } + if (symbol.flags & (32 | 64)) { + ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); + } + else if (declaration.kind === 222) { + ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); + } + }); + } + return; + function getPropertySymbolFromTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type) { + var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); + if (propertySymbol) { + result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); + } + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); + } + } + } + } + function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation, searchLocationIsConstructor, parents, cache) { + if (ts.contains(searchSymbols, referenceSymbol)) { + return (!searchLocationIsConstructor || ts.isNewExpressionTarget(referenceLocation)) && referenceSymbol; + } + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); + if (aliasSymbol) { + return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation, searchLocationIsConstructor, parents, cache); + } + var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); + if (containingObjectLiteralElement) { + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + }); + if (contextualSymbol) { + return contextualSymbol; + } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); + if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { + return propertySymbol; + } + } + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); + if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { + return bindingElementPropertySymbol; + } + return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { + if (searchSymbols.indexOf(rootSymbol) >= 0) { + return rootSymbol; + } + if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + if (parents) { + if (!ts.forEach(parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, cache); })) { + return undefined; + } + } + var result_3 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, ts.createMap()); + return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + } + return undefined; + }); + } + function getNameFromObjectLiteralElement(node) { + if (node.name.kind === 140) { + var nameExpression = node.name.expression; + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } + return undefined; + } + return node.name.text; + } + function getPropertySymbolsFromContextualType(node) { + var objectLiteral = node.parent; + var contextualType = typeChecker.getContextualType(objectLiteral); + var name = getNameFromObjectLiteralElement(node); + if (name && contextualType) { + var result_4 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_4.push(symbol_2); + } + if (contextualType.flags & 524288) { + ts.forEach(contextualType.types, function (t) { + var symbol = t.getProperty(name); + if (symbol) { + result_4.push(symbol); + } + }); + } + return result_4; + } + return undefined; + } + function getIntersectingMeaningFromDeclarations(meaning, declarations) { + if (declarations) { + var lastIterationMeaning = void 0; + do { + lastIterationMeaning = meaning; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + } + FindAllReferences.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function convertReferences(referenceSymbols) { + if (!referenceSymbols) { + return undefined; + } + var referenceEntries = []; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; + ts.addRange(referenceEntries, referenceSymbol.references); + } + return referenceEntries; + } + FindAllReferences.convertReferences = convertReferences; + function isImplementation(node) { + if (!node) { + return false; + } + else if (ts.isVariableLike(node)) { + if (node.initializer) { + return true; + } + else if (node.kind === 218) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2); + } + } + else if (ts.isFunctionLike(node)) { + return !!node.body || ts.hasModifier(node, 2); + } + else { + switch (node.kind) { + case 221: + case 192: + case 224: + case 225: + return true; + } + } + return false; + } + function getParentStatementOfVariableDeclaration(node) { + if (node.parent && node.parent.parent && node.parent.parent.kind === 200) { + ts.Debug.assert(node.parent.kind === 219); + return node.parent.parent; + } + } + function getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result) { + var refSymbol = typeChecker.getSymbolAtLocation(node); + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1) { + result.push(getReferenceEntryFromNode(declaration)); + } + } + } + } + FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function getReferenceEntryFromNode(node) { + var start = node.getStart(); + var end = node.getEnd(); + if (node.kind === 9) { + start += 1; + end -= 1; + } + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(start, end), + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) + }; + } + FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; + function isWriteAccess(node) { + if (node.kind === 69 && ts.isDeclarationName(node)) { + return true; + } + var parent = node.parent; + if (parent) { + if (parent.kind === 186 || parent.kind === 185) { + return true; + } + else if (parent.kind === 187 && parent.left === node) { + var operator = parent.operatorToken.kind; + return 56 <= operator && operator <= 68; + } + } + return false; + } + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + function getContainingObjectLiteralElement(node) { + switch (node.kind) { + case 9: + case 8: + if (node.parent.kind === 140) { + return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; + } + case 69: + return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function isObjectLiteralPropertyDeclaration(node) { + switch (node.kind) { + case 253: + case 254: + case 147: + case 149: + case 150: + return true; + } + return false; + } + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + function isNameOfExternalModuleImportOrDeclaration(node) { + if (node.kind === 9) { + return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); + } + return false; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + var comment = findReferenceInPosition(sourceFile.referencedFiles, position); + if (comment) { + var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); + if (referenceFile) { + return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; + } + return undefined; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + if (referenceFile && referenceFile.resolvedFileName) { + return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + } + return undefined; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + if (ts.isJumpStatementTarget(node)) { + var labelName = node.text; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfo(label, ts.ScriptElementKind.label, labelName, undefined)] : undefined; + } + var typeChecker = program.getTypeChecker(); + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + if (calledDeclaration) { + return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + if (symbol.flags & 8388608) { + var declaration = symbol.declarations[0]; + if (node.kind === 69 && + (node.parent === declaration || + (declaration.kind === 234 && declaration.parent && declaration.parent.kind === 233))) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + } + if (node.parent.kind === 254) { + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + if (!shorthandSymbol) { + return []; + } + var shorthandDeclarations = shorthandSymbol.getDeclarations(); + var shorthandSymbolKind_1 = ts.SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; + } + if (type.flags & 524288 && !(type.flags & 16)) { + var result_5 = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + ts.addRange(result_5, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + } + }); + return result_5; + } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(typeChecker, type.symbol, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionFromSymbol(typeChecker, symbol, node) { + var result = []; + var declarations = symbol.getDeclarations(); + var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (ts.isNewExpressionTarget(location) || location.kind === 121) { + if (symbol.flags & 32) { + for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isClassLike(declaration)) { + return tryAddSignature(declaration.members, true, symbolKind, symbolName, containerName, result); + } + } + ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 148) || + (!selectConstructors && (d.kind === 220 || d.kind === 147 || d.kind === 146))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } + function createDefinitionInfo(node, symbolKind, symbolName, containerName) { + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function getSymbolInfo(typeChecker, symbol, node) { + return { + symbolName: typeChecker.symbolToString(symbol), + symbolKind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node), + containerName: symbol.parent ? typeChecker.symbolToString(symbol.parent, node) : "" + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + var _a = getSymbolInfo(typeChecker, decl.symbol, decl), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + return createDefinitionInfo(decl, symbolKind, symbolName, containerName); + } + function findReferenceInPosition(refs, pos) { + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + if (ref.pos <= pos && pos < ref.end) { + return ref; + } + } + return undefined; + } + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: ts.ScriptElementKind.scriptElement, + name: name, + containerName: undefined, + containerKind: undefined + }; + } + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + return callLike && typeChecker.getResolvedSignature(callLike).declaration; + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var GoToImplementation; + (function (GoToImplementation) { + function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { + if (node.parent.kind === 254) { + var result = []; + ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); + return result.length > 0 ? result : undefined; + } + else if (node.kind === 95 || ts.isSuperProperty(node.parent)) { + var symbol = typeChecker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)]; + } + else { + var referencedSymbols = ts.FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, false, false, true); + var result = ts.flatMap(referencedSymbols, function (symbol) { + return ts.map(symbol.references, function (_a) { + var textSpan = _a.textSpan, fileName = _a.fileName; + return ({ textSpan: textSpan, fileName: fileName }); + }); + }); + return result && result.length > 0 ? result : undefined; + } + } + GoToImplementation.getImplementationAtPosition = getImplementationAtPosition; + })(GoToImplementation = ts.GoToImplementation || (ts.GoToImplementation = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "augments", + "author", + "argument", + "borrows", + "class", + "constant", + "constructor", + "constructs", + "default", + "deprecated", + "description", + "event", + "example", + "extends", + "field", + "fileOverview", + "function", + "ignore", + "inner", + "lends", + "link", + "memberOf", + "name", + "namespace", + "param", + "private", + "property", + "public", + "requires", + "returns", + "see", + "since", + "static", + "throws", + "type", + "typedef", + "property", + "prop", + "version" + ]; + var jsDocCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + var comments = ts.getJSDocComments(declaration, true); + if (!comments) { + return; + } + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var comment = comments_3[_i]; + if (comment) { + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function forEachUnique(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (ts.indexOf(array, array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getAllJsDocCompletionEntries() { + return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getAllJsDocCompletionEntries = getAllJsDocCompletionEntries; + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + return undefined; + } + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenStart = tokenAtPos.getStart(); + if (!tokenAtPos || tokenStart < position) { + return undefined; + } + var commentOwner; + findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 220: + case 147: + case 148: + case 221: + case 200: + break findOwner; + case 256: + return undefined; + case 225: + if (commentOwner.parent.kind === 225) { + return undefined; + } + break findOwner; + } + } + if (!commentOwner || commentOwner.getStart() < position) { + return undefined; + } + var parameters = getParametersForJsDocOwningNode(commentOwner); + var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); + var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; + var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var docParams = ""; + for (var i = 0, numParams = parameters.length; i < numParams; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 69 ? + currentName.text : + "param" + i; + docParams += indentationStr + " * @param " + paramName + newLine; + } + var preamble = "/**" + newLine + + indentationStr + " * "; + var result = preamble + newLine + + docParams + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getParametersForJsDocOwningNode(commentOwner) { + if (ts.isFunctionLike(commentOwner)) { + return commentOwner.parameters; + } + if (commentOwner.kind === 200) { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + if (varDeclarations.length === 1 && varDeclarations[0].initializer) { + return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + } + } + return ts.emptyArray; + } + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 178) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 179: + case 180: + return rightHandSide.parameters; + case 192: + for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + return member.parameters; + } + } + break; + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = ts.createMap(result.config); + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_48 in packageNameToTypingLocation) { + if (name_48 in inferredTypings && !inferredTypings[name_48]) { + inferredTypings[name_48] = packageNameToTypingLocation[name_48]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); + } + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; var baseSensitivity = { sensitivity: "base" }; - ts.forEach(program.getSourceFiles(), function (sourceFile) { + ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_49 in nameToDeclarations) { + var declarations = nameToDeclarations[name_49]; if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_49); if (!matches) { continue; } - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (patternMatcher.patternContainsDots) { var containers = getContainers(declaration); if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_49); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -39174,8 +54159,8 @@ var ts; return items; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; if (!match.isCaseSensitive) { return false; } @@ -39243,8 +54228,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -39396,9 +54381,9 @@ var ts; case 169: case 218: var decl = node; - var name_37 = decl.name; - if (ts.isBindingPattern(name_37)) { - addChildrenRecursively(name_37); + var name_50 = decl.name; + if (ts.isBindingPattern(name_50)) { + addChildrenRecursively(name_50); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -39444,29 +54429,25 @@ var ts; addLeafNode(node); break; default: - if (node.jsDocComments) { - for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { - var jsDocComment = _j[_h]; - for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { - var tag = _l[_k]; - if (tag.kind === 279) { - addLeafNode(tag); - } + ts.forEach(node.jsDocComments, function (jsDocComment) { + ts.forEach(jsDocComment.tags, function (tag) { + if (tag.kind === 279) { + addLeafNode(tag); } - } - } + }); + }); ts.forEachChild(node, addChildrenRecursively); } } function mergeChildren(children) { - var nameToItems = {}; + var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); if (!name) { return true; } - var itemsWithSameName = ts.getProperty(nameToItems, name); + var itemsWithSameName = nameToItems[name]; if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -39595,7 +54576,7 @@ var ts; case 179: case 221: case 192: - if (node.flags & 512) { + if (ts.getModifierFlags(node) & 512) { return "default"; } return getFunctionOrClassName(node); @@ -39660,6 +54641,7 @@ var ts; case 147: case 149: case 150: + case 218: return hasSomeImportantChild(item); case 180: case 220: @@ -39694,7 +54676,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -39705,7 +54687,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -39725,46 +54707,6 @@ var ts; return spans; } } - function nodeKind(node) { - switch (node.kind) { - case 256: - return ts.ScriptElementKind.moduleElement; - case 255: - return ts.ScriptElementKind.memberVariableElement; - case 218: - case 169: - var variableDeclarationNode = void 0; - var name_38; - if (node.kind === 169) { - name_38 = node.name; - variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(!!variableDeclarationNode); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_38 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return ts.ScriptElementKind.constElement; - } - else if (ts.isLet(variableDeclarationNode)) { - return ts.ScriptElementKind.letElement; - } - else { - return ts.ScriptElementKind.variableElement; - } - case 180: - return ts.ScriptElementKind.functionElement; - case 279: - return ts.ScriptElementKind.typeElement; - default: - return ts.getNodeKind(node); - } - } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); @@ -39802,7 +54744,7 @@ var ts; else if (node.parent.kind === 253 && node.parent.name) { return nodeText(node.parent.name); } - else if (node.flags & 512) { + else if (ts.getModifierFlags(node) & 512) { return "default"; } else { @@ -39815,6 +54757,157 @@ var ts; })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile) { + var elements = []; + var collapseText = "..."; + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + if (hintSpanNode && startElement && endElement) { + var span_12 = { + textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_12); + } + } + function addOutliningSpanComments(commentSpan, autoCollapse) { + if (commentSpan) { + var span_13 = { + textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_13); + } + } + function addOutliningForLeadingCommentsForNode(n) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (comments) { + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var isFirstSingleLineComment = true; + var singleLineCommentCount = 0; + for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { + var currentComment = comments_4[_i]; + if (currentComment.kind === 2) { + if (isFirstSingleLineComment) { + firstSingleLineCommentStart = currentComment.pos; + } + isFirstSingleLineComment = false; + lastSingleLineCommentEnd = currentComment.end; + singleLineCommentCount++; + } + else if (currentComment.kind === 3) { + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + addOutliningSpanComments(currentComment, false); + singleLineCommentCount = 0; + lastSingleLineCommentEnd = -1; + isFirstSingleLineComment = true; + } + } + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + } + } + function combineAndAddMultipleSingleLineComments(count, start, end) { + if (count > 1) { + var multipleSingleLineComments = { + pos: start, + end: end, + kind: 2 + }; + addOutliningSpanComments(multipleSingleLineComments, false); + } + } + function autoCollapse(node) { + return ts.isFunctionBlock(node) && node.parent.kind !== 180; + } + var depth = 0; + var maxDepth = 20; + function walk(n) { + if (depth > maxDepth) { + return; + } + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n); + } + switch (n.kind) { + case 199: + if (!ts.isFunctionBlock(n)) { + var parent_22 = n.parent; + var openBrace = ts.findChildOfKind(n, 15, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + if (parent_22.kind === 204 || + parent_22.kind === 207 || + parent_22.kind === 208 || + parent_22.kind === 206 || + parent_22.kind === 203 || + parent_22.kind === 205 || + parent_22.kind === 212 || + parent_22.kind === 252) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + if (parent_22.kind === 216) { + var tryStatement = parent_22; + if (tryStatement.tryBlock === n) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + else if (tryStatement.finallyBlock === n) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); + if (finallyKeyword) { + addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + break; + } + } + } + var span_14 = ts.createTextSpanFromBounds(n.getStart(), n.end); + elements.push({ + textSpan: span_14, + hintSpan: span_14, + bannerText: collapseText, + autoCollapse: autoCollapse(n) + }); + break; + } + case 226: { + var openBrace = ts.findChildOfKind(n, 15, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 221: + case 222: + case 224: + case 171: + case 227: { + var openBrace = ts.findChildOfKind(n, 15, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 170: + var openBracket = ts.findChildOfKind(n, 19, sourceFile); + var closeBracket = ts.findChildOfKind(n, 20, sourceFile); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + break; + } + depth++; + ts.forEachChild(n, walk); + depth--; + } + walk(sourceFile); + return elements; + } + OutliningElementsCollector.collectElements = collectElements; + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +var ts; (function (ts) { (function (PatternMatchKind) { PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; @@ -39832,7 +54925,7 @@ var ts; }; } function createPatternMatcher(pattern) { - var stringToWordSpans = {}; + var stringToWordSpans = ts.createMap(); pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -39875,7 +54968,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -39887,7 +54980,7 @@ var ts; return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text); } else { - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -39895,9 +54988,9 @@ var ts; if (index > 0) { var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span = wordSpans_1[_i]; - if (partStartsWith(candidate, span, chunk.text, true)) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span, chunk.text, false)); + var span_15 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_15, chunk.text, true)) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span_15, chunk.text, false)); } } } @@ -40059,14 +55152,6 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function startsWith(string, search) { - for (var i = 0, n = search.length; i < n; i++) { - if (string.charCodeAt(i) !== search.charCodeAt(i)) { - return false; - } - } - return true; - } function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { if (startsWithIgnoringCase(string, value, i)) { @@ -40231,6 +55316,383 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var referencedFiles = []; + var typeReferenceDirectives = []; + var importedFiles = []; + var ambientExternalModules; + var isNoDefaultLib = false; + var braceNesting = 0; + var externalModule = false; + function nextToken() { + var token = ts.scanner.scan(); + if (token === 15) { + braceNesting++; + } + else if (token === 16) { + braceNesting--; + } + return token; + } + function processTripleSlashDirectives() { + var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); + ts.forEach(commentRanges, function (commentRange) { + var comment = sourceText.substring(commentRange.pos, commentRange.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); + if (referencePathMatchResult) { + isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var fileReference = referencePathMatchResult.fileReference; + if (fileReference) { + var collection = referencePathMatchResult.isTypeReferenceDirective + ? typeReferenceDirectives + : referencedFiles; + collection.push(fileReference); + } + } + }); + } + function getFileReference() { + var file = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { + fileName: file, + pos: pos, + end: pos + file.length + }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 122) { + token = nextToken(); + if (token === 125) { + token = nextToken(); + if (token === 9) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + function tryConsumeImport() { + var token = ts.scanner.getToken(); + if (token === 89) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + return true; + } + else { + if (token === 69 || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + return true; + } + } + else if (token === 56) { + if (tryConsumeRequireCall(true)) { + return true; + } + } + else if (token === 24) { + token = nextToken(); + } + else { + return true; + } + } + if (token === 15) { + token = nextToken(); + while (token !== 16 && token !== 1) { + token = nextToken(); + } + if (token === 16) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + } + else if (token === 37) { + token = nextToken(); + if (token === 116) { + token = nextToken(); + if (token === 69 || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 82) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 15) { + token = nextToken(); + while (token !== 16 && token !== 1) { + token = nextToken(); + } + if (token === 16) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + } + else if (token === 37) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + else if (token === 89) { + token = nextToken(); + if (token === 69 || ts.isKeyword(token)) { + token = nextToken(); + if (token === 56) { + if (tryConsumeRequireCall(true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 129) { + token = nextToken(); + if (token === 17) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 69 && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 17) { + return true; + } + token = nextToken(); + if (token === 9) { + token = nextToken(); + if (token === 24) { + token = nextToken(); + } + else { + return true; + } + } + if (token !== 19) { + return true; + } + token = nextToken(); + var i = 0; + while (token !== 20 && token !== 1) { + if (token === 9) { + recordModuleName(); + i++; + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + while (true) { + if (ts.scanner.getToken() === 1) { + break; + } + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + processTripleSlashDirectives(); + if (externalModule) { + if (ambientExternalModules) { + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + } + else { + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); + var node = ts.getTouchingWord(sourceFile, position, true); + if (node) { + if (node.kind === 69 || + node.kind === 9 || + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + ts.isThis(node)) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + if (ts.forEach(declarations, isDefinedInLibraryFile)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + if (kind) { + return { + canRename: true, + kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + else if (node.kind === 9) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (type) { + if (isDefinedInLibraryFile(node)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + else { + var displayName = ts.stripQuotes(type.text); + return { + canRename: true, + kind: ts.ScriptElementKind.variableElement, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: displayName, + kindModifiers: ts.ScriptElementKindModifier.none, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + } + } + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); + function getRenameInfoError(localizedErrorMessage) { + return { + canRename: false, + localizedErrorMessage: localizedErrorMessage, + displayName: undefined, + fullDisplayName: undefined, + kind: undefined, + kindModifiers: undefined, + triggerSpan: undefined + }; + } + function isDefinedInLibraryFile(declaration) { + if (defaultLibFileName) { + var sourceFile_1 = declaration.getSourceFile(); + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_1.fileName)); + if (canonicalName === canonicalDefaultLibName) { + return true; + } + } + return false; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 9) { + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + } + Rename.getRenameInfo = getRenameInfo; + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { @@ -40277,10 +55739,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = ts.getProperty(nameToDeclarations, name.text); + var declarations = nameToDeclarations[name.text]; if (declarations) { - for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { - var declaration = declarations_8[_b]; + for (var _b = 0, declarations_10 = declarations; _b < declarations_10.length; _b++) { + var declaration = declarations_10[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -40541,920 +56003,569 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getLineStartPositionForPosition(position, sourceFile) { - var lineStarts = sourceFile.getLineStarts(); - var line = sourceFile.getLineAndCharacterOfPosition(position).line; - return lineStarts[line]; - } - ts.getLineStartPositionForPosition = getLineStartPositionForPosition; - function rangeContainsRange(r1, r2) { - return startEndContainsRange(r1.pos, r1.end, r2); - } - ts.rangeContainsRange = rangeContainsRange; - function startEndContainsRange(start, end, range) { - return start <= range.pos && end >= range.end; - } - ts.startEndContainsRange = startEndContainsRange; - function rangeContainsStartEnd(range, start, end) { - return range.pos <= start && range.end >= end; - } - ts.rangeContainsStartEnd = rangeContainsStartEnd; - function rangeOverlapsWithStartEnd(r1, start, end) { - return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); - } - ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; - function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { - var start = Math.max(start1, start2); - var end = Math.min(end1, end2); - return start < end; - } - ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; - function positionBelongsToNode(candidate, position, sourceFile) { - return candidate.end > position || !isCompletedNode(candidate, sourceFile); - } - ts.positionBelongsToNode = positionBelongsToNode; - function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { - return false; - } - switch (n.kind) { - case 221: - case 222: - case 224: - case 171: - case 167: - case 159: - case 199: - case 226: - case 227: - case 233: - case 237: - return nodeEndsWith(n, 16, sourceFile); - case 252: - return isCompletedNode(n.block, sourceFile); - case 175: - if (!n.arguments) { - return true; - } - case 174: - case 178: - case 164: - return nodeEndsWith(n, 18, sourceFile); - case 156: - case 157: - return isCompletedNode(n.type, sourceFile); - case 148: - case 149: - case 150: - case 220: - case 179: - case 147: - case 146: - case 152: - case 151: - case 180: - if (n.body) { - return isCompletedNode(n.body, sourceFile); - } - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - return hasChildOfKind(n, 18, sourceFile); - case 225: - return n.body && isCompletedNode(n.body, sourceFile); - case 203: - if (n.elseStatement) { - return isCompletedNode(n.elseStatement, sourceFile); - } - return isCompletedNode(n.thenStatement, sourceFile); - case 202: - return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23); - case 170: - case 168: - case 173: - case 140: - case 161: - return nodeEndsWith(n, 20, sourceFile); - case 153: - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - return hasChildOfKind(n, 20, sourceFile); - case 249: - case 250: - return false; - case 206: - case 207: - case 208: - case 205: - return isCompletedNode(n.statement, sourceFile); - case 204: - var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 18, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); - case 158: - return isCompletedNode(n.exprName, sourceFile); - case 182: - case 181: - case 183: - case 190: - case 191: - var unaryWordExpression = n; - return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176: - return isCompletedNode(n.template, sourceFile); - case 189: - var lastSpan = ts.lastOrUndefined(n.templateSpans); - return isCompletedNode(lastSpan, sourceFile); - case 197: - return ts.nodeIsPresent(n.literal); - case 236: - case 230: - return ts.nodeIsPresent(n.moduleSpecifier); - case 185: - return isCompletedNode(n.operand, sourceFile); - case 187: - return isCompletedNode(n.right, sourceFile); - case 188: - return isCompletedNode(n.whenFalse, sourceFile); - default: - return true; - } - } - ts.isCompletedNode = isCompletedNode; - function nodeEndsWith(n, expectedLastToken, sourceFile) { - var children = n.getChildren(sourceFile); - if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { - return true; - } - else if (last.kind === 23 && children.length !== 1) { - return children[children.length - 2].kind === expectedLastToken; + var SymbolDisplay; + (function (SymbolDisplay) { + function getSymbolKind(typeChecker, symbol, location) { + var flags = symbol.getFlags(); + if (flags & 32) + return ts.getDeclarationOfKind(symbol, 192) ? + ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + if (flags & 384) + return ts.ScriptElementKind.enumElement; + if (flags & 524288) + return ts.ScriptElementKind.typeElement; + if (flags & 64) + return ts.ScriptElementKind.interfaceElement; + if (flags & 262144) + return ts.ScriptElementKind.typeParameterElement; + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location); + if (result === ts.ScriptElementKind.unknown) { + if (flags & 262144) + return ts.ScriptElementKind.typeParameterElement; + if (flags & 8) + return ts.ScriptElementKind.variableElement; + if (flags & 8388608) + return ts.ScriptElementKind.alias; + if (flags & 1536) + return ts.ScriptElementKind.moduleElement; } + return result; } - return false; - } - function findListItemInfo(node) { - var list = findContainingList(node); - if (!list) { - return undefined; - } - var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); - return { - listItemIndex: listItemIndex, - list: list - }; - } - ts.findListItemInfo = findListItemInfo; - function hasChildOfKind(n, kind, sourceFile) { - return !!findChildOfKind(n, kind, sourceFile); - } - ts.hasChildOfKind = hasChildOfKind; - function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); - } - ts.findChildOfKind = findChildOfKind; - function findContainingList(node) { - var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 282 && c.pos <= node.pos && c.end >= node.end) { - return c; + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location) { + if (typeChecker.isUndefinedSymbol(symbol)) { + return ts.ScriptElementKind.variableElement; } - }); - ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); - return syntaxList; - } - ts.findContainingList = findContainingList; - function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); - } - ts.getTouchingWord = getTouchingWord; - function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); - } - ts.getTouchingPropertyName = getTouchingPropertyName; - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); - } - ts.getTouchingToken = getTouchingToken; - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); - } - ts.getTokenAtPosition = getTokenAtPosition; - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - var current = sourceFile; - outer: while (true) { - if (isToken(current)) { - return current; + if (typeChecker.isArgumentsSymbol(symbol)) { + return ts.ScriptElementKind.localVariableElement; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; + if (location.kind === 97 && ts.isExpression(location)) { + return ts.ScriptElementKind.parameterElement; + } + if (flags & 3) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return ts.ScriptElementKind.parameterElement; + } + else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return ts.ScriptElementKind.letElement; + } + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + } + if (flags & 16) + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + if (flags & 32768) + return ts.ScriptElementKind.memberGetAccessorElement; + if (flags & 65536) + return ts.ScriptElementKind.memberSetAccessorElement; + if (flags & 8192) + return ts.ScriptElementKind.memberFunctionElement; + if (flags & 16384) + return ts.ScriptElementKind.constructorImplementationElement; + if (flags & 4) { + if (flags & 268435456) { + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 | 3)) { + return ts.ScriptElementKind.memberVariableElement; } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; + ts.Debug.assert(!!(rootSymbolFlags & 8192)); + }); + if (!unionPropertyKind) { + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return ts.ScriptElementKind.memberFunctionElement; + } + return ts.ScriptElementKind.memberVariableElement; + } + return unionPropertyKind; + } + return ts.ScriptElementKind.memberVariableElement; + } + return ts.ScriptElementKind.unknown; + } + function getSymbolModifiers(symbol) { + return symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : ts.ScriptElementKindModifier.none; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var symbolFlags = symbol.flags; + var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); + var hasAddedSymbolInfo; + var isThisExpression = location.kind === 97 && ts.isExpression(location); + var type; + if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { + if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { + symbolKind = ts.ScriptElementKind.memberVariableElement; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (type) { + if (location.parent && location.parent.kind === 172) { + var right = location.parent.name; + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + var callExpression = void 0; + if (location.kind === 174 || location.kind === 175) { + callExpression = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpression = location.parent; + } + if (callExpression) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); + if (!signature && candidateSignatures.length) { + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpression.kind === 175 || callExpression.expression.kind === 95; + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32)) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 8388608) { + symbolKind = ts.ScriptElementKind.alias; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case ts.ScriptElementKind.memberVariableElement: + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.parameterElement: + case ts.ScriptElementKind.localVariableElement: + displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + if (!(type.flags & 2097152) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); + } + addSignatureDisplayParts(signature, allSignatures, 8); + break; + default: + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || + (location.kind === 121 && location.parent.kind === 148)) { + var functionDeclaration = location.parent; + var allSignatures = functionDeclaration.kind === 148 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration.kind === 148) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { + if (ts.getDeclarationOfKind(symbol, 192)) { + pushTypePart(ts.ScriptElementKind.localClassElement); + } + else { + displayParts.push(ts.keywordPart(73)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64) && (semanticMeaning & 2)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(107)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if (symbolFlags & 524288) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(134)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); + } + if (symbolFlags & 384) { + addNewLineIfDisplayPartsExist(); + if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + displayParts.push(ts.keywordPart(74)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(81)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536) { + addNewLineIfDisplayPartsExist(); + var declaration = ts.getDeclarationOfKind(symbol, 225); + var isNamespace = declaration && declaration.name && declaration.name.kind === 69; + displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144) && (semanticMeaning & 2)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(90)); + displayParts.push(ts.spacePart()); + if (symbol.parent) { + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + var declaration = ts.getDeclarationOfKind(symbol, 141); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 152) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 151 && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); + } + else { + displayParts.push(ts.keywordPart(134)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8) { + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 255) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + } + } + } + if (symbolFlags & 8388608) { + addNewLineIfDisplayPartsExist(); + if (symbol.declarations[0].kind === 228) { + displayParts.push(ts.keywordPart(82)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(126)); + } + else { + displayParts.push(ts.keywordPart(89)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 229) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129)); + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(18)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== ts.ScriptElementKind.unknown) { + if (type) { + if (isThisExpression) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(97)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + if (symbolKind === ts.ScriptElementKind.memberVariableElement || + symbolFlags & 3 || + symbolKind === ts.ScriptElementKind.localVariableElement || + isThisExpression) { + displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.spacePart()); + if (type.symbol && type.symbol.flags & 262144) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 || + symbolFlags & 8192 || + symbolFlags & 16384 || + symbolFlags & 131072 || + symbolFlags & 98304 || + symbolKind === ts.ScriptElementKind.memberFunctionElement) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(); + if (documentation.length === 0 && symbol.flags & 4) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 187) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; } } } } } - for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { - var child = current.getChildAt(i); - if (ts.isJSDocNode(child)) { - continue; - } - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + function addNewLineIfDisplayPartsExist() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); } } - return current; - } - } - function findTokenOnLeftOfPosition(file, position) { - var tokenAtPosition = getTokenAtPosition(file, position); - if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { - return tokenAtPosition; - } - return findPrecedingToken(position, file); - } - ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { - return find(parent); - function find(n) { - if (isToken(n) && n.pos === previousToken.end) { - return n; + function addFullSymbolName(symbol, enclosingDeclaration) { + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); + ts.addRange(displayParts, fullSymbolDisplayParts); } - var children = n.getChildren(); - for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { - var child = children_1[_i]; - var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || - (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { - return find(child); + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + addNewLineIfDisplayPartsExist(); + if (symbolKind) { + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); } } - return undefined; - } - } - ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { - return find(startNode || sourceFile); - function findRightmostToken(n) { - if (isToken(n) || n.kind === 244) { - return n; - } - var children = n.getChildren(); - var candidate = findRightmostChildNodeWithTokens(children, children.length); - return candidate && findRightmostToken(candidate); - } - function find(n) { - if (isToken(n) || n.kind === 244) { - return n; - } - var children = n.getChildren(); - for (var i = 0, len = children.length; i < len; i++) { - var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 244)) { - var start = child.getStart(sourceFile); - var lookInPreviousChild = (start >= position) || - (child.kind === 244 && start === child.end); - if (lookInPreviousChild) { - var candidate = findRightmostChildNodeWithTokens(children, i); - return candidate && findRightmostToken(candidate); - } - else { - return find(child); - } + function pushTypePart(symbolKind) { + switch (symbolKind) { + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.functionElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.constructorImplementationElement: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(18)); + return; } } - ts.Debug.assert(startNode !== undefined || n.kind === 256); - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, children.length); - return candidate && findRightmostToken(candidate); - } - } - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { - for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { - return children[i]; + function addSignatureDisplayParts(signature, allSignatures, flags) { + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.operatorPart(35)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(18)); } + documentation = signature.getDocumentationComment(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); } } - } - ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 || previousToken.kind === 166)) { - var start = previousToken.getStart(); - var end = previousToken.getEnd(); - if (start < position && position < end) { - return true; + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; } - if (position === end) { - return !!previousToken.isUnterminated; - } - } - return false; - } - ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; - function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - if (!token) { - return false; - } - if (token.kind === 244) { - return true; - } - if (token.kind === 25 && token.parent.kind === 244) { - return true; - } - if (token.kind === 25 && token.parent.kind === 248) { - return true; - } - if (token && token.kind === 16 && token.parent.kind === 248) { - return true; - } - if (token.kind === 25 && token.parent.kind === 245) { - return true; - } - return false; - } - ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; - function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); - } - ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 ? position <= c.end : position < c.end); }); - } - return false; - } - ts.isInCommentHelper = isInCommentHelper; - function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return ts.forEach(commentRanges, jsDocPrefix); - function jsDocPrefix(c) { - var text = sourceFile.text; - return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; - } - } - ts.hasDocComment = hasDocComment; - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (isToken(node)) { - switch (node.kind) { - case 102: - case 108: - case 74: - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } + return ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 179) { + return true; } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; - function nodeHasTokens(n) { - return n.getWidth() !== 0; - } - function getNodeModifiers(node) { - var flags = ts.getCombinedNodeFlags(node); - var result = []; - if (flags & 8) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 16) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 4) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 32) - result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 128) - result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1) - result.push(ts.ScriptElementKindModifier.exportedModifier); - if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; - } - ts.getNodeModifiers = getNodeModifiers; - function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 || node.kind === 174) { - return node.typeArguments; - } - if (ts.isFunctionLike(node) || node.kind === 221 || node.kind === 222) { - return node.typeParameters; - } - return undefined; - } - ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; - function isToken(n) { - return n.kind >= 0 && n.kind <= 138; - } - ts.isToken = isToken; - function isWord(kind) { - return kind === 69 || ts.isKeyword(kind); - } - ts.isWord = isWord; - function isPropertyName(kind) { - return kind === 9 || kind === 8 || isWord(kind); - } - function isComment(kind) { - return kind === 2 || kind === 3; - } - ts.isComment = isComment; - function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 - || kind === 166 - || kind === 10 - || ts.isTemplateLiteralKind(kind)) { - return true; - } - return false; - } - ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; - function isPunctuation(kind) { - return 15 <= kind && kind <= 68; - } - ts.isPunctuation = isPunctuation; - function isInsideTemplateLiteral(node, position) { - return ts.isTemplateLiteralKind(node.kind) - && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); - } - ts.isInsideTemplateLiteral = isInsideTemplateLiteral; - function isAccessibilityModifier(kind) { - switch (kind) { - case 112: - case 110: - case 111: - return true; - } - return false; - } - ts.isAccessibilityModifier = isAccessibilityModifier; - function compareDataObjects(dst, src) { - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { + if (declaration.kind !== 218 && declaration.kind !== 220) { return false; } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; + for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { + if (parent_23.kind === 256 || parent_23.kind === 226) { + return false; + } } - } + return true; + }); } - return true; - } - ts.compareDataObjects = compareDataObjects; - function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 || - node.kind === 171) { - if (node.parent.kind === 187 && - node.parent.left === node && - node.parent.operatorToken.kind === 56) { - return true; - } - if (node.parent.kind === 208 && - node.parent.initializer === node) { - return true; - } - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 ? node.parent.parent : node.parent)) { - return true; - } - } - return false; - } - ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); })(ts || (ts = {})); var ts; (function (ts) { - function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; - } - ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; - var displayPartWriter = getDisplayPartWriter(); - function getDisplayPartWriter() { - var displayParts; - var lineStart; - var indent; - resetWriter(); - return { - displayParts: function () { return displayParts; }, - writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, - writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, - writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, - writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, - writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, - writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, - writeSymbol: writeSymbol, - writeLine: writeLine, - increaseIndent: function () { indent++; }, - decreaseIndent: function () { indent--; }, - clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + options.suppressOutputPathCheck = true; + options.allowNonTsExtensions = true; + options.noLib = true; + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + options.noResolve = true; + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; + } + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); + } + var newLine = ts.getNewLineCharacter(options); + var outputText; + var sourceMapText; + var compilerHost = { + getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text, writeByteOrderMark) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + sourceMapText = text; + } + else { + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; - function writeIndent() { - if (lineStart) { - var indentString = ts.getIndentString(indent); - if (indentString) { - displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + } + program.emit(); + ts.Debug.assert(outputText !== undefined, "Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; + } + ts.transpileModule = transpileModule; + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; + } + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + function fixupCompilerOptions(options, diagnostics) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.clone(options); + var _loop_2 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + if (typeof value === "string") { + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); } - lineStart = false; } - } - function writeKind(text, kind) { - writeIndent(); - displayParts.push(displayPart(text, kind)); - } - function writeSymbol(text, symbol) { - writeIndent(); - displayParts.push(symbolPart(text, symbol)); - } - function writeLine() { - displayParts.push(lineBreakPart()); - lineStart = true; - } - function resetWriter() { - displayParts = []; - lineStart = true; - indent = 0; - } - } - function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); - function displayPartKind(symbol) { - var flags = symbol.flags; - if (flags & 3) { - return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; - } - else if (flags & 4) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 32768) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 65536) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 8) { - return ts.SymbolDisplayPartKind.enumMemberName; - } - else if (flags & 16) { - return ts.SymbolDisplayPartKind.functionName; - } - else if (flags & 32) { - return ts.SymbolDisplayPartKind.className; - } - else if (flags & 64) { - return ts.SymbolDisplayPartKind.interfaceName; - } - else if (flags & 384) { - return ts.SymbolDisplayPartKind.enumName; - } - else if (flags & 1536) { - return ts.SymbolDisplayPartKind.moduleName; - } - else if (flags & 8192) { - return ts.SymbolDisplayPartKind.methodName; - } - else if (flags & 262144) { - return ts.SymbolDisplayPartKind.typeParameterName; - } - else if (flags & 524288) { - return ts.SymbolDisplayPartKind.aliasName; - } - else if (flags & 8388608) { - return ts.SymbolDisplayPartKind.aliasName; - } - return ts.SymbolDisplayPartKind.text; - } - } - ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] }; - } - ts.displayPart = displayPart; - function spacePart() { - return displayPart(" ", ts.SymbolDisplayPartKind.space); - } - ts.spacePart = spacePart; - function keywordPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); - } - ts.keywordPart = keywordPart; - function punctuationPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); - } - ts.punctuationPart = punctuationPart; - function operatorPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); - } - ts.operatorPart = operatorPart; - function textOrKeywordPart(text) { - var kind = ts.stringToToken(text); - return kind === undefined - ? textPart(text) - : keywordPart(kind); - } - ts.textOrKeywordPart = textOrKeywordPart; - function textPart(text) { - return displayPart(text, ts.SymbolDisplayPartKind.text); - } - ts.textPart = textPart; - var carriageReturnLineFeed = "\r\n"; - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; - } - ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; - function lineBreakPart() { - return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); - } - ts.lineBreakPart = lineBreakPart; - function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; - } - ts.mapToDisplayParts = mapToDisplayParts; - function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - }); - } - ts.typeToDisplayParts = typeToDisplayParts; - function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { - return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); - }); - } - ts.symbolToDisplayParts = symbolToDisplayParts; - function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); - }); - } - ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - if (isImportOrExportSpecifierName(location)) { - return location.getText(); + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_2(opt); } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140) { - return location.text; - } - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); - return name; + return options; } - ts.getDeclaredName = getDeclaredName; - function isImportOrExportSpecifierName(location) { - return location.parent && - (location.parent.kind === 234 || location.parent.kind === 238) && - location.parent.propertyName === location; - } - ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; - function stripQuotes(name) { - var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 || name.charCodeAt(0) === 39)) { - return name.substring(1, length - 1); - } - ; - return name; - } - ts.stripQuotes = stripQuotes; - function scriptKindIs(fileName, host) { - var scriptKinds = []; - for (var _i = 2; _i < arguments.length; _i++) { - scriptKinds[_i - 2] = arguments[_i]; - } - var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); - } - ts.scriptKindIs = scriptKindIs; - function getScriptKind(fileName, host) { - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind || scriptKind === 0) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); - } - ts.getScriptKind = getScriptKind; -})(ts || (ts = {})); -var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - var safeList; - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = {}; - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - if (result.config) { - safeList = result.config; - } - else { - safeList = {}; - } - ; - } - var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - for (var name_39 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { - inferredTypings[name_39] = packageNameToTypingLocation[name_39]; - } - } - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { - inferredTypings[typing] = undefined; - } - } - } - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); - } - } - } - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; - var normalizedFileName = ts.normalizePath(fileName); - if (ts.getBaseFileName(normalizedFileName) !== "package.json") { - continue; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -41551,6 +56662,9 @@ var ts; } return false; } + function shouldRescanJsxText(node) { + return node && node.kind === 244; + } function shouldRescanSlashToken(container) { return container.kind === 10; } @@ -41578,7 +56692,9 @@ var ts; ? 3 : shouldRescanJsxIdentifier(n) ? 4 - : 0; + : shouldRescanJsxText(n) + ? 5 + : 0; if (lastTokenInfo && expectedScanAction === lastScanAction) { return fixTokenKind(lastTokenInfo, n); } @@ -41606,6 +56722,10 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4; } + else if (expectedScanAction === 5) { + currentToken = scanner.reScanJsxToken(); + lastScanAction = 5; + } else { lastScanAction = 0; } @@ -41848,9 +56968,9 @@ var ts; } return true; }; - RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); + RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41885,6 +57005,8 @@ var ts; this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -41907,7 +57029,7 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 131]), 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); @@ -41926,7 +57048,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.FromTokens([17, 19, 27, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); @@ -41938,6 +57059,11 @@ var ts; this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -41951,7 +57077,7 @@ var ts; this.SpaceAfterPostdecrementWhenFollowedBySubtract, this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, this.NoSpaceAfterCloseBrace, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, @@ -41964,6 +57090,8 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, + this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, + this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, this.SpaceAfterModuleName, @@ -41976,7 +57104,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket, this.NoSpaceBeforeCloseAngularBracket, this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, @@ -41991,8 +57118,8 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); @@ -42018,18 +57145,20 @@ var ts; this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_40 in o) { - if (o[name_40] === rule) { - return name_40; + for (var name_51 in o) { + if (o[name_51] === rule) { + return name_51; } } throw new Error("Unknown rule"); @@ -42196,12 +57325,21 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244; }; - Rules.isNonJsxElementContext = function (context) { + Rules.IsNonJsxElementContext = function (context) { return context.contextNode.kind !== 241; }; - Rules.isJsxExpressionContext = function (context) { + Rules.IsJsxExpressionContext = function (context) { return context.contextNode.kind === 248; }; + Rules.IsNextTokenParentJsxAttribute = function (context) { + return context.nextTokenParent.kind === 246; + }; + Rules.IsJsxAttributeContext = function (context) { + return context.contextNode.kind === 246; + }; + Rules.IsJsxSelfClosingElementContext = function (context) { + return context.contextNode.kind === 242; + }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -42212,7 +57350,7 @@ var ts; !Rules.NodeIsInDecoratorContext(context.nextTokenParent); }; Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isExpression(node)) { + while (ts.isPartOfExpression(node)) { node = node.parent; } return node.kind === 143; @@ -42504,21 +57642,21 @@ var ts; TokenRange.prototype.toString = function () { return this.tokenAccess.toString(); }; - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(70, 138); - TokenRange.BinaryOperators = TokenRange.FromRange(25, 68); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 138, 116, 124]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41, 42, 50, 49]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 69, 17, 19, 15, 97, 92]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([69, 130, 132, 120, 133, 103, 117]); return TokenRange; }()); + TokenRange.Any = TokenRange.AllTokens(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); + TokenRange.Keywords = TokenRange.FromRange(70, 138); + TokenRange.BinaryOperators = TokenRange.FromRange(25, 68); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 138, 116, 124]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41, 42, 50, 49]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 69, 17, 19, 15, 97, 92]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([69, 130, 132, 120, 133, 103, 117]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -42589,6 +57727,16 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + rules.push(this.globalRules.SpaceAfterOpenBrace); + rules.push(this.globalRules.SpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } + else { + rules.push(this.globalRules.NoSpaceAfterOpenBrace); + rules.push(this.globalRules.NoSpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); @@ -42626,6 +57774,12 @@ var ts; rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } + if (options.InsertSpaceAfterTypeAssertion) { + rules.push(this.globalRules.SpaceAfterTypeAssertion); + } + else { + rules.push(this.globalRules.NoSpaceAfterTypeAssertion); + } rules = rules.concat(this.globalRules.LowPriorityCommonRules); return rules; }; @@ -43535,7 +58689,7 @@ var ts; } } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { - var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && (parent.kind === 256 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; @@ -43788,85 +58942,22 @@ var ts; var ts; (function (ts) { ts.servicesVersion = "0.5"; - var ScriptSnapshot; - (function (ScriptSnapshot) { - var StringScriptSnapshot = (function () { - function StringScriptSnapshot(text) { - this.text = text; - } - StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringScriptSnapshot.prototype.getLength = function () { - return this.text.length; - }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { - return undefined; - }; - return StringScriptSnapshot; - }()); - function fromString(text) { - return new StringScriptSnapshot(text); - } - ScriptSnapshot.fromString = fromString; - })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - var scanner = ts.createScanner(2, true); - var emptyArray = []; - var jsDocTagNames = [ - "augments", - "author", - "argument", - "borrows", - "class", - "constant", - "constructor", - "constructs", - "default", - "deprecated", - "description", - "event", - "example", - "extends", - "field", - "fileOverview", - "function", - "ignore", - "inner", - "lends", - "link", - "memberOf", - "name", - "namespace", - "param", - "private", - "property", - "public", - "requires", - "returns", - "see", - "since", - "static", - "throws", - "type", - "typedef", - "property", - "prop", - "version" - ]; - var jsDocCompletionEntries; - function createNode(kind, pos, end, flags, parent) { - var node = new NodeObject(kind, pos, end); - node.flags = flags; + function createNode(kind, pos, end, parent) { + var node = kind >= 139 ? new NodeObject(kind, pos, end) : + kind === 69 ? new IdentifierObject(kind, pos, end) : + new TokenObject(kind, pos, end); node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { - this.kind = kind; this.pos = pos; this.end = end; this.flags = 0; + this.transformFlags = undefined; + this.excludeTransformFlags = undefined; this.parent = undefined; + this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -43893,22 +58984,25 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { - scanner.setTextPos(pos); + ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); - var textPos = scanner.getTextPos(); + var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, 0, this)); + nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282, nodes.pos, nodes.end, 0, this); + var list = createNode(286, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -43928,16 +59022,19 @@ var ts; var _this = this; var children; if (this.kind >= 139) { - scanner.setText((sourceFile || this.getSourceFile()).text); + ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 281; + var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 285; var processNode = function (node) { - if (pos_3 < node.pos) { + var isJSDocTagNode = ts.isJSDocTag(node); + if (!isJSDocTagNode && pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - pos_3 = node.end; + if (!isJSDocTagNode) { + pos_3 = node.end; + } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -43952,13 +59049,14 @@ var ts; processNode(jsDocComment); } } + pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { this.addSyntheticNodes(children, pos_3, this.end); } - scanner.setText(undefined); + ts.scanner.setText(undefined); } - this._children = children || emptyArray; + this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -43993,6 +59091,57 @@ var ts; }; return NodeObject; }()); + var TokenOrIdentifierObject = (function () { + function TokenOrIdentifierObject(pos, end) { + this.pos = pos; + this.end = end; + this.flags = 0; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + return ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + return undefined; + }; + return TokenOrIdentifierObject; + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -44009,259 +59158,28 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4)); } return this.documentationComment; }; return SymbolObject; }()); - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { - var documentationComment = []; - var docComments = getJsDocCommentsSeparatedByNewLines(); - ts.forEach(docComments, function (docComment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(docComment); - }); - return documentationComment; - function getJsDocCommentsSeparatedByNewLines() { - var paramTag = "@param"; - var jsDocCommentParts = []; - ts.forEach(declarations, function (declaration, indexOfDeclaration) { - if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); - if (canUseParsedParamTagComments && declaration.kind === 142) { - if ((declaration.parent.kind === 179 || declaration.parent.kind === 180) && - declaration.parent.parent.kind === 218) { - addCommentParts(declaration.parent.parent.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - if (declaration.kind === 225 && declaration.body && declaration.body.kind === 225) { - return; - } - if ((declaration.kind === 179 || declaration.kind === 180) && - declaration.parent.kind === 218) { - addCommentParts(declaration.parent.parent, sourceFileOfDeclaration, getCleanedJsDocComment); - } - while (declaration.kind === 225 && declaration.parent.kind === 225) { - declaration = declaration.parent; - } - addCommentParts(declaration.kind === 218 ? declaration.parent.parent : declaration, sourceFileOfDeclaration, getCleanedJsDocComment); - if (declaration.kind === 218) { - var init = declaration.initializer; - if (init && (init.kind === 179 || init.kind === 180)) { - addCommentParts(init, sourceFileOfDeclaration, getCleanedJsDocComment); - } - } - } - }); - return jsDocCommentParts; - function addCommentParts(commented, sourceFileOfDeclaration, getCommentPart) { - var ranges = getJsDocCommentTextRange(commented, sourceFileOfDeclaration); - ts.forEach(ranges, function (jsDocCommentTextRange) { - var cleanedComment = getCommentPart(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); - if (cleanedComment) { - ts.addRange(jsDocCommentParts, cleanedComment); - } - }); - } - function getJsDocCommentTextRange(node, sourceFile) { - return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { - return { - pos: jsDocComment.pos + "/*".length, - end: jsDocComment.end - "*/".length - }; - }); - } - function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { - if (maxSpacesToRemove !== undefined) { - end = Math.min(end, pos + maxSpacesToRemove); - } - for (; pos < end; pos++) { - var ch = sourceFile.text.charCodeAt(pos); - if (!ts.isWhiteSpaceSingleLine(ch)) { - return pos; - } - } - return end; - } - function consumeLineBreaks(pos, end, sourceFile) { - while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function isName(pos, end, sourceFile, name) { - return pos + name.length < end && - sourceFile.text.substr(pos, name.length) === name && - ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)); - } - function isParamTag(pos, end, sourceFile) { - return isName(pos, end, sourceFile, paramTag); - } - function pushDocCommentLineText(docComments, text, blankLineCount) { - while (blankLineCount) { - blankLineCount--; - docComments.push(ts.textPart("")); - } - docComments.push(ts.textPart(text)); - } - function getCleanedJsDocComment(pos, end, sourceFile) { - var spacesToRemoveAfterAsterisk; - var docComments = []; - var blankLineCount = 0; - var isInParamTag = false; - while (pos < end) { - var docCommentTextOfLine = ""; - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); - if (pos < end && sourceFile.text.charCodeAt(pos) === 42) { - var lineStartPos = pos + 1; - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); - if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - spacesToRemoveAfterAsterisk = pos - lineStartPos; - } - } - else if (spacesToRemoveAfterAsterisk === undefined) { - spacesToRemoveAfterAsterisk = 0; - } - while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - var ch = sourceFile.text.charAt(pos); - if (ch === "@") { - if (isParamTag(pos, end, sourceFile)) { - isInParamTag = true; - pos += paramTag.length; - continue; - } - else { - isInParamTag = false; - } - } - if (!isInParamTag) { - docCommentTextOfLine += ch; - } - pos++; - } - pos = consumeLineBreaks(pos, end, sourceFile); - if (docCommentTextOfLine) { - pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); - blankLineCount = 0; - } - else if (!isInParamTag && docComments.length) { - blankLineCount++; - } - } - return docComments; - } - function getCleanedParamJsDocComment(pos, end, sourceFile) { - var paramHelpStringMargin; - var paramDocComments = []; - while (pos < end) { - if (isParamTag(pos, end, sourceFile)) { - var blankLineCount = 0; - var recordedParamTag = false; - pos = consumeWhiteSpaces(pos + paramTag.length); - if (pos >= end) { - break; - } - if (sourceFile.text.charCodeAt(pos) === 123) { - pos++; - for (var curlies = 1; pos < end; pos++) { - var charCode = sourceFile.text.charCodeAt(pos); - if (charCode === 123) { - curlies++; - continue; - } - if (charCode === 125) { - curlies--; - if (curlies === 0) { - pos++; - break; - } - else { - continue; - } - } - if (charCode === 64) { - break; - } - } - pos = consumeWhiteSpaces(pos); - if (pos >= end) { - break; - } - } - if (isName(pos, end, sourceFile, name)) { - pos = consumeWhiteSpaces(pos + name.length); - if (pos >= end) { - break; - } - var paramHelpString = ""; - var firstLineParamHelpStringPos = pos; - while (pos < end) { - var ch = sourceFile.text.charCodeAt(pos); - if (ts.isLineBreak(ch)) { - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - paramHelpString = ""; - blankLineCount = 0; - recordedParamTag = true; - } - else if (recordedParamTag) { - blankLineCount++; - } - setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); - continue; - } - if (ch === 64) { - break; - } - paramHelpString += sourceFile.text.charAt(pos); - pos++; - } - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - } - paramHelpStringMargin = undefined; - } - if (sourceFile.text.charCodeAt(pos) === 64) { - continue; - } - } - pos++; - } - return paramDocComments; - function consumeWhiteSpaces(pos) { - while (pos < end && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { - pos = consumeLineBreaks(pos, end, sourceFile); - if (pos >= end) { - return; - } - if (paramHelpStringMargin === undefined) { - paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; - } - var startOfLinePos = pos; - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); - if (pos >= end) { - return; - } - var consumedSpaces = pos - startOfLinePos; - if (consumedSpaces < paramHelpStringMargin) { - var ch = sourceFile.text.charCodeAt(pos); - if (ch === 42) { - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); - } - } - } - } + var TokenObject = (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + _super.call(this, pos, end); + this.kind = kind; } - } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(kind, pos, end) { + _super.call(this, pos, end); + } + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 69; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -44295,7 +59213,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (1024 | 2048) + return this.flags & (32768 | 65536) ? this.checker.getBaseTypes(this) : undefined; }; @@ -44322,7 +59240,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? getJsDocCommentsFromDeclarations([this.declaration], undefined, false) : []; + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], undefined, false) : []; } return this.documentationComment; }; @@ -44352,24 +59270,23 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { var name = getDeclarationName(declaration); if (name) { - var declarations = getDeclarations(name); - declarations.push(declaration); + ts.multiMapAdd(result, name, declaration); } } function getDeclarations(name) { - return ts.getProperty(result, name) || (result[name] = []); + return result[name] || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_2 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_2 !== undefined) { - return result_2; + var result_6 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_6 !== undefined) { + return result_6; } if (declaration.name.kind === 140) { var expr = declaration.name.expression; @@ -44432,7 +59349,7 @@ var ts; ts.forEachChild(node, visit); break; case 142: - if (!(node.flags & 92)) { + if (!ts.hasModifier(node, 92)) { break; } case 218: @@ -44478,134 +59395,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); - var TextChange = (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; - var HighlightSpanKind; - (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; - })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); - (function (IndentStyle) { - IndentStyle[IndentStyle["None"] = 0] = "None"; - IndentStyle[IndentStyle["Block"] = 1] = "Block"; - IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; - (function (SymbolDisplayPartKind) { - SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; - SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; - SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; - SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; - SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; - SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; - SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; - (function (TokenClass) { - TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; - TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; - TokenClass[TokenClass["Operator"] = 2] = "Operator"; - TokenClass[TokenClass["Comment"] = 3] = "Comment"; - TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; - TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; - TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; - var ScriptElementKind; - (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; - ScriptElementKind.keyword = "keyword"; - ScriptElementKind.scriptElement = "script"; - ScriptElementKind.moduleElement = "module"; - ScriptElementKind.classElement = "class"; - ScriptElementKind.localClassElement = "local class"; - ScriptElementKind.interfaceElement = "interface"; - ScriptElementKind.typeElement = "type"; - ScriptElementKind.enumElement = "enum"; - ScriptElementKind.variableElement = "var"; - ScriptElementKind.localVariableElement = "local var"; - ScriptElementKind.functionElement = "function"; - ScriptElementKind.localFunctionElement = "local function"; - ScriptElementKind.memberFunctionElement = "method"; - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; - ScriptElementKind.memberVariableElement = "property"; - ScriptElementKind.constructorImplementationElement = "constructor"; - ScriptElementKind.callSignatureElement = "call"; - ScriptElementKind.indexSignatureElement = "index"; - ScriptElementKind.constructSignatureElement = "construct"; - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); - var ScriptElementKindModifier; - (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; - })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - return ClassificationTypeNames; - }()); - ts.ClassificationTypeNames = ClassificationTypeNames; + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; } + }; + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -44613,25 +59413,6 @@ var ts; return ""; } ts.displayPartsToString = displayPartsToString; - function isLocalVariableOrFunction(symbol) { - if (symbol.parent) { - return false; - } - return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 179) { - return true; - } - if (declaration.kind !== 218 && declaration.kind !== 220) { - return false; - } - for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { - if (parent_16.kind === 256 || parent_16.kind === 226) { - return false; - } - } - return true; - }); - } function getDefaultCompilerOptions() { return { target: 1, @@ -44736,97 +59517,6 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptionsStringToEnum; - function fixupCompilerOptions(options, diagnostics) { - commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { - return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); - }); - options = ts.clone(options); - var _loop_3 = function(opt) { - if (!ts.hasProperty(options, opt.name)) { - return "continue"; - } - var value = options[opt.name]; - if (typeof value === "string") { - options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); - } - else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { - diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); - } - } - }; - for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { - var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_3(opt); - } - return options; - } - function transpileModule(input, transpileOptions) { - var diagnostics = []; - var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : getDefaultCompilerOptions(); - options.isolatedModules = true; - options.suppressOutputPathCheck = true; - options.allowNonTsExtensions = true; - options.noLib = true; - options.lib = undefined; - options.types = undefined; - options.noEmit = undefined; - options.noEmitOnError = undefined; - options.paths = undefined; - options.rootDirs = undefined; - options.declaration = undefined; - options.declarationDir = undefined; - options.out = undefined; - options.outFile = undefined; - options.noResolve = true; - var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); - if (transpileOptions.moduleName) { - sourceFile.moduleName = transpileOptions.moduleName; - } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; - var newLine = ts.getNewLineCharacter(options); - var outputText; - var sourceMapText; - var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { - if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); - sourceMapText = text; - } - else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); - outputText = text; - } - }, - getDefaultLibFileName: function () { return "lib.d.ts"; }, - useCaseSensitiveFileNames: function () { return false; }, - getCanonicalFileName: function (fileName) { return fileName; }, - getCurrentDirectory: function () { return ""; }, - getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } - }; - var program = ts.createProgram([inputFileName], options, compilerHost); - if (transpileOptions.reportDiagnostics) { - ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); - ts.addRange(diagnostics, program.getOptionsDiagnostics()); - } - program.emit(); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); - return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; - } - ts.transpileModule = transpileModule; - function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { - var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); - ts.addRange(diagnostics, output.diagnostics); - return output.outputText; - } - ts.transpile = transpile; function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); @@ -44873,593 +59563,6 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - var buckets = {}; - var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = ts.lookUp(buckets, key); - if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(); - } - return bucket; - } - function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { - var entries = ts.lookUp(buckets, name); - var sourceFiles = []; - entries.forEachValue(function (key, entry) { - sourceFiles.push({ - name: key, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) - }); - }); - sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); - return { - bucket: name, - sourceFiles: sourceFiles - }; - }); - return JSON.stringify(bucketInfoArray, undefined, 2); - } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, true, scriptKind); - } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, false, scriptKind); - } - function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, true); - var entry = bucket.get(path); - if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); - var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); - entry = { - sourceFile: sourceFile, - languageServiceRefCount: 0, - owners: [] - }; - bucket.set(path, entry); - } - else { - if (entry.sourceFile.version !== version) { - entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); - } - } - if (acquiring) { - entry.languageServiceRefCount++; - } - return entry.sourceFile; - } - function releaseDocument(fileName, compilationSettings) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); - } - function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, false); - ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(path); - entry.languageServiceRefCount--; - ts.Debug.assert(entry.languageServiceRefCount >= 0); - if (entry.languageServiceRefCount === 0) { - bucket.remove(path); - } - } - return { - acquireDocument: acquireDocument, - acquireDocumentWithKey: acquireDocumentWithKey, - updateDocument: updateDocument, - updateDocumentWithKey: updateDocumentWithKey, - releaseDocument: releaseDocument, - releaseDocumentWithKey: releaseDocumentWithKey, - reportStats: reportStats, - getKeyForCompilationSettings: getKeyForCompilationSettings - }; - } - ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { - if (readImportFiles === void 0) { readImportFiles = true; } - if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; - var importedFiles = []; - var ambientExternalModules; - var isNoDefaultLib = false; - var braceNesting = 0; - var externalModule = false; - function nextToken() { - var token = scanner.scan(); - if (token === 15) { - braceNesting++; - } - else if (token === 16) { - braceNesting--; - } - return token; - } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } - function getFileReference() { - var file = scanner.getTokenValue(); - var pos = scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; - } - function recordAmbientExternalModule() { - if (!ambientExternalModules) { - ambientExternalModules = []; - } - ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); - } - function recordModuleName() { - importedFiles.push(getFileReference()); - markAsExternalModuleIfTopLevel(); - } - function markAsExternalModuleIfTopLevel() { - if (braceNesting === 0) { - externalModule = true; - } - } - function tryConsumeDeclare() { - var token = scanner.getToken(); - if (token === 122) { - token = nextToken(); - if (token === 125) { - token = nextToken(); - if (token === 9) { - recordAmbientExternalModule(); - } - } - return true; - } - return false; - } - function tryConsumeImport() { - var token = scanner.getToken(); - if (token === 89) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - return true; - } - else { - if (token === 69 || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - return true; - } - } - else if (token === 56) { - if (tryConsumeRequireCall(true)) { - return true; - } - } - else if (token === 24) { - token = nextToken(); - } - else { - return true; - } - } - if (token === 15) { - token = nextToken(); - while (token !== 16 && token !== 1) { - token = nextToken(); - } - if (token === 16) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - } - else if (token === 37) { - token = nextToken(); - if (token === 116) { - token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - } - } - } - return true; - } - return false; - } - function tryConsumeExport() { - var token = scanner.getToken(); - if (token === 82) { - markAsExternalModuleIfTopLevel(); - token = nextToken(); - if (token === 15) { - token = nextToken(); - while (token !== 16 && token !== 1) { - token = nextToken(); - } - if (token === 16) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - } - else if (token === 37) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - else if (token === 89) { - token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { - token = nextToken(); - if (token === 56) { - if (tryConsumeRequireCall(true)) { - return true; - } - } - } - } - return true; - } - return false; - } - function tryConsumeRequireCall(skipCurrentToken) { - var token = skipCurrentToken ? nextToken() : scanner.getToken(); - if (token === 129) { - token = nextToken(); - if (token === 17) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - return true; - } - return false; - } - function tryConsumeDefine() { - var token = scanner.getToken(); - if (token === 69 && scanner.getTokenValue() === "define") { - token = nextToken(); - if (token !== 17) { - return true; - } - token = nextToken(); - if (token === 9) { - token = nextToken(); - if (token === 24) { - token = nextToken(); - } - else { - return true; - } - } - if (token !== 19) { - return true; - } - token = nextToken(); - var i = 0; - while (token !== 20 && token !== 1) { - if (token === 9) { - recordModuleName(); - i++; - } - token = nextToken(); - } - return true; - } - return false; - } - function processImports() { - scanner.setText(sourceText); - nextToken(); - while (true) { - if (scanner.getToken() === 1) { - break; - } - if (tryConsumeDeclare() || - tryConsumeImport() || - tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(false) || tryConsumeDefine()))) { - continue; - } - else { - nextToken(); - } - } - scanner.setText(undefined); - } - if (readImportFiles) { - processImports(); - } - processTripleSlashDirectives(); - if (externalModule) { - if (ambientExternalModules) { - for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { - var decl = ambientExternalModules_1[_i]; - importedFiles.push(decl.ref); - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; - } - else { - var ambientModuleNames = void 0; - if (ambientExternalModules) { - for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { - var decl = ambientExternalModules_2[_a]; - if (decl.depth === 0) { - if (!ambientModuleNames) { - ambientModuleNames = []; - } - ambientModuleNames.push(decl.ref.fileName); - } - else { - importedFiles.push(decl.ref); - } - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; - } - } - ts.preProcessFile = preProcessFile; - function getTargetLabel(referenceNode, labelName) { - while (referenceNode) { - if (referenceNode.kind === 214 && referenceNode.label.text === labelName) { - return referenceNode.label; - } - referenceNode = referenceNode.parent; - } - return undefined; - } - function isJumpStatementTarget(node) { - return node.kind === 69 && - (node.parent.kind === 210 || node.parent.kind === 209) && - node.parent.label === node; - } - function isLabelOfLabeledStatement(node) { - return node.kind === 69 && - node.parent.kind === 214 && - node.parent.label === node; - } - function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214; owner = owner.parent) { - if (owner.label.text === labelName) { - return true; - } - } - return false; - } - function isLabelName(node) { - return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); - } - function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 && node.parent.right === node; - } - function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 && node.parent.name === node; - } - function isCallExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 174 && node.parent.expression === node; - } - function isNewExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 175 && node.parent.expression === node; - } - function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 && node.parent.name === node; - } - function isNameOfFunctionDeclaration(node) { - return node.kind === 69 && - ts.isFunctionLike(node.parent) && node.parent.name === node; - } - function isObjectLiteralPropertyDeclaration(node) { - switch (node.kind) { - case 253: - case 254: - case 147: - case 149: - case 150: - return true; - } - return false; - } - function getContainingObjectLiteralElement(node) { - switch (node.kind) { - case 9: - case 8: - if (node.parent.kind === 140) { - return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; - } - case 69: - return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; - } - return undefined; - } - function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 || node.kind === 8) { - switch (node.parent.kind) { - case 145: - case 144: - case 253: - case 255: - case 147: - case 146: - case 149: - case 150: - case 225: - return node.parent.name === node; - case 173: - return node.parent.argumentExpression === node; - case 140: - return true; - } - } - return false; - } - function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9) { - return isNameOfModuleDeclaration(node) || - (ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node); - } - return false; - } - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - var keywordCompletions = []; - for (var i = 70; i <= 138; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - sortText: "0" - }); - } - function getContainerNode(node) { - while (true) { - node = node.parent; - if (!node) { - return undefined; - } - switch (node.kind) { - case 256: - case 147: - case 146: - case 220: - case 179: - case 149: - case 150: - case 221: - case 222: - case 224: - case 225: - return node; - } - } - } - ts.getContainerNode = getContainerNode; - function getNodeKind(node) { - switch (node.kind) { - case 225: return ScriptElementKind.moduleElement; - case 221: - case 192: - return ScriptElementKind.classElement; - case 222: return ScriptElementKind.interfaceElement; - case 223: return ScriptElementKind.typeElement; - case 224: return ScriptElementKind.enumElement; - case 218: - return ts.isConst(node) - ? ScriptElementKind.constElement - : ts.isLet(node) - ? ScriptElementKind.letElement - : ScriptElementKind.variableElement; - case 220: - case 179: - return ScriptElementKind.functionElement; - case 149: return ScriptElementKind.memberGetAccessorElement; - case 150: return ScriptElementKind.memberSetAccessorElement; - case 147: - case 146: - return ScriptElementKind.memberFunctionElement; - case 145: - case 144: - return ScriptElementKind.memberVariableElement; - case 153: return ScriptElementKind.indexSignatureElement; - case 152: return ScriptElementKind.constructSignatureElement; - case 151: return ScriptElementKind.callSignatureElement; - case 148: return ScriptElementKind.constructorImplementationElement; - case 141: return ScriptElementKind.typeParameterElement; - case 255: return ScriptElementKind.variableElement; - case 142: return (node.flags & 92) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 229: - case 234: - case 231: - case 238: - case 232: - return ScriptElementKind.alias; - } - return ScriptElementKind.unknown; - } - ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { function CancellationTokenObject(cancellationToken) { this.cancellationToken = cancellationToken; @@ -45475,7 +59578,7 @@ var ts; return CancellationTokenObject; }()); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; @@ -45522,14 +59625,16 @@ var ts; } var oldSettings = program && program.getCompilerOptions(); var newSettings = hostCache.compilationSettings(); - var changesInCompilationSettingsAffectSyntax = oldSettings && + var shouldCreateNewSourceFiles = oldSettings && (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.baseUrl !== newSettings.baseUrl || + !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, @@ -45541,7 +59646,6 @@ var ts; writeFile: function (fileName, data, writeByteOrderMark) { }, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return hostCache.getOrCreateEntry(fileName) !== undefined; }, readFile: function (fileName) { @@ -45573,7 +59677,7 @@ var ts; var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } } @@ -45591,7 +59695,7 @@ var ts; if (!hostFileInformation) { return undefined; } - if (!changesInCompilationSettingsAffectSyntax) { + if (!shouldCreateNewSourceFiles) { var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); @@ -45655,1240 +59759,17 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - if ((symbol.flags & 1536) && (firstCharCode === 39 || firstCharCode === 34)) { - return undefined; - } - } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); - } - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { - return undefined; - } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } - if (performCharacterChecks) { - if (!ts.isIdentifier(name, target)) { - return undefined; - } - } - return name; - } - function getCompletionData(fileName, position) { - var typeChecker = program.getTypeChecker(); - var sourceFile = getValidSourceFile(fileName); - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - var isJsDocTagName = false; - var start = new Date().getTime(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); - var insideComment = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); - if (insideComment) { - if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64) { - isJsDocTagName = true; - } - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); - if (tag) { - if (tag.tagName.pos <= position && position <= tag.tagName.end) { - isJsDocTagName = true; - } - switch (tag.kind) { - case 277: - case 275: - case 276: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; - } - } - if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; - } - if (!insideJsDocTagExpression) { - log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); - return undefined; - } - } - start = new Date().getTime(); - var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); - var contextToken = previousToken; - if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_5 = new Date().getTime(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); - } - var node = currentToken; - var isRightOfDot = false; - var isRightOfOpenTag = false; - var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); - if (contextToken) { - if (isCompletionListBlocker(contextToken)) { - log("Returning an empty list because completion was requested in an invalid position."); - return undefined; - } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21) { - if (parent_17.kind === 172) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent_17.kind === 139) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - return undefined; - } - } - else if (sourceFile.languageVariant === 1) { - if (kind === 25) { - isRightOfOpenTag = true; - location = contextToken; - } - else if (kind === 39 && contextToken.parent.kind === 245) { - isStartingCloseTag = true; - location = contextToken; - } - } - } - var semanticStart = new Date().getTime(); - var isMemberCompletion; - var isNewIdentifierLocation; - var symbols = []; - if (isRightOfDot) { - getTypeScriptMemberSymbols(); - } - else if (isRightOfOpenTag) { - var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); - if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 8388608)); })); - } - else { - symbols = tagSymbols; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else if (isStartingCloseTag) { - var tagName = contextToken.parent.parent.openingElement.tagName; - var tagSymbol = typeChecker.getSymbolAtLocation(tagName); - if (!typeChecker.isUnknownSymbol(tagSymbol)) { - symbols = [tagSymbol]; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else { - if (!tryGetGlobalSymbols()) { - return undefined; - } - } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; - function getTypeScriptMemberSymbols() { - isMemberCompletion = true; - isNewIdentifierLocation = false; - if (node.kind === 69 || node.kind === 139 || node.kind === 172) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol && symbol.flags & 8388608) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - }); - } - } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); - } - function addTypeProperties(type) { - if (type) { - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - } - if (isJavaScriptFile && type.flags & 16384) { - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } - } - } - } - function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - return tryGetObjectLikeCompletionSymbols(objectLikeContainer); - } - if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { - return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); - } - if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType = void 0; - if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { - attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); - if (attrsType) { - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); - isMemberCompletion = true; - isNewIdentifierLocation = false; - return true; - } - } - } - isMemberCompletion = false; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); - if (previousToken !== contextToken) { - ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); - } - var adjustedPosition = previousToken !== contextToken ? - previousToken.getStart() : - position; - var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - var symbolMeanings = 793056 | 107455 | 1536 | 8388608; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); - return true; - } - function getScopeNode(initialToken, position, sourceFile) { - var scope = initialToken; - while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { - scope = scope.parent; - } - return scope; - } - function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); - var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || - isSolelyIdentifierDefinitionLocation(contextToken) || - isDotOfNumericLiteral(contextToken) || - isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); - return result; - } - function isInJsxText(contextToken) { - if (contextToken.kind === 244) { - return true; - } - if (contextToken.kind === 27 && contextToken.parent) { - if (contextToken.parent.kind === 243) { - return true; - } - if (contextToken.parent.kind === 245 || contextToken.parent.kind === 242) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241; - } - } - return false; - } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { - case 24: - return containingNodeKind === 174 - || containingNodeKind === 148 - || containingNodeKind === 175 - || containingNodeKind === 170 - || containingNodeKind === 187 - || containingNodeKind === 156; - case 17: - return containingNodeKind === 174 - || containingNodeKind === 148 - || containingNodeKind === 175 - || containingNodeKind === 178 - || containingNodeKind === 164; - case 19: - return containingNodeKind === 170 - || containingNodeKind === 153 - || containingNodeKind === 140; - case 125: - case 126: - return true; - case 21: - return containingNodeKind === 225; - case 15: - return containingNodeKind === 221; - case 56: - return containingNodeKind === 218 - || containingNodeKind === 187; - case 12: - return containingNodeKind === 189; - case 13: - return containingNodeKind === 197; - case 112: - case 110: - case 111: - return containingNodeKind === 145; - } - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": - return true; - } - } - return false; - } - function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { - if (contextToken.kind === 9 - || contextToken.kind === 166 - || contextToken.kind === 10 - || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_6 = contextToken.getStart(); - var end = contextToken.getEnd(); - if (start_6 < position && position < end) { - return true; - } - if (position === end) { - return !!contextToken.isUnterminated - || contextToken.kind === 10; - } - } - return false; - } - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { - isMemberCompletion = true; - var typeForObject; - var existingMembers; - if (objectLikeContainer.kind === 171) { - isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - existingMembers = objectLikeContainer.properties; - } - else if (objectLikeContainer.kind === 167) { - isNewIdentifierLocation = false; - var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 147 || rootDeclaration.parent.kind === 150) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } - } - if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - existingMembers = objectLikeContainer.elements; - } - } - else { - ts.Debug.fail("Root declaration is not variable-like."); - } - } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); - if (typeMembers && typeMembers.length > 0) { - symbols = filterObjectMembersList(typeMembers, existingMembers); - } - return true; - } - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 ? - 230 : - 236; - var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); - var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; - if (!moduleSpecifier) { - return false; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - var exports; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); - if (moduleSpecifierSymbol) { - exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); - } - symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; - return true; - } - function tryGetObjectLikeCompletionContainer(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15: - case 24: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 || parent_18.kind === 167)) { - return parent_18; - } - break; - } - } - return undefined; - } - function tryGetNamedImportsOrExportsForCompletion(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15: - case 24: - switch (contextToken.parent.kind) { - case 233: - case 237: - return contextToken.parent; - } - } - } - return undefined; - } - function tryGetContainingJsxElement(contextToken) { - if (contextToken) { - var parent_19 = contextToken.parent; - switch (contextToken.kind) { - case 26: - case 39: - case 69: - case 246: - case 247: - if (parent_19 && (parent_19.kind === 242 || parent_19.kind === 243)) { - return parent_19; - } - else if (parent_19.kind === 246) { - return parent_19.parent; - } - break; - case 9: - if (parent_19 && ((parent_19.kind === 246) || (parent_19.kind === 247))) { - return parent_19.parent; - } - break; - case 16: - if (parent_19 && - parent_19.kind === 248 && - parent_19.parent && - (parent_19.parent.kind === 246)) { - return parent_19.parent.parent; - } - if (parent_19 && parent_19.kind === 247) { - return parent_19.parent; - } - break; - } - } - return undefined; - } - function isFunction(kind) { - switch (kind) { - case 179: - case 180: - case 220: - case 147: - case 146: - case 149: - case 150: - case 151: - case 152: - case 153: - return true; - } - return false; - } - function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; - switch (contextToken.kind) { - case 24: - return containingNodeKind === 218 || - containingNodeKind === 219 || - containingNodeKind === 200 || - containingNodeKind === 224 || - isFunction(containingNodeKind) || - containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 168 || - containingNodeKind === 223; - case 21: - return containingNodeKind === 168; - case 54: - return containingNodeKind === 169; - case 19: - return containingNodeKind === 168; - case 17: - return containingNodeKind === 252 || - isFunction(containingNodeKind); - case 15: - return containingNodeKind === 224 || - containingNodeKind === 222 || - containingNodeKind === 159; - case 23: - return containingNodeKind === 144 && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 || - contextToken.parent.parent.kind === 159); - case 25: - return containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 223 || - isFunction(containingNodeKind); - case 113: - return containingNodeKind === 145; - case 22: - return containingNodeKind === 142 || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168); - case 112: - case 110: - case 111: - return containingNodeKind === 142; - case 116: - return containingNodeKind === 234 || - containingNodeKind === 238 || - containingNodeKind === 232; - case 73: - case 81: - case 107: - case 87: - case 102: - case 123: - case 131: - case 89: - case 108: - case 74: - case 114: - case 134: - return true; - } - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": - return true; - } - return false; - } - function isDotOfNumericLiteral(contextToken) { - if (contextToken.kind === 8) { - var text = contextToken.getFullText(); - return text.charAt(text.length - 1) === "."; - } - return false; - } - function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; - for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { - var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { - continue; - } - var name_41 = element.propertyName || element.name; - existingImportsOrExports[name_41.text] = true; - } - if (ts.isEmpty(existingImportsOrExports)) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); - } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !ts.lookUp(existingImportsOrExports, e.name); }); - } - function filterObjectMembersList(contextualMemberSymbols, existingMembers) { - if (!existingMembers || existingMembers.length === 0) { - return contextualMemberSymbols; - } - var existingMemberNames = {}; - for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { - var m = existingMembers_1[_i]; - if (m.kind !== 253 && - m.kind !== 254 && - m.kind !== 169 && - m.kind !== 147) { - continue; - } - if (m.getStart() <= position && position <= m.getEnd()) { - continue; - } - var existingName = void 0; - if (m.kind === 169 && m.propertyName) { - if (m.propertyName.kind === 69) { - existingName = m.propertyName.text; - } - } - else { - existingName = m.name.text; - } - existingMemberNames[existingName] = true; - } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); - } - function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; - for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { - var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { - continue; - } - if (attr.kind === 246) { - seenNames[attr.name.text] = true; - } - } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); - } - } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position); - } - var completionData = getCompletionData(fileName, position); - if (!completionData) { - return undefined; - } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; - if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; - } - var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); - } - else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 && - location.parent && location.parent.kind === 245) { - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0" - }); - } - else { - return undefined; - } - } - getCompletionEntriesFromSymbols(symbols, entries, location, true); - } - if (!isMemberCompletion && !isJsDocTagName) { - ts.addRange(entries, keywordCompletions); - } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { - var entries = []; - var target = program.getCompilerOptions().target; - var nameTable = getNameTable(sourceFile); - for (var name_42 in nameTable) { - if (nameTable[name_42] === position) { - continue; - } - if (!uniqueNames[name_42]) { - uniqueNames[name_42] = name_42; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, true); - if (displayName) { - var entry = { - name: displayName, - kind: ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } - } - } - return entries; - } - function getAllJsDocCompletionEntries() { - return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { - return { - name: tagName, - kind: ScriptElementKind.keyword, - kindModifiers: "", - sortText: "0" - }; - })); - } - function createCompletionEntry(symbol, location, performCharacterChecks) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, performCharacterChecks, location); - if (!displayName) { - return undefined; - } - return { - name: displayName, - kind: getSymbolKind(symbol, location), - kindModifiers: getSymbolModifiers(symbol), - sortText: "0" - }; - } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; - if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks); - if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(uniqueNames, id)) { - entries.push(entry); - uniqueNames[id] = id; - } - } - } - } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return uniqueNames; - } - function getStringLiteralCompletionEntries(sourceFile, position) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9) { - return undefined; - } - var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - return getStringLiteralCompletionEntriesFromElementAccess(node.parent); - } - else { - return getStringLiteralCompletionEntriesFromContextualType(node); - } - } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { - var typeChecker = program.getTypeChecker(); - var candidates = []; - var entries = []; - typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); - for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { - var candidate = candidates_3[_i]; - if (candidate.parameters.length > argumentInfo.argumentIndex) { - var parameter = candidate.parameters[argumentInfo.argumentIndex]; - addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); - } - } - if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; - } - return undefined; - } - function getStringLiteralCompletionEntriesFromElementAccess(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getTypeAtLocation(node.expression); - var entries = []; - if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); - if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; - } - } - return undefined; - } - function getStringLiteralCompletionEntriesFromContextualType(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getContextualType(node); - if (type) { - var entries_2 = []; - addStringLiteralCompletionsFromType(type, entries_2); - if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; - } - } - return undefined; - } - function addStringLiteralCompletionsFromType(type, result) { - if (!type) { - return; - } - if (type.flags & 16384) { - ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); - } - else { - if (type.flags & 256) { - result.push({ - name: type.text, - kindModifiers: ScriptElementKindModifier.none, - kind: ScriptElementKind.variableElement, - sortText: "0" - }); - } - } - } + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); - var completionData = getCompletionData(fileName, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - var target_2 = program.getCompilerOptions().target; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, false, location_2) === entryName ? s : undefined; }); - if (symbol) { - var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; - return { - name: entryName, - kindModifiers: getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation - }; - } - } - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - displayParts: [ts.displayPart(entryName, SymbolDisplayPartKind.keyword)], - documentation: undefined - }; - } - return undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } - function getSymbolKind(symbol, location) { - var flags = symbol.getFlags(); - if (flags & 32) - return ts.getDeclarationOfKind(symbol, 192) ? - ScriptElementKind.localClassElement : ScriptElementKind.classElement; - if (flags & 384) - return ScriptElementKind.enumElement; - if (flags & 524288) - return ScriptElementKind.typeElement; - if (flags & 64) - return ScriptElementKind.interfaceElement; - if (flags & 262144) - return ScriptElementKind.typeParameterElement; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location); - if (result === ScriptElementKind.unknown) { - if (flags & 262144) - return ScriptElementKind.typeParameterElement; - if (flags & 8) - return ScriptElementKind.variableElement; - if (flags & 8388608) - return ScriptElementKind.alias; - if (flags & 1536) - return ScriptElementKind.moduleElement; - } - return result; - } - function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location) { - var typeChecker = program.getTypeChecker(); - if (typeChecker.isUndefinedSymbol(symbol)) { - return ScriptElementKind.variableElement; - } - if (typeChecker.isArgumentsSymbol(symbol)) { - return ScriptElementKind.localVariableElement; - } - if (location.kind === 97 && ts.isExpression(location)) { - return ScriptElementKind.parameterElement; - } - if (flags & 3) { - if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ScriptElementKind.parameterElement; - } - else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ScriptElementKind.constElement; - } - else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ScriptElementKind.letElement; - } - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement; - } - if (flags & 16) - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localFunctionElement : ScriptElementKind.functionElement; - if (flags & 32768) - return ScriptElementKind.memberGetAccessorElement; - if (flags & 65536) - return ScriptElementKind.memberSetAccessorElement; - if (flags & 8192) - return ScriptElementKind.memberFunctionElement; - if (flags & 16384) - return ScriptElementKind.constructorImplementationElement; - if (flags & 4) { - if (flags & 268435456) { - var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - var rootSymbolFlags = rootSymbol.getFlags(); - if (rootSymbolFlags & (98308 | 3)) { - return ScriptElementKind.memberVariableElement; - } - ts.Debug.assert(!!(rootSymbolFlags & 8192)); - }); - if (!unionPropertyKind) { - var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (typeOfUnionProperty.getCallSignatures().length) { - return ScriptElementKind.memberFunctionElement; - } - return ScriptElementKind.memberVariableElement; - } - return unionPropertyKind; - } - return ScriptElementKind.memberVariableElement; - } - return ScriptElementKind.unknown; - } - function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 - ? ts.getNodeModifiers(symbol.declarations[0]) - : ScriptElementKindModifier.none; - } - function getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { - if (semanticMeaning === void 0) { semanticMeaning = getMeaningFromLocation(location); } - var typeChecker = program.getTypeChecker(); - var displayParts = []; - var documentation; - var symbolFlags = symbol.flags; - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, location); - var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 && ts.isExpression(location); - var type; - if (symbolKind !== ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { - if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { - symbolKind = ScriptElementKind.memberVariableElement; - } - var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (type) { - if (location.parent && location.parent.kind === 172) { - var right = location.parent.name; - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; - } - } - var callExpression = void 0; - if (location.kind === 174 || location.kind === 175) { - callExpression = location; - } - else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { - callExpression = location.parent; - } - if (callExpression) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); - if (!signature && candidateSignatures.length) { - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpression.kind === 175 || callExpression.expression.kind === 95; - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32)) { - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else if (symbolFlags & 8388608) { - symbolKind = ScriptElementKind.alias; - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); - displayParts.push(ts.spacePart()); - } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case ScriptElementKind.memberVariableElement: - case ScriptElementKind.variableElement: - case ScriptElementKind.constElement: - case ScriptElementKind.letElement: - case ScriptElementKind.parameterElement: - case ScriptElementKind.localVariableElement: - displayParts.push(ts.punctuationPart(54)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 65536) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); - } - addSignatureDisplayParts(signature, allSignatures, 8); - break; - default: - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; - } - } - else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || - (location.kind === 121 && location.parent.kind === 148)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); - } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 148) { - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; - } - } - } - if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192)) { - pushTypePart(ScriptElementKind.localClassElement); - } - else { - displayParts.push(ts.keywordPart(73)); - } - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if ((symbolFlags & 64) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if (symbolFlags & 524288) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); - } - if (symbolFlags & 384) { - addNewLineIfDisplayPartsExist(); - if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74)); - displayParts.push(ts.spacePart()); - } - displayParts.push(ts.keywordPart(81)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if (symbolFlags & 1536) { - addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69; - displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if ((symbolFlags & 262144) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(18)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90)); - displayParts.push(ts.spacePart()); - if (symbol.parent) { - addFullSymbolName(symbol.parent, enclosingDeclaration); - writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); - } - else { - var declaration = ts.getDeclarationOfKind(symbol, 141); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; - if (declaration) { - if (ts.isFunctionLikeKind(declaration.kind)) { - var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152) { - displayParts.push(ts.keywordPart(92)); - displayParts.push(ts.spacePart()); - } - else if (declaration.kind !== 151 && declaration.name) { - addFullSymbolName(declaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); - } - else { - displayParts.push(ts.keywordPart(134)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); - } - } - } - } - if (symbolFlags & 8) { - addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 255) { - var constantValue = typeChecker.getConstantValue(declaration); - if (constantValue !== undefined) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral)); - } - } - } - if (symbolFlags & 8388608) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229) { - var importEqualsDeclaration = declaration; - if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129)); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(18)); - } - else { - var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); - if (internalAliasSymbol) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - addFullSymbolName(internalAliasSymbol, enclosingDeclaration); - } - } - return true; - } - }); - } - if (!hasAddedSymbolInfo) { - if (symbolKind !== ScriptElementKind.unknown) { - if (type) { - if (isThisExpression) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97)); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - if (symbolKind === ScriptElementKind.memberVariableElement || - symbolFlags & 3 || - symbolKind === ScriptElementKind.localVariableElement || - isThisExpression) { - displayParts.push(ts.punctuationPart(54)); - displayParts.push(ts.spacePart()); - if (type.symbol && type.symbol.flags & 262144) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } - else { - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); - } - } - else if (symbolFlags & 16 || - symbolFlags & 8192 || - symbolFlags & 16384 || - symbolFlags & 131072 || - symbolFlags & 98304 || - symbolKind === ScriptElementKind.memberFunctionElement) { - var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); - } - } - } - else { - symbolKind = getSymbolKind(symbol, location); - } - } - if (!documentation) { - documentation = symbol.getDocumentationComment(); - } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; - function addNewLineIfDisplayPartsExist() { - if (displayParts.length) { - displayParts.push(ts.lineBreakPart()); - } - } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); - ts.addRange(displayParts, fullSymbolDisplayParts); - } - function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); - if (symbolKind) { - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - } - function pushTypePart(symbolKind) { - switch (symbolKind) { - case ScriptElementKind.variableElement: - case ScriptElementKind.functionElement: - case ScriptElementKind.letElement: - case ScriptElementKind.constElement: - case ScriptElementKind.constructorImplementationElement: - displayParts.push(ts.textOrKeywordPart(symbolKind)); - return; - default: - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(18)); - return; - } - } - function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); - if (allSignatures.length > 1) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.operatorPart(35)); - displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), SymbolDisplayPartKind.numericLiteral)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18)); - } - documentation = signature.getDocumentationComment(); - } - function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } + function getCompletionEntrySymbol(fileName, position, entryName) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -46897,7 +59778,7 @@ var ts; if (node === sourceFile) { return undefined; } - if (isLabelName(node)) { + if (ts.isLabelName(node)) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -46913,200 +59794,42 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ScriptElementKind.unknown, - kindModifiers: ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.unknown, + kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: ts.typeToDisplayParts(typeChecker, type, getContainerNode(node)), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined }; } } return undefined; } - var displayPartsDocumentationsAndKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, getContainerNode(node), node); + var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); return { kind: displayPartsDocumentationsAndKind.symbolKind, - kindModifiers: getSymbolModifiers(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, documentation: displayPartsDocumentationsAndKind.documentation }; } - function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), - kind: symbolKind, - name: symbolName, - containerKind: undefined, - containerName: containerName - }; - } - function getDefinitionFromSymbol(symbol, node) { - var typeChecker = program.getTypeChecker(); - var result = []; - var declarations = symbol.getDeclarations(); - var symbolName = typeChecker.symbolToString(symbol); - var symbolKind = getSymbolKind(symbol, node); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isNewExpressionTarget(location) || location.kind === 121) { - if (symbol.flags & 32) { - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } - } - return false; - } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); - } - return false; - } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { - var declarations = []; - var definition; - ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148) || - (!selectConstructors && (d.kind === 220 || d.kind === 147 || d.kind === 146))) { - declarations.push(d); - if (d.body) - definition = d; - } - }); - if (definition) { - result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); - return true; - } - else if (declarations.length) { - result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; - } - } - function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { - return ref; - } - } - return undefined; - } - function getDefinitionInfoForFileReference(name, targetFileName) { - return { - fileName: targetFileName, - textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ScriptElementKind.scriptElement, - name: name, - containerName: undefined, - containerKind: undefined - }; - } function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - return undefined; - } - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); - if (referenceFile && referenceFile.resolvedFileName) { - return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; - } - return undefined; - } - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - if (isJumpStatementTarget(node)) { - var labelName = node.text; - var label = getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, undefined)] : undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 69 && - (node.parent === declaration || - (declaration.kind === 234 && declaration.parent && declaration.parent.kind === 233))) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - } - if (node.parent.kind === 254) { - var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - if (!shorthandSymbol) { - return []; - } - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); - var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); - } - return getDefinitionFromSymbol(symbol, node); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToImplementation.getImplementationAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { - return undefined; - } - if (type.flags & 16384) { - var result_3 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(result_3, getDefinitionFromSymbol(t.symbol, node)); - } - }); - return result_3; - } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(type.symbol, node); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -47114,492 +59837,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingWord(sourceFile, position); - if (!node) { - return undefined; - } - return getSemanticDocumentHighlights(node) || getSyntacticDocumentHighlights(node); - function getHighlightSpanForNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - return { - fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: HighlightSpanKind.none - }; - } - function getSemanticDocumentHighlights(node) { - if (node.kind === 69 || - node.kind === 97 || - node.kind === 165 || - node.kind === 95 || - node.kind === 9 || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, false, false); - return convertReferencedSymbols(referencedSymbols); - } - return undefined; - function convertReferencedSymbols(referencedSymbols) { - if (!referencedSymbols) { - return undefined; - } - var fileNameToDocumentHighlights = {}; - var result = []; - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var referencedSymbol = referencedSymbols_1[_i]; - for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { - var referenceEntry = _b[_a]; - var fileName_1 = referenceEntry.fileName; - var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); - if (!documentHighlights) { - documentHighlights = { fileName: fileName_1, highlightSpans: [] }; - fileNameToDocumentHighlights[fileName_1] = documentHighlights; - result.push(documentHighlights); - } - documentHighlights.highlightSpans.push({ - textSpan: referenceEntry.textSpan, - kind: referenceEntry.isWriteAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference - }); - } - } - return result; - } - } - function getSyntacticDocumentHighlights(node) { - var fileName = sourceFile.fileName; - var highlightSpans = getHighlightSpans(node); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: fileName, highlightSpans: highlightSpans }]; - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - function parent(node) { - return node && node.parent; - } - function getHighlightSpans(node) { - if (node) { - switch (node.kind) { - case 88: - case 80: - if (hasKind(node.parent, 203)) { - return getIfElseOccurrences(node.parent); - } - break; - case 94: - if (hasKind(node.parent, 211)) { - return getReturnOccurrences(node.parent); - } - break; - case 98: - if (hasKind(node.parent, 215)) { - return getThrowOccurrences(node.parent); - } - break; - case 72: - if (hasKind(parent(parent(node)), 216)) { - return getTryCatchFinallyOccurrences(node.parent.parent); - } - break; - case 100: - case 85: - if (hasKind(parent(node), 216)) { - return getTryCatchFinallyOccurrences(node.parent); - } - break; - case 96: - if (hasKind(node.parent, 213)) { - return getSwitchCaseDefaultOccurrences(node.parent); - } - break; - case 71: - case 77: - if (hasKind(parent(parent(parent(node))), 213)) { - return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); - } - break; - case 70: - case 75: - if (hasKind(node.parent, 210) || hasKind(node.parent, 209)) { - return getBreakOrContinueStatementOccurrences(node.parent); - } - break; - case 86: - if (hasKind(node.parent, 206) || - hasKind(node.parent, 207) || - hasKind(node.parent, 208)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 104: - case 79: - if (hasKind(node.parent, 205) || hasKind(node.parent, 204)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 121: - if (hasKind(node.parent, 148)) { - return getConstructorOccurrences(node.parent); - } - break; - case 123: - case 131: - if (hasKind(node.parent, 149) || hasKind(node.parent, 150)) { - return getGetAndSetOccurrences(node.parent); - } - break; - default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 200)) { - return getModifierOccurrences(node.kind, node.parent); - } - } - } - return undefined; - } - function aggregateOwnedThrowStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 215) { - statementAccumulator.push(node); - } - else if (node.kind === 216) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); - } - else { - aggregate(tryStatement.tryBlock); - } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); - } - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - function getThrowStatementOwner(throwStatement) { - var child = throwStatement; - while (child.parent) { - var parent_20 = child.parent; - if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256) { - return parent_20; - } - if (parent_20.kind === 216) { - var tryStatement = parent_20; - if (tryStatement.tryBlock === child && tryStatement.catchClause) { - return child; - } - } - child = parent_20; - } - return undefined; - } - function aggregateAllBreakAndContinueStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 210 || node.kind === 209) { - statementAccumulator.push(node); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - function ownsBreakOrContinueStatement(owner, statement) { - var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; - } - function getBreakOrContinueOwner(statement) { - for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) { - switch (node_1.kind) { - case 213: - if (statement.kind === 209) { - continue; - } - case 206: - case 207: - case 208: - case 205: - case 204: - if (!statement.label || isLabeledBy(node_1, statement.label.text)) { - return node_1; - } - break; - default: - if (ts.isFunctionLike(node_1)) { - return undefined; - } - break; - } - } - return undefined; - } - function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 221 || - container.kind === 192 || - (declaration.kind === 142 && hasKind(container, 148)))) { - return undefined; - } - } - else if (modifier === 113) { - if (!(container.kind === 221 || container.kind === 192)) { - return undefined; - } - } - else if (modifier === 82 || modifier === 122) { - if (!(container.kind === 226 || container.kind === 256)) { - return undefined; - } - } - else if (modifier === 115) { - if (!(container.kind === 221 || declaration.kind === 221)) { - return undefined; - } - } - else { - return undefined; - } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; - switch (container.kind) { - case 226: - case 256: - if (modifierFlag & 128) { - nodes = declaration.members.concat(declaration); - } - else { - nodes = container.statements; - } - break; - case 148: - nodes = container.parameters.concat(container.parent.members); - break; - case 221: - case 192: - nodes = container.members; - if (modifierFlag & 28) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 148 && member; - }); - if (constructor) { - nodes = nodes.concat(constructor.parameters); - } - } - else if (modifierFlag & 128) { - nodes = nodes.concat(container); - } - break; - default: - ts.Debug.fail("Invalid container kind."); - } - ts.forEach(nodes, function (node) { - if (node.modifiers && node.flags & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - function getFlagFromModifier(modifier) { - switch (modifier) { - case 112: - return 4; - case 110: - return 8; - case 111: - return 16; - case 113: - return 32; - case 82: - return 1; - case 122: - return 2; - case 115: - return 128; - default: - ts.Debug.fail(); - } - } - } - function pushKeywordIf(keywordList, token) { - var expected = []; - for (var _i = 2; _i < arguments.length; _i++) { - expected[_i - 2] = arguments[_i]; - } - if (token && ts.contains(expected, token.kind)) { - keywordList.push(token); - return true; - } - return false; - } - function getGetAndSetOccurrences(accessorDeclaration) { - var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 149); - tryPushAccessorKeyword(accessorDeclaration.symbol, 150); - return ts.map(keywords, getHighlightSpanForNode); - function tryPushAccessorKeyword(accessorSymbol, accessorKind) { - var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); - if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123, 131); }); - } - } - } - function getConstructorOccurrences(constructorDeclaration) { - var declarations = constructorDeclaration.symbol.getDeclarations(); - var keywords = []; - ts.forEach(declarations, function (declaration) { - ts.forEach(declaration.getChildren(), function (token) { - return pushKeywordIf(keywords, token, 121); - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getLoopBreakContinueOccurrences(loopNode) { - var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86, 104, 79)) { - if (loopNode.kind === 204) { - var loopTokens = loopNode.getChildren(); - for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104)) { - break; - } - } - } - } - var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70, 75); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { - var owner = getBreakOrContinueOwner(breakOrContinueStatement); - if (owner) { - switch (owner.kind) { - case 206: - case 207: - case 208: - case 204: - case 205: - return getLoopBreakContinueOccurrences(owner); - case 213: - return getSwitchCaseDefaultOccurrences(owner); - } - } - return undefined; - } - function getSwitchCaseDefaultOccurrences(switchStatement) { - var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96); - ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71, 77); - var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70); - } - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getTryCatchFinallyOccurrences(tryStatement) { - var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100); - if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72); - } - if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getThrowOccurrences(throwStatement) { - var owner = getThrowStatementOwner(throwStatement); - if (!owner) { - return undefined; - } - var keywords = []; - ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); - }); - if (ts.isFunctionBlock(owner)) { - ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); - }); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getReturnOccurrences(returnStatement) { - var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 199))) { - return undefined; - } - var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); - }); - ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getIfElseOccurrences(ifStatement) { - var keywords = []; - while (hasKind(ifStatement.parent, 203) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88); - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 203)) { - break; - } - ifStatement = ifStatement.elseStatement; - } - var result = []; - for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 && i < keywords.length - 1) { - var elseKeyword = keywords[i]; - var ifKeyword = keywords[i + 1]; - var shouldCombindElseAndIf = true; - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { - if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; - break; - } - } - if (shouldCombindElseAndIf) { - result.push({ - fileName: fileName, - textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: HighlightSpanKind.reference - }); - i++; - continue; - } - } - result.push(getHighlightSpanForNode(keywords[i])); - } - return result; - } - } + return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { synchronizeHostData(); @@ -47616,7 +59854,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, isDefinition: false }); } @@ -47624,24 +59862,13 @@ var ts; return result; } } - function convertReferences(referenceSymbols) { - if (!referenceSymbols) { - return undefined; - } - var referenceEntries = []; - for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { - var referenceSymbol = referenceSymbols_1[_i]; - ts.addRange(referenceEntries, referenceSymbol.references); - } - return referenceEntries; - } function findRenameLocations(fileName, position, findInStrings, findInComments) { var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, false, false); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function findReferences(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, false, false); @@ -47649,672 +59876,12 @@ var ts; } function findReferencedSymbols(fileName, position, findInStrings, findInComments) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position, true); - if (node === sourceFile) { - return undefined; - } - switch (node.kind) { - case 8: - if (!isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - break; - } - case 69: - case 97: - case 9: - return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); - } - return undefined; + return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function isThis(node) { - switch (node.kind) { - case 97: - return true; - case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; - default: - return false; - } - } - function getReferencedSymbolsForNode(node, sourceFiles, findInStrings, findInComments) { - var typeChecker = program.getTypeChecker(); - if (isLabelName(node)) { - if (isJumpStatementTarget(node)) { - var labelDefinition = getTargetLabel(node.parent, node.text); - return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; - } - else { - return getLabelReferencesInNode(node.parent, node); - } - } - if (isThis(node)) { - return getReferencesForThisKeyword(node, sourceFiles); - } - if (node.kind === 95) { - return getReferencesForSuperKeyword(node); - } - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol && node.kind === 9) { - return getReferencesForStringLiteral(node, sourceFiles); - } - if (!symbol) { - return undefined; - } - var declarations = symbol.declarations; - if (!declarations || !declarations.length) { - return undefined; - } - var result; - var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); - var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - var scope = getSymbolScope(symbol); - var symbolToIndex = []; - if (scope) { - result = []; - getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; - cancellationToken.throwIfCancellationRequested(); - var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { - result = result || []; - getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - } - } - return result; - function getDefinition(symbol) { - var info = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, node.getSourceFile(), getContainerNode(node), node); - var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } - return { - containerKind: "", - containerName: "", - name: name, - kind: info.symbolKind, - fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0) - }; - } - function getAliasSymbolForPropertyNameSymbol(symbol, location) { - if (symbol.flags & 8388608) { - var defaultImport = ts.getDeclarationOfKind(symbol, 231); - if (defaultImport) { - return typeChecker.getAliasedSymbol(symbol); - } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 || - declaration.kind === 238) ? declaration : undefined; }); - if (importOrExportSpecifier && - (!importOrExportSpecifier.propertyName || - importOrExportSpecifier.propertyName === location)) { - return importOrExportSpecifier.kind === 234 ? - typeChecker.getAliasedSymbol(symbol) : - typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); - } - } - return undefined; - } - function getPropertySymbolOfDestructuringAssignment(location) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - typeChecker.getPropertySymbolOfDestructuringAssignment(location); - } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); - return bindingElement && - bindingElement.parent.kind === 167 && - !bindingElement.propertyName; - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); - var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); - return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - } - return undefined; - } - function getInternedName(symbol, location, declarations) { - if (ts.isImportOrExportSpecifierName(location)) { - return location.getText(); - } - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - symbol = localExportDefaultSymbol || symbol; - return ts.stripQuotes(symbol.name); - } - function getSymbolScope(symbol) { - var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 || valueDeclaration.kind === 192)) { - return valueDeclaration; - } - if (symbol.flags & (4 | 8192)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8) ? d : undefined; }); - if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221); - } - } - if (symbol.flags & 8388608) { - return undefined; - } - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - return undefined; - } - if (symbol.parent || (symbol.flags & 268435456)) { - return undefined; - } - var scope; - var declarations = symbol.getDeclarations(); - if (declarations) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - var container = getContainerNode(declaration); - if (!container) { - return undefined; - } - if (scope && scope !== container) { - return undefined; - } - if (container.kind === 256 && !ts.isExternalModule(container)) { - return undefined; - } - scope = container; - } - } - return scope; - } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { - var positions = []; - if (!symbolName || !symbolName.length) { - return positions; - } - var text = sourceFile.text; - var sourceLength = text.length; - var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); - while (position >= 0) { - cancellationToken.throwIfCancellationRequested(); - if (position > end) - break; - var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2))) { - positions.push(position); - } - position = text.indexOf(symbolName, position + symbolNameLength + 1); - } - return positions; - } - function getLabelReferencesInNode(container, targetLabel) { - var references = []; - var sourceFile = container.getSourceFile(); - var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - return; - } - if (node === targetLabel || - (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = { - containerKind: "", - containerName: "", - fileName: targetLabel.getSourceFile().fileName, - kind: ScriptElementKind.label, - name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) - }; - return [{ definition: definition, references: references }]; - } - function isValidReferencePosition(node, searchSymbolName) { - if (node) { - switch (node.kind) { - case 69: - return node.getWidth() === searchSymbolName.length; - case 9: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isNameOfExternalModuleImportOrDeclaration(node)) { - return node.getWidth() === searchSymbolName.length + 2; - } - break; - case 8: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - return node.getWidth() === searchSymbolName.length; - } - break; - } - } - return false; - } - function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { - var sourceFile = container.getSourceFile(); - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0) { - var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); - referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); - } - } - }); - } - return; - function getReferencedSymbol(symbol) { - var symbolId = ts.getSymbolId(symbol); - var index = symbolToIndex[symbolId]; - if (index === undefined) { - index = result.length; - symbolToIndex[symbolId] = index; - result.push({ - definition: getDefinition(symbol), - references: [] - }); - } - return result[index]; - } - function isInNonReferenceComment(sourceFile, position) { - return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - } - function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, false); - if (!searchSpaceNode) { - return undefined; - } - var staticFlag = 32; - switch (searchSpaceNode.kind) { - case 145: - case 144: - case 147: - case 146: - case 148: - case 149: - case 150: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; - break; - default: - return undefined; - } - var references = []; - var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95) { - return; - } - var container = ts.getSuperContainer(node, false); - if (container && (32 & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = getDefinition(searchSpaceNode.symbol); - return [{ definition: definition, references: references }]; - } - function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { - var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); - var staticFlag = 32; - switch (searchSpaceNode.kind) { - case 147: - case 146: - if (ts.isObjectLiteralMethod(searchSpaceNode)) { - break; - } - case 145: - case 144: - case 148: - case 149: - case 150: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; - break; - case 256: - if (ts.isExternalModule(searchSpaceNode)) { - return undefined; - } - case 220: - case 179: - break; - default: - return undefined; - } - var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 256) { - ts.forEach(sourceFiles, function (sourceFile) { - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: "this", - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || !isThis(node)) { - return; - } - var container = ts.getThisContainer(node, false); - switch (searchSpaceNode.kind) { - case 179: - case 220: - if (searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 147: - case 146: - if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 192: - case 221: - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 32) === staticFlag) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 256: - if (container.kind === 256 && !ts.isExternalModule(container)) { - result.push(getReferenceEntryFromNode(node)); - } - break; - } - }); - } - } - function getReferencesForStringLiteral(node, sourceFiles) { - var typeChecker = program.getTypeChecker(); - var type = getStringLiteralTypeForNode(node, typeChecker); - if (!type) { - return undefined; - } - var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); - getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: type.text, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; - cancellationToken.throwIfCancellationRequested(); - var node_2 = ts.getTouchingWord(sourceFile, position); - if (!node_2 || node_2.kind !== 9) { - return; - } - var type_1 = getStringLiteralTypeForNode(node_2, typeChecker); - if (type_1 === searchType) { - references.push(getReferenceEntryFromNode(node_2)); - } - } - } - } - function populateSearchSymbolSet(symbol, location) { - var result = [symbol]; - var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254) { - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); - if (propertySymbol) { - result.push(propertySymbol); - } - } - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); - if (aliasSymbol) { - result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); - } - if (containingObjectLiteralElement) { - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); - }); - var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); - if (shorthandValueSymbol) { - result.push(shorthandValueSymbol); - } - } - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); - if (bindingElementPropertySymbol) { - result.push(bindingElementPropertySymbol); - } - ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, {}); - } - }); - return result; - } - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { - if (!symbol) { - return; - } - if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { - return; - } - if (symbol.flags & (32 | 64)) { - ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === 222) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = typeChecker.getTypeAtLocation(typeReference); - if (type) { - var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); - if (propertySymbol) { - result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); - } - previousIterationSymbolsCache[symbol.name] = symbol; - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); - } - } - } - } - function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation) { - if (searchSymbols.indexOf(referenceSymbol) >= 0) { - return referenceSymbol; - } - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); - if (aliasSymbol) { - return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation); - } - var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); - if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - }); - if (contextualSymbol) { - return contextualSymbol; - } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); - if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { - return propertySymbol; - } - } - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); - if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { - return bindingElementPropertySymbol; - } - return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { - if (searchSymbols.indexOf(rootSymbol) >= 0) { - return rootSymbol; - } - if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - var result_4 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, {}); - return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - } - return undefined; - }); - } - function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140) { - var nameExpression = node.name.expression; - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { - return nameExpression.text; - } - return undefined; - } - return node.name.text; - } - function getPropertySymbolsFromContextualType(node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol_1 = contextualType.getProperty(name); - if (symbol_1) { - result_5.push(symbol_1); - } - if (contextualType.flags & 16384) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; - } - function getIntersectingMeaningFromDeclarations(meaning, declarations) { - if (declarations) { - var lastIterationMeaning = void 0; - do { - lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; - var declarationMeaning = getMeaningFromDeclaration(declaration); - if (declarationMeaning & meaning) { - meaning |= declarationMeaning; - } - } - } while (meaning !== lastIterationMeaning); - } - return meaning; - } - } - function getReferenceEntryFromNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - if (node.kind === 9) { - start += 1; - end -= 1; - } - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) - }; - } - function isWriteAccess(node) { - if (node.kind === 69 && ts.isDeclarationName(node)) { - return true; - } - var parent = node.parent; - if (parent) { - if (parent.kind === 186 || parent.kind === 185) { - return true; - } - else if (parent.kind === 187 && parent.left === node) { - var operator = parent.operatorToken.kind; - return 56 <= operator && operator <= 68; - } - } - return false; - } - function getNavigateToItems(searchValue, maxResultCount) { + function getNavigateToItems(searchValue, maxResultCount, fileName) { synchronizeHostData(); - var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -48333,130 +59900,6 @@ var ts; emitSkipped: emitOutput.emitSkipped }; } - function getMeaningFromDeclaration(node) { - switch (node.kind) { - case 142: - case 218: - case 169: - case 145: - case 144: - case 253: - case 254: - case 255: - case 147: - case 146: - case 148: - case 149: - case 150: - case 220: - case 179: - case 180: - case 252: - return 1; - case 141: - case 222: - case 223: - case 159: - return 2; - case 221: - case 224: - return 1 | 2; - case 225: - if (ts.isAmbientModule(node)) { - return 4 | 1; - } - else if (ts.getModuleInstanceState(node) === 1) { - return 4 | 1; - } - else { - return 4; - } - case 233: - case 234: - case 229: - case 230: - case 235: - case 236: - return 1 | 2 | 4; - case 256: - return 4 | 1; - } - return 1 | 2 | 4; - } - function isTypeReference(node) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - return node.parent.kind === 155 || - (node.parent.kind === 194 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 && !ts.isExpression(node)) || - node.kind === 165; - } - function isNamespaceReference(node) { - return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); - } - function isPropertyAccessNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 172) { - while (root.parent && root.parent.kind === 172) { - root = root.parent; - } - isLastClause = root.name === node; - } - if (!isLastClause && root.parent.kind === 194 && root.parent.parent.kind === 251) { - var decl = root.parent.parent.parent; - return (decl.kind === 221 && root.parent.parent.token === 106) || - (decl.kind === 222 && root.parent.parent.token === 83); - } - return false; - } - function isQualifiedNameNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 139) { - while (root.parent && root.parent.kind === 139) { - root = root.parent; - } - isLastClause = root.right === node; - } - return root.parent.kind === 155 && !isLastClause; - } - function isInRightSideOfImport(node) { - while (node.parent.kind === 139) { - node = node.parent; - } - return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; - } - function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69); - if (node.parent.kind === 139 && - node.parent.right === node && - node.parent.parent.kind === 229) { - return 1 | 2 | 4; - } - return 4; - } - function getMeaningFromLocation(node) { - if (node.parent.kind === 235) { - return 1 | 2 | 4; - } - else if (isInRightSideOfImport(node)) { - return getMeaningFromRightHandSideOfImportEquals(node); - } - else if (ts.isDeclarationName(node)) { - return getMeaningFromDeclaration(node.parent); - } - else if (isTypeReference(node)) { - return 2; - } - else if (isNamespaceReference(node)) { - return 4; - } - else { - return 1; - } - } function getSignatureHelpItems(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -48465,6 +59908,9 @@ var ts; function getNonBoundSourceFile(fileName) { return syntaxTreeCache.getCurrentSourceFile(fileName); } + function getSourceFile(fileName) { + return getNonBoundSourceFile(fileName); + } function getNameOrDottedNameSpan(fileName, startPos, endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, startPos); @@ -48475,7 +59921,6 @@ var ts; case 172: case 139: case 9: - case 166: case 84: case 99: case 93: @@ -48489,10 +59934,10 @@ var ts; } var nodeForStartPos = node; while (true) { - if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { nodeForStartPos = nodeForStartPos.parent; } - else if (isNameOfModuleDeclaration(nodeForStartPos)) { + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { if (nodeForStartPos.parent.parent.kind === 225 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -48516,406 +59961,18 @@ var ts; return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { - return convertClassifications(getEncodedSemanticClassifications(fileName, span)); - } - function checkForClassificationCancellation(kind) { - switch (kind) { - case 225: - case 221: - case 222: - case 220: - cancellationToken.throwIfCancellationRequested(); - } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); - var result = []; - var classifiableNames = program.getClassifiableNames(); - processNode(sourceFile); - return { spans: result, endOfLineState: 0 }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448) === 0) { - return; - } - if (flags & 32) { - return 11; - } - else if (flags & 384) { - return 12; - } - else if (flags & 524288) { - return 16; - } - else if (meaningAtPosition & 2) { - if (flags & 64) { - return 13; - } - else if (flags & 262144) { - return 15; - } - } - else if (flags & 1536) { - if (meaningAtPosition & 4 || - (meaningAtPosition & 1 && hasValueSideModule(symbol))) { - return 14; - } - } - return undefined; - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 && - ts.getModuleInstanceState(declaration) === 1; - }); - } - } - function processNode(node) { - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(kind); - if (kind === 69 && !ts.nodeIsMissing(node)) { - var identifier = node; - if (classifiableNames[identifier.text]) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } - } - } - function getClassificationTypeName(type) { - switch (type) { - case 1: return ClassificationTypeNames.comment; - case 2: return ClassificationTypeNames.identifier; - case 3: return ClassificationTypeNames.keyword; - case 4: return ClassificationTypeNames.numericLiteral; - case 5: return ClassificationTypeNames.operator; - case 6: return ClassificationTypeNames.stringLiteral; - case 8: return ClassificationTypeNames.whiteSpace; - case 9: return ClassificationTypeNames.text; - case 10: return ClassificationTypeNames.punctuation; - case 11: return ClassificationTypeNames.className; - case 12: return ClassificationTypeNames.enumName; - case 13: return ClassificationTypeNames.interfaceName; - case 14: return ClassificationTypeNames.moduleName; - case 15: return ClassificationTypeNames.typeParameterName; - case 16: return ClassificationTypeNames.typeAliasName; - case 17: return ClassificationTypeNames.parameterName; - case 18: return ClassificationTypeNames.docCommentTagName; - case 19: return ClassificationTypeNames.jsxOpenTagName; - case 20: return ClassificationTypeNames.jsxCloseTagName; - case 21: return ClassificationTypeNames.jsxSelfClosingTagName; - case 22: return ClassificationTypeNames.jsxAttribute; - case 23: return ClassificationTypeNames.jsxText; - case 24: return ClassificationTypeNames.jsxAttributeStringLiteralValue; - } - } - function convertClassifications(classifications) { - ts.Debug.assert(classifications.spans.length % 3 === 0); - var dense = classifications.spans; - var result = []; - for (var i = 0, n = dense.length; i < n; i += 3) { - result.push({ - textSpan: ts.createTextSpan(dense[i], dense[i + 1]), - classificationType: getClassificationTypeName(dense[i + 2]) - }); - } - return result; + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getSyntacticClassifications(fileName, span) { - return convertClassifications(getEncodedSyntacticClassifications(fileName, span)); + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getEncodedSyntacticClassifications(fileName, span) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var spanStart = span.start; - var spanLength = span.length; - var triviaScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); - var result = []; - processElement(sourceFile); - return { spans: result, endOfLineState: 0 }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifyLeadingTriviaAndGetTokenStart(token) { - triviaScanner.setTextPos(token.pos); - while (true) { - var start = triviaScanner.getTextPos(); - if (!ts.couldStartTrivia(sourceFile.text, start)) { - return start; - } - var kind = triviaScanner.scan(); - var end = triviaScanner.getTextPos(); - var width = end - start; - if (!ts.isTrivia(kind)) { - return start; - } - if (kind === 4 || kind === 5) { - continue; - } - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - if (ch === 60 || ch === 62) { - pushClassification(start, width, 1); - continue; - } - ts.Debug.assert(ch === 61); - classifyDisabledMergeCode(text, start, end); - } - } - } - function classifyComment(token, kind, start, width) { - if (kind === 3) { - var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); - if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { - docCommentAndDiagnostics.jsDocComment.parent = token; - classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); - return; - } - } - pushCommentRange(start, width); - } - function pushCommentRange(start, width) { - pushClassification(start, width, 1); - } - function classifyJSDocComment(docComment) { - var pos = docComment.pos; - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - if (tag.pos !== pos) { - pushCommentRange(pos, tag.pos - pos); - } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10); - pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); - pos = tag.tagName.end; - switch (tag.kind) { - case 275: - processJSDocParameterTag(tag); - break; - case 278: - processJSDocTemplateTag(tag); - break; - case 277: - processElement(tag.typeExpression); - break; - case 276: - processElement(tag.typeExpression); - break; - } - pos = tag.end; - } - if (pos !== docComment.end) { - pushCommentRange(pos, docComment.end - pos); - } - return; - function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17); - pos = tag.preParameterName.end; - } - if (tag.typeExpression) { - pushCommentRange(pos, tag.typeExpression.pos - pos); - processElement(tag.typeExpression); - pos = tag.typeExpression.end; - } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17); - pos = tag.postParameterName.end; - } - } - } - function processJSDocTemplateTag(tag) { - for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { - var child = _a[_i]; - processElement(child); - } - } - function classifyDisabledMergeCode(text, start, end) { - var i; - for (i = start; i < end; i++) { - if (ts.isLineBreak(text.charCodeAt(i))) { - break; - } - } - pushClassification(start, i - start, 1); - mergeConflictScanner.setTextPos(i); - while (mergeConflictScanner.getTextPos() < end) { - classifyDisabledCodeToken(); - } - } - function classifyDisabledCodeToken() { - var start = mergeConflictScanner.getTextPos(); - var tokenKind = mergeConflictScanner.scan(); - var end = mergeConflictScanner.getTextPos(); - var type = classifyTokenType(tokenKind); - if (type) { - pushClassification(start, end - start, type); - } - } - function tryClassifyNode(node) { - if (ts.nodeIsMissing(node)) { - return true; - } - var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 && classifiedElementName === undefined) { - return false; - } - var tokenStart = node.kind === 244 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); - var tokenWidth = node.end - tokenStart; - ts.Debug.assert(tokenWidth >= 0); - if (tokenWidth > 0) { - var type = classifiedElementName || classifyTokenType(node.kind, node); - if (type) { - pushClassification(tokenStart, tokenWidth, type); - } - } - return true; - } - function tryClassifyJsxElementName(token) { - switch (token.parent && token.parent.kind) { - case 243: - if (token.parent.tagName === token) { - return 19; - } - break; - case 245: - if (token.parent.tagName === token) { - return 20; - } - break; - case 242: - if (token.parent.tagName === token) { - return 21; - } - break; - case 246: - if (token.parent.name === token) { - return 22; - } - break; - } - return undefined; - } - function classifyTokenType(tokenKind, token) { - if (ts.isKeyword(tokenKind)) { - return 3; - } - if (tokenKind === 25 || tokenKind === 27) { - if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { - return 10; - } - } - if (ts.isPunctuation(tokenKind)) { - if (token) { - if (tokenKind === 56) { - if (token.parent.kind === 218 || - token.parent.kind === 145 || - token.parent.kind === 142 || - token.parent.kind === 246) { - return 5; - } - } - if (token.parent.kind === 187 || - token.parent.kind === 185 || - token.parent.kind === 186 || - token.parent.kind === 188) { - return 5; - } - } - return 10; - } - else if (tokenKind === 8) { - return 4; - } - else if (tokenKind === 9 || tokenKind === 166) { - return token.parent.kind === 246 ? 24 : 6; - } - else if (tokenKind === 10) { - return 6; - } - else if (ts.isTemplateLiteralKind(tokenKind)) { - return 6; - } - else if (tokenKind === 244) { - return 23; - } - else if (tokenKind === 69) { - if (token) { - switch (token.parent.kind) { - case 221: - if (token.parent.name === token) { - return 11; - } - return; - case 141: - if (token.parent.name === token) { - return 15; - } - return; - case 222: - if (token.parent.name === token) { - return 13; - } - return; - case 224: - if (token.parent.name === token) { - return 12; - } - return; - case 225: - if (token.parent.name === token) { - return 14; - } - return; - case 142: - if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; - } - return; - } - } - return 2; - } - } - function processElement(element) { - if (!element) { - return; - } - if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { - checkForClassificationCancellation(element.kind); - var children = element.getChildren(sourceFile); - for (var i = 0, n = children.length; i < n; i++) { - var child = children[i]; - if (!tryClassifyNode(child)) { - processElement(child); - } - } - } - } + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getOutliningSpans(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); @@ -48962,12 +60019,12 @@ var ts; } } function getIndentationAtPosition(fileName, position, editorOptions) { - var start = new Date().getTime(); + var start = ts.timestamp(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); - start = new Date().getTime(); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); - log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { @@ -48992,56 +60049,7 @@ var ts; return []; } function getDocCommentTemplateAtPosition(fileName, position) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { - return undefined; - } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); - var tokenStart = tokenAtPos.getStart(); - if (!tokenAtPos || tokenStart < position) { - return undefined; - } - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 220: - case 147: - case 148: - case 221: - case 200: - break findOwner; - case 256: - return undefined; - case 225: - if (commentOwner.parent.kind === 225) { - return undefined; - } - break findOwner; - } - } - if (!commentOwner || commentOwner.getStart() < position) { - return undefined; - } - var parameters = getParametersForJsDocOwningNode(commentOwner); - var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); - var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; - var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); - var newLine = ts.getNewLineOrDefaultFromHost(host); - var docParams = ""; - for (var i = 0, numParams = parameters.length; i < numParams; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 69 ? - currentName.text : - "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; - } - var preamble = "/**" + newLine + - indentationStr + " * "; - var result = preamble + newLine + - docParams + - indentationStr + " */" + - (tokenStart === position ? newLine + indentationStr : ""); - return { newText: result, caretOffset: preamble.length }; + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { if (openingBrace === 60) { @@ -49059,38 +60067,6 @@ var ts; } return true; } - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 200) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); - } - } - return emptyArray; - } - function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178) { - rightHandSide = rightHandSide.expression; - } - switch (rightHandSide.kind) { - case 179: - case 180: - return rightHandSide.parameters; - case 192: - for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148) { - return member.parameters; - } - } - break; - } - return emptyArray; - } function getTodoComments(fileName, descriptors) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -49107,7 +60083,7 @@ var ts; var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInsideComment(sourceFile, token, matchPosition)) { continue; } var descriptor = undefined; @@ -49150,101 +60126,10 @@ var ts; (char >= 48 && char <= 57); } } - function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 ? node.parent : node; - var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256) { - return type; - } - return undefined; - } function getRenameInfo(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); - var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); - var node = ts.getTouchingWord(sourceFile, position, true); - if (node) { - if (node.kind === 69 || - node.kind === 9 || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isThis(node)) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var declarations = symbol.getDeclarations(); - if (declarations && declarations.length > 0) { - if (ts.forEach(declarations, isDefinedInLibraryFile)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - var kind = getSymbolKind(symbol, node); - if (kind) { - return { - canRename: true, - kind: kind, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), - kindModifiers: getSymbolModifiers(symbol), - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - else if (node.kind === 9) { - var type = getStringLiteralTypeForNode(node, typeChecker); - if (type) { - if (isDefinedInLibraryFile(node)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - else { - var displayName = ts.stripQuotes(type.text); - return { - canRename: true, - kind: ScriptElementKind.variableElement, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: displayName, - kindModifiers: ScriptElementKindModifier.none, - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - } - } - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); - function getRenameInfoError(localizedErrorMessage) { - return { - canRename: false, - localizedErrorMessage: localizedErrorMessage, - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; - } - function isDefinedInLibraryFile(declaration) { - if (defaultLibFileName) { - var sourceFile_2 = declaration.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (canonicalName === canonicalDefaultLibName) { - return true; - } - } - return false; - } - function createTriggerSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var width = node.getWidth(sourceFile); - if (node.kind === 9) { - start += 1; - width -= 2; - } - return ts.createTextSpan(start, width); - } + return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } return { dispose: dispose, @@ -49258,9 +60143,11 @@ var ts; getEncodedSemanticClassifications: getEncodedSemanticClassifications, getCompletionsAtPosition: getCompletionsAtPosition, getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, findReferences: findReferences, @@ -49283,6 +60170,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, + getSourceFile: getSourceFile, getProgram: getProgram }; } @@ -49295,7 +60183,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -49329,340 +60217,6 @@ var ts; node.parent.kind === 173 && node.parent.argumentExpression === node; } - function createClassifier() { - var scanner = ts.createScanner(2, false); - var noRegexTable = []; - noRegexTable[69] = true; - noRegexTable[9] = true; - noRegexTable[8] = true; - noRegexTable[10] = true; - noRegexTable[97] = true; - noRegexTable[41] = true; - noRegexTable[42] = true; - noRegexTable[18] = true; - noRegexTable[20] = true; - noRegexTable[16] = true; - noRegexTable[99] = true; - noRegexTable[84] = true; - var templateStack = []; - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 || - keyword2 === 131 || - keyword2 === 121 || - keyword2 === 113) { - return true; - } - return false; - } - return true; - } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0, n = dense.length; i < n; i += 3) { - var start = dense[i]; - var length_3 = dense[i + 1]; - var type = dense[i + 2]; - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); - } - } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1: return TokenClass.Comment; - case 3: return TokenClass.Keyword; - case 4: return TokenClass.NumberLiteral; - case 5: return TokenClass.Operator; - case 6: return TokenClass.StringLiteral; - case 8: return TokenClass.Whitespace; - case 10: return TokenClass.Punctuation; - case 2: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 9: - case 17: - default: - return TokenClass.Identifier; - } - } - function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); - } - function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; - var token = 0; - var lastNonTriviaToken = 0; - while (templateStack.length > 0) { - templateStack.pop(); - } - switch (lexState) { - case 3: - text = "\"\\\n" + text; - offset = 3; - break; - case 2: - text = "'\\\n" + text; - offset = 3; - break; - case 1: - text = "/*\n" + text; - offset = 3; - break; - case 4: - text = "`\n" + text; - offset = 2; - break; - case 5: - text = "}\n" + text; - offset = 2; - case 6: - templateStack.push(12); - break; - } - scanner.setText(text); - var result = { - endOfLineState: 0, - spans: [] - }; - var angleBracketStack = 0; - do { - token = scanner.scan(); - if (!ts.isTrivia(token)) { - if ((token === 39 || token === 61) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10) { - token = 10; - } - } - else if (lastNonTriviaToken === 21 && isKeyword(token)) { - token = 69; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - token = 69; - } - else if (lastNonTriviaToken === 69 && - token === 25) { - angleBracketStack++; - } - else if (token === 27 && angleBracketStack > 0) { - angleBracketStack--; - } - else if (token === 117 || - token === 132 || - token === 130 || - token === 120 || - token === 133) { - if (angleBracketStack > 0 && !syntacticClassifierAbsent) { - token = 69; - } - } - else if (token === 12) { - templateStack.push(token); - } - else if (token === 15) { - if (templateStack.length > 0) { - templateStack.push(token); - } - } - else if (token === 16) { - if (templateStack.length > 0) { - var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12) { - token = scanner.reScanTemplateToken(); - if (token === 14) { - templateStack.pop(); - } - else { - ts.Debug.assert(token === 13, "Should have been a template middle. Was " + token); - } - } - else { - ts.Debug.assert(lastTemplateStackToken === 15, "Should have been an open brace. Was: " + token); - templateStack.pop(); - } - } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9 || token === 166) { - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92) { - numBackslashes++; - } - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 - ? 3 - : 2; - } - } - } - else if (token === 3) { - if (scanner.isUnterminated()) { - result.endOfLineState = 1; - } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 14) { - result.endOfLineState = 5; - } - else if (token === 11) { - result.endOfLineState = 4; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } - } - } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12) { - result.endOfLineState = 6; - } - } - } - function addResult(start, end, classification) { - if (classification === 8) { - return; - } - if (start === 0 && offset > 0) { - start += offset; - } - start -= offset; - end -= offset; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); - } - } - } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 37: - case 39: - case 40: - case 35: - case 36: - case 43: - case 44: - case 45: - case 25: - case 27: - case 28: - case 29: - case 91: - case 90: - case 116: - case 30: - case 31: - case 32: - case 33: - case 46: - case 48: - case 47: - case 51: - case 52: - case 67: - case 66: - case 68: - case 63: - case 64: - case 65: - case 57: - case 58: - case 59: - case 61: - case 62: - case 56: - case 24: - return true; - default: - return false; - } - } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 35: - case 36: - case 50: - case 49: - case 41: - case 42: - return true; - default: - return false; - } - } - function isKeyword(token) { - return token >= 70 && token <= 138; - } - function classFromKind(token) { - if (isKeyword(token)) { - return 3; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5; - } - else if (token >= 15 && token <= 68) { - return 10; - } - switch (token) { - case 8: - return 4; - case 9: - case 166: - return 6; - case 10: - return 7; - case 7: - case 3: - case 2: - return 1; - case 5: - case 4: - return 8; - case 69: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6; - } - return 2; - } - } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; - } - ts.createClassifier = createClassifier; function getDefaultLibFilePath(options) { if (typeof __dirname !== "undefined") { return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); @@ -49671,13 +60225,7 @@ var ts; } ts.getDefaultLibFilePath = getDefaultLibFilePath; function initializeServices() { - ts.objectAllocator = { - getNodeConstructor: function () { return NodeObject; }, - getSourceFileConstructor: function () { return SourceFileObject; }, - getSymbolConstructor: function () { return SymbolObject; }, - getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } - }; + ts.objectAllocator = getServicesObjectAllocator(); } initializeServices(); })(ts || (ts = {})); @@ -49775,6 +60323,7 @@ var ts; CommandNames.Formatonkey = "formatonkey"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; + CommandNames.Implementation = "implementation"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; @@ -49806,7 +60355,7 @@ var ts; this.hrtime = hrtime; this.logger = logger; this.changeSeq = 0; - this.handlers = (_a = {}, + this.handlers = ts.createMap((_a = {}, _a[CommandNames.Exit] = function () { _this.exit(); return { responseRequired: false }; @@ -49819,6 +60368,10 @@ var ts; var defArgs = request.arguments; return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, + _a[CommandNames.Implementation] = function (request) { + var implArgs = request.arguments; + return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + }, _a[CommandNames.References] = function (request) { var defArgs = request.arguments; return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; @@ -49915,7 +60468,7 @@ var ts; }, _a[CommandNames.Navto] = function (request) { var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true }; + return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; }, _a[CommandNames.Brace] = function (request) { var braceArguments = request.arguments; @@ -49941,19 +60494,24 @@ var ts; _this.reloadProjects(); return { responseRequired: false }; }, - _a - ); + _a)); this.projectService = - new server.ProjectService(host, logger, function (eventName, project, fileName) { - _this.handleEvent(eventName, project, fileName); + new server.ProjectService(host, logger, function (event) { + _this.handleEvent(event); }); var _a; } - Session.prototype.handleEvent = function (eventName, project, fileName) { + Session.prototype.handleEvent = function (event) { var _this = this; - if (eventName == "context") { - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); - this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); + switch (event.eventName) { + case "context": + var _a = event.data, project = _a.project, fileName = _a.fileName; + this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); + break; + case "configFileDiag": + var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; + this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); } }; Session.prototype.logError = function (err, cmd) { @@ -50133,6 +60691,23 @@ var ts; end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) }); }); }; + Session.prototype.getImplementation = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + if (!implementations) { + return undefined; + } + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), + end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) + }); }); + }; Session.prototype.getOccurrences = function (line, offset, fileName) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); @@ -50469,7 +61044,15 @@ var ts; } return completions.entries.reduce(function (result, entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - result.push(entry); + var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = undefined; + if (replacementSpan) { + convertedSpan = { + start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), + end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) + }; + } + result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } return result; }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); @@ -50603,7 +61186,7 @@ var ts; } return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { + Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); @@ -50613,7 +61196,7 @@ var ts; } var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); + var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); if (!navItems) { return []; } @@ -50717,7 +61300,7 @@ var ts; return { response: response, responseRequired: true }; }; Session.prototype.addProtocolHandler = function (command, handler) { - if (this.handlers[command]) { + if (command in this.handlers) { throw new Error("Protocol handler already exists for command \"" + command + "\""); } this.handlers[command] = handler; @@ -50793,7 +61376,6 @@ var ts; if (isOpen === void 0) { isOpen = false; } this.host = host; this.fileName = fileName; - this.content = content; this.isOpen = isOpen; this.children = []; this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); @@ -50849,25 +61431,28 @@ var ts; readFile: function (fileName) { return _this.host.readFile(fileName); }, directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } }; + if (this.host.realpath) { + this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; + } } LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); var currentResolutionsInFile = cache.get(path); - var newResolutions = {}; + var newResolutions = ts.createMap(); var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_43 = names_2[_i]; - var resolution = ts.lookUp(newResolutions, name_43); + for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { + var name_53 = names_3[_i]; + var resolution = newResolutions[name_53]; if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } else { - resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); + resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); resolution.lastCheckTime = Date.now(); - newResolutions[name_43] = resolution; + newResolutions[name_53] = resolution; } } ts.Debug.assert(resolution !== undefined); @@ -50966,7 +61551,7 @@ var ts; LSHost.prototype.removeRoot = function (info) { if (this.filenameToScript.contains(info.path)) { this.filenameToScript.remove(info.path); - this.roots = copyListRemovingItem(info, this.roots); + ts.unorderedRemoveItem(this.roots, info); this.resolvedModuleNames.remove(info.path); this.resolvedTypeReferenceDirectives.remove(info.path); } @@ -50992,10 +61577,6 @@ var ts; } throw new Error("No script with name '" + filename + "'"); }; - LSHost.prototype.resolvePath = function (path) { - var result = this.host.resolvePath(path); - return result; - }; LSHost.prototype.fileExists = function (path) { var result = this.host.fileExists(path); return result; @@ -51006,6 +61587,12 @@ var ts; LSHost.prototype.getDirectories = function (path) { return this.host.getDirectories(path); }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.readFile = function (path, encoding) { + return this.host.readFile(path, encoding); + }; LSHost.prototype.lineToTextSpan = function (filename, line) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); @@ -51048,7 +61635,7 @@ var ts; this.projectOptions = projectOptions; this.languageServiceDiabled = languageServiceDiabled; this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = {}; + this.filenameToSourceFile = ts.createMap(); this.updateGraphSeq = 0; this.openRefCount = 0; if (projectOptions && projectOptions.files) { @@ -51132,7 +61719,7 @@ var ts; if (this.languageServiceDiabled) { return; } - this.filenameToSourceFile = {}; + this.filenameToSourceFile = ts.createMap(); var sourceFiles = this.program.getSourceFiles(); for (var i = 0, len = sourceFiles.length; i < len; i++) { var normFilename = ts.normalizePath(sourceFiles[i].fileName); @@ -51177,7 +61764,7 @@ var ts; } } var strBuilder = ""; - ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); + ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); return strBuilder; }; Project.prototype.setProjectOptions = function (projectOptions) { @@ -51192,15 +61779,6 @@ var ts; return Project; }()); server.Project = Project; - function copyListRemovingItem(item, list) { - var copiedList = []; - for (var i = 0, len = list.length; i < len; i++) { - if (list[i] != item) { - copiedList.push(list[i]); - } - } - return copiedList; - } function combineProjectOutput(projects, action, comparer, areEqual) { var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; @@ -51211,15 +61789,15 @@ var ts; this.host = host; this.psLogger = psLogger; this.eventHandler = eventHandler; - this.filenameToScriptInfo = {}; + this.filenameToScriptInfo = ts.createMap(); this.openFileRoots = []; this.inferredProjects = []; this.configuredProjects = []; this.openFilesReferenced = []; this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = {}; - this.directoryWatchersRefCount = {}; - this.timerForDetectingProjectFileListChanges = {}; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + this.timerForDetectingProjectFileListChanges = ts.createMap(); this.addDefaultHostConfiguration(); } ProjectService.prototype.addDefaultHostConfiguration = function () { @@ -51267,7 +61845,8 @@ var ts; }; ProjectService.prototype.handleProjectFileListChanges = function (project) { var _this = this; - var projectOptions = this.configFileToProjectOptions(project.projectFilename).projectOptions; + var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; + this.reportConfigFileDiagnostics(project.projectFilename, errors); var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { @@ -51275,14 +61854,26 @@ var ts; this.updateProjectStructure(); } }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (diagnostics && diagnostics.length > 0) { + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } + }); + } + }; ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { var _this = this; - if (ts.getBaseFileName(fileName) != "tsconfig.json") { + if (ts.getBaseFileName(fileName) !== "tsconfig.json") { this.log(fileName + " is not tsconfig.json"); return; } this.log("Detected newly added tsconfig file: " + fileName); - var projectOptions = this.configFileToProjectOptions(fileName).projectOptions; + var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; + this.reportConfigFileDiagnostics(fileName, errors); + if (!projectOptions) { + return; + } var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { @@ -51299,8 +61890,11 @@ var ts; }; ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { this.log("Config file changed: " + project.projectFilename); - this.updateConfiguredProject(project); + var configFileErrors = this.updateConfiguredProject(project); this.updateProjectStructure(); + if (configFileErrors && configFileErrors.length > 0) { + this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); + } }; ProjectService.prototype.log = function (msg, type) { if (type === void 0) { type = "Err"; } @@ -51370,13 +61964,13 @@ var ts; for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { var openFile = this.openFileRoots[j]; if (this.eventHandler) { - this.eventHandler("context", openFile.defaultProject, openFile.fileName); + this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); } } for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { var openFile = this.openFilesReferenced[j]; if (this.eventHandler) { - this.eventHandler("context", openFile.defaultProject, openFile.fileName); + this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); } } } @@ -51396,9 +61990,9 @@ var ts; if (project.isConfiguredProject()) { project.projectFileWatcher.close(); project.directoryWatcher.close(); - ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); delete project.directoriesWatchedForWildcards; - this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); + ts.unorderedRemoveItem(this.configuredProjects, project); } else { for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { @@ -51410,7 +62004,7 @@ var ts; delete project.projectService.directoryWatchersForTsconfig[directory]; } } - this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); + ts.unorderedRemoveItem(this.inferredProjects, project); } var fileNames = project.getFileNames(); for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { @@ -51509,7 +62103,7 @@ var ts; } } else { - this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + ts.unorderedRemoveItem(this.openFilesReferenced, info); } info.close(); }; @@ -51604,12 +62198,12 @@ var ts; }; ProjectService.prototype.getScriptInfo = function (filename) { filename = ts.normalizePath(filename); - return ts.lookUp(this.filenameToScriptInfo, filename); + return this.filenameToScriptInfo[filename]; }; ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { var _this = this; fileName = ts.normalizePath(fileName); - var info = ts.lookUp(this.filenameToScriptInfo, fileName); + var info = this.filenameToScriptInfo[fileName]; if (!info) { var content = void 0; if (this.host.fileExists(fileName)) { @@ -51674,7 +62268,7 @@ var ts; var project = this.findConfiguredProjectByConfigFile(configFileName); if (!project) { var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.success) { + if (!configResult.project) { return { configFileName: configFileName, configFileErrors: configResult.errors }; } else { @@ -51688,14 +62282,15 @@ var ts; else { this.updateConfiguredProject(project); } + return { configFileName: configFileName }; } else { this.log("No config files found."); } - return configFileName ? { configFileName: configFileName } : {}; + return {}; }; ProjectService.prototype.closeClientFile = function (filename) { - var info = ts.lookUp(this.filenameToScriptInfo, filename); + var info = this.filenameToScriptInfo[filename]; if (info) { this.closeOpenFile(info); info.isOpen = false; @@ -51703,13 +62298,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + var scriptInfo = this.filenameToScriptInfo[filename]; if (scriptInfo) { return scriptInfo.defaultProject; } }; ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + var scriptInfo = this.filenameToScriptInfo[filename]; if (scriptInfo) { this.psLogger.startGroup(); this.psLogger.info("Projects for " + filename); @@ -51773,30 +62368,25 @@ var ts; }; ProjectService.prototype.configFileToProjectOptions = function (configFilename) { configFilename = ts.normalizePath(configFilename); + var errors = []; var dirPath = ts.getDirectoryPath(configFilename); var contents = this.host.readFile(configFilename); - var rawConfig = ts.parseConfigFileTextToJson(configFilename, contents); - if (rawConfig.error) { - return { succeeded: false, errors: [rawConfig.error] }; + var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; + errors = ts.concatenate(errors, diagnostics); + var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); + errors = ts.concatenate(errors, parsedCommandLine.errors); + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { errors: errors }; } else { - var parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath, {}, configFilename); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { - return { succeeded: false, errors: parsedCommandLine.errors }; - } - else if (parsedCommandLine.fileNames.length === 0) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename); - return { succeeded: false, errors: [error] }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { succeeded: true, projectOptions: projectOptions }; - } + var projectOptions = { + files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, + compilerOptions: parsedCommandLine.options + }; + return { projectOptions: projectOptions, errors: errors }; } }; ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { @@ -51818,45 +62408,44 @@ var ts; }; ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { var _this = this; - var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; - if (!succeeded) { - return { success: false, errors: errors }; + var parseConfigFileResult = this.configFileToProjectOptions(configFilename); + var errors = parseConfigFileResult.errors; + if (!parseConfigFileResult.projectOptions) { + return { errors: errors }; } - else { - if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { - if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - var project_1 = this.createProject(configFilename, projectOptions, true); - project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - return { success: true, project: project_1 }; - } + var projectOptions = parseConfigFileResult.projectOptions; + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { project: project_1, errors: errors }; } - var project_2 = this.createProject(configFilename, projectOptions); - var errors_1; - for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { - var rootFilename = _b[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project_2.addRoot(info); - } - else { - (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project_2.finishGraph(); - project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); - var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath_1); - project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); - project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); - } - return watchers; - }, {}); - return { success: true, project: project_2, errors: errors_1 }; } + var project = this.createProject(configFilename, projectOptions); + for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { + var rootFilename = _a[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, clientFileName == rootFilename); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); + } + } + project.finishGraph(); + project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); + var configDirectoryPath = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath); + project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive); + } + return watchers; + }, {}); + return { project: project, errors: errors }; }; ProjectService.prototype.updateConfiguredProject = function (project) { var _this = this; @@ -51865,22 +62454,22 @@ var ts; this.removeProject(project); } else { - var _a = this.configFileToProjectOptions(project.projectFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; - if (!succeeded) { + var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; + if (!projectOptions) { return errors; } else { if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { project.setProjectOptions(projectOptions); if (project.languageServiceDiabled) { - return; + return errors; } project.disableLanguageService(); if (project.directoryWatcher) { project.directoryWatcher.close(); project.directoryWatcher = undefined; } - return; + return errors; } if (project.languageServiceDiabled) { project.setProjectOptions(projectOptions); @@ -51894,7 +62483,7 @@ var ts; } } project.finishGraph(); - return; + return errors; } var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); @@ -51916,13 +62505,13 @@ var ts; else { if (info.isOpen) { if (this.openFileRoots.indexOf(info) >= 0) { - this.openFileRoots = copyListRemovingItem(info, this.openFileRoots); + ts.unorderedRemoveItem(this.openFileRoots, info); if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { this.removeProject(info.defaultProject); } } if (this.openFilesReferenced.indexOf(info) >= 0) { - this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + ts.unorderedRemoveItem(this.openFilesReferenced, info); } this.openFileRootsConfigured.push(info); info.defaultProject = project; @@ -51933,6 +62522,7 @@ var ts; project.setProjectOptions(projectOptions); project.finishGraph(); } + return errors; } }; ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { @@ -51983,8 +62573,10 @@ var ts; InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + InsertSpaceAfterTypeAssertion: false, PlaceOpenBraceOnNewLineForFunctions: false, PlaceOpenBraceOnNewLineForControlBlocks: false }); @@ -52307,11 +62899,11 @@ var ts; snap.index.load(lm.lines); return svc; }; - ScriptVersionCache.changeNumberThreshold = 8; - ScriptVersionCache.changeLengthThreshold = 256; - ScriptVersionCache.maxVersions = 8; return ScriptVersionCache; }()); + ScriptVersionCache.changeNumberThreshold = 8; + ScriptVersionCache.changeLengthThreshold = 256; + ScriptVersionCache.maxVersions = 8; server.ScriptVersionCache = ScriptVersionCache; var LineIndexSnapshot = (function () { function LineIndexSnapshot(version, cache) { @@ -52419,7 +63011,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - this.done = true; + walkFns.done = true; } } }; @@ -53023,7 +63615,7 @@ var ts; return file; } function removeFile(file) { - watchedFiles = ts.copyListRemovingItem(file, watchedFiles); + ts.unorderedRemoveItem(watchedFiles, file); } return { getModifiedTime: getModifiedTime, @@ -53069,7 +63661,7 @@ var ts; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = this; +var debugObjectHost = new Function("return this")(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -53113,7 +63705,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.lookUp(resolutionsInFile, name); + var result = ts.getProperty(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -53124,7 +63716,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -53197,11 +63789,21 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return this.shimHost.getDirectories(path); + return JSON.parse(this.shimHost.getDirectories(path)); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -53211,7 +63813,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = Date.now(); + var time = ts.timestamp(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { this.lastCancellationCheckTime = time; @@ -53261,6 +63863,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -53268,11 +63873,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = Date.now(); + start = ts.timestamp(); } var result = action(); if (logPerformance) { - var end = Date.now(); + var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -53422,6 +64027,10 @@ var ts; var _this = this; return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); @@ -53498,9 +64107,9 @@ var ts; var _this = this; return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; @@ -53599,6 +64208,13 @@ var ts; }; }); }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -53722,4 +64338,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "1.9"; +var toolsVersion = "2.1"; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 2c9fffcfcfb..7ed6595bc80 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1,8 +1,11 @@ /// declare namespace ts { - interface Map { + interface MapLike { [index: string]: T; } + interface Map extends MapLike { + __mapBrand: any; + } type Path = string & { __pathBrand: any; }; @@ -185,7 +188,7 @@ declare namespace ts { IntersectionType = 163, ParenthesizedType = 164, ThisType = 165, - StringLiteralType = 166, + LiteralType = 166, ObjectBindingPattern = 167, ArrayBindingPattern = 168, BindingElement = 169, @@ -301,10 +304,18 @@ declare namespace ts { JSDocTypedefTag = 279, JSDocPropertyTag = 280, JSDocTypeLiteral = 281, - SyntaxList = 282, - Count = 283, + JSDocLiteralType = 282, + JSDocNullKeyword = 283, + JSDocUndefinedKeyword = 284, + JSDocNeverKeyword = 285, + SyntaxList = 286, + NotEmittedStatement = 287, + PartiallyEmittedExpression = 288, + Count = 289, FirstAssignment = 56, LastAssignment = 68, + FirstCompoundAssignment = 57, + LastCompoundAssignment = 68, FirstReservedWord = 70, LastReservedWord = 105, FirstKeyword = 70, @@ -327,11 +338,44 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 139, FirstJSDocNode = 257, - LastJSDocNode = 281, + LastJSDocNode = 282, FirstJSDocTagNode = 273, - LastJSDocTagNode = 281, + LastJSDocTagNode = 285, } const enum NodeFlags { + None = 0, + Let = 1, + Const = 2, + NestedNamespace = 4, + Synthesized = 8, + Namespace = 16, + ExportContext = 32, + ContainsThis = 64, + HasImplicitReturn = 128, + HasExplicitReturn = 256, + GlobalAugmentation = 512, + HasClassExtends = 1024, + HasDecorators = 2048, + HasParamDecorators = 4096, + HasAsyncFunctions = 8192, + HasJsxSpreadAttributes = 16384, + DisallowInContext = 32768, + YieldContext = 65536, + DecoratorContext = 131072, + AwaitContext = 262144, + ThisNodeHasError = 524288, + JavaScriptFile = 1048576, + ThisNodeOrAnySubNodesHasError = 2097152, + HasAggregatedChildData = 4194304, + BlockScoped = 3, + ReachabilityCheckFlags = 384, + EmitHelperFlags = 31744, + ReachabilityAndEmitFlags = 32128, + ContextFlags = 1540096, + TypeExcludesFlags = 327680, + } + type ModifiersArray = NodeArray; + const enum ModifierFlags { None = 0, Export = 1, Ambient = 2, @@ -343,36 +387,11 @@ declare namespace ts { Abstract = 128, Async = 256, Default = 512, - Let = 1024, Const = 2048, - Namespace = 4096, - ExportContext = 8192, - ContainsThis = 16384, - HasImplicitReturn = 32768, - HasExplicitReturn = 65536, - GlobalAugmentation = 131072, - HasClassExtends = 262144, - HasDecorators = 524288, - HasParamDecorators = 1048576, - HasAsyncFunctions = 2097152, - DisallowInContext = 4194304, - YieldContext = 8388608, - DecoratorContext = 16777216, - AwaitContext = 33554432, - ThisNodeHasError = 67108864, - JavaScriptFile = 134217728, - ThisNodeOrAnySubNodesHasError = 268435456, - HasAggregatedChildData = 536870912, - HasJsxSpreadAttribute = 1073741824, - Modifier = 1023, + HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 92, - BlockScoped = 3072, - ReachabilityCheckFlags = 98304, - EmitHelperFlags = 3932160, - ReachabilityAndEmitFlags = 4030464, - ContextFlags = 197132288, - TypeExcludesFlags = 41943040, + NonPublicAccessibilityModifier = 24, } const enum JsxFlags { None = 0, @@ -388,28 +407,48 @@ declare namespace ts { interface Node extends TextRange { kind: SyntaxKind; flags: NodeFlags; + modifierFlagsCache?: ModifierFlags; + transformFlags?: TransformFlags; decorators?: NodeArray; modifiers?: ModifiersArray; id?: number; parent?: Node; - jsDocComments?: JSDocComment[]; + original?: Node; + startsOnNewLine?: boolean; + jsDocComments?: JSDoc[]; symbol?: Symbol; locals?: SymbolTable; nextContainer?: Node; localSymbol?: Symbol; flowNode?: FlowNode; + transformId?: number; + emitFlags?: NodeEmitFlags; + sourceMapRange?: TextRange; + commentRange?: TextRange; } - interface NodeArray extends Array, TextRange { + interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface ModifiersArray extends NodeArray { - flags: NodeFlags; + interface Token extends Node { + __tokenTag: any; } - interface Modifier extends Node { + interface Modifier extends Token { + } + const enum GeneratedIdentifierKind { + None = 0, + Auto = 1, + Loop = 2, + Unique = 3, + Node = 4, } interface Identifier extends PrimaryExpression { text: string; originalKeywordKind?: SyntaxKind; + autoGenerateKind?: GeneratedIdentifierKind; + autoGenerateId?: number; + } + interface TransientIdentifier extends Identifier { + resolvedSymbol: Symbol; } interface QualifiedName extends Node { left: EntityName; @@ -446,9 +485,10 @@ declare namespace ts { } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { } + type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { parent?: VariableDeclarationList; - name: Identifier | BindingPattern; + name: BindingName; type?: TypeNode; initializer?: Expression; } @@ -457,7 +497,7 @@ declare namespace ts { } interface ParameterDeclaration extends Declaration { dotDotDotToken?: Node; - name: Identifier | BindingPattern; + name: BindingName; questionToken?: Node; type?: TypeNode; initializer?: Expression; @@ -465,7 +505,7 @@ declare namespace ts { interface BindingElement extends Declaration { propertyName?: PropertyName; dotDotDotToken?: Node; - name: Identifier | BindingPattern; + name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { @@ -484,6 +524,7 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { _propertyAssignmentBrand: any; name: PropertyName; @@ -508,11 +549,14 @@ declare namespace ts { name: PropertyName; } interface BindingPattern extends Node { - elements: NodeArray; + elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + elements: NodeArray; } + type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + elements: NodeArray; } interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; @@ -592,17 +636,23 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { + interface LiteralTypeNode extends TypeNode { _stringLiteralTypeBrand: any; + literal: Expression; } interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; + textSourceNode?: Identifier | StringLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { + _omittedExpressionBrand: any; + } + interface PartiallyEmittedExpression extends LeftHandSideExpression { + expression: Expression; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -677,9 +727,14 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface NumericLiteral extends LiteralExpression { + _numericLiteralBrand: any; + trailingComment?: string; + } interface TemplateLiteralFragment extends LiteralLikeNode { _templateLiteralFragmentBrand: any; } + type Template = TemplateExpression | LiteralExpression; interface TemplateExpression extends PrimaryExpression { head: TemplateLiteralFragment; templateSpans: NodeArray; @@ -698,15 +753,22 @@ declare namespace ts { interface SpreadElementExpression extends Expression { expression: Expression; } - interface ObjectLiteralExpression extends PrimaryExpression, Declaration { - properties: NodeArray; + interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { multiLine?: boolean; } + type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; + type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; name: Identifier; } - type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; + interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { + _propertyAccessExpressionLikeQualifiedNameBrand?: any; + expression: EntityNameExpression; + } interface ElementAccessExpression extends MemberExpression { expression: LeftHandSideExpression; argumentExpression?: Expression; @@ -724,7 +786,7 @@ declare namespace ts { } interface TaggedTemplateExpression extends MemberExpression { tag: LeftHandSideExpression; - template: LiteralExpression | TemplateExpression; + template: Template; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { @@ -754,9 +816,10 @@ declare namespace ts { _selfClosingElementBrand?: any; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { name: Identifier; - initializer?: Expression; + initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { expression: Expression; @@ -774,6 +837,8 @@ declare namespace ts { interface Statement extends Node { _statementBrand: any; } + interface NotEmittedStatement extends Statement { + } interface EmptyStatement extends Statement { } interface DebuggerStatement extends Statement { @@ -784,6 +849,7 @@ declare namespace ts { type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { statements: NodeArray; + multiLine?: boolean; } interface VariableStatement extends Statement { declarationList: VariableDeclarationList; @@ -805,17 +871,18 @@ declare namespace ts { interface WhileStatement extends IterationStatement { expression: Expression; } + type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { - initializer?: VariableDeclarationList | Expression; + initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; + initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; + initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { @@ -901,7 +968,7 @@ declare namespace ts { type: TypeNode; } interface EnumMember extends Declaration { - name: DeclarationName; + name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { @@ -909,6 +976,7 @@ declare namespace ts { members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; + type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; body?: ModuleBlock | ModuleDeclaration; @@ -916,9 +984,10 @@ declare namespace ts { interface ModuleBlock extends Node, Statement { statements: NodeArray; } + type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { name: Identifier; - moduleReference: EntityName | ExternalModuleReference; + moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { expression?: Expression; @@ -927,9 +996,10 @@ declare namespace ts { importClause?: ImportClause; moduleSpecifier: Expression; } + type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { name?: Identifier; - namedBindings?: NamespaceImport | NamedImports; + namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { name: Identifier; @@ -997,7 +1067,7 @@ declare namespace ts { type: JSDocType; } interface JSDocRecordType extends JSDocType, TypeLiteralNode { - members: NodeArray; + literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { name: EntityName; @@ -1019,17 +1089,22 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } + interface JSDocLiteralType extends JSDocType { + literal: LiteralTypeNode; + } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; type?: JSDocType; } - interface JSDocComment extends Node { - tags: NodeArray; + interface JSDoc extends Node { + tags: NodeArray | undefined; + comment: string | undefined; } interface JSDocTag extends Node { atToken: Node; tagName: Identifier; + comment: string | undefined; } interface JSDocTemplateTag extends JSDocTag { typeParameters: NodeArray; @@ -1057,6 +1132,7 @@ declare namespace ts { preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; postParameterName?: Identifier; + parameterName: Identifier; isBracketed: boolean; } const enum FlowFlags { @@ -1097,6 +1173,11 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } interface AmdDependency { path: string; name: string; @@ -1132,6 +1213,7 @@ declare namespace ts { imports: LiteralExpression[]; moduleAugmentations: LiteralExpression[]; patternAmbientModules?: PatternAmbientModule[]; + externalHelpersModuleName?: Identifier; } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; @@ -1143,6 +1225,7 @@ declare namespace ts { useCaseSensitiveFileNames: boolean; readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; fileExists(path: string): boolean; + readFile(path: string): string; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1248,6 +1331,7 @@ declare namespace ts { getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; + getAmbientModules(): Symbol[]; getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver; @@ -1294,6 +1378,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, InFirstTypeArgument = 256, + InTypeAlias = 512, } const enum SymbolFormatFlags { None = 0, @@ -1334,18 +1419,19 @@ declare namespace ts { enum TypeReferenceSerializationKind { Unknown = 0, TypeWithConstructSignatureAndValue = 1, - VoidType = 2, + VoidNullableOrNeverType = 2, NumberLikeType = 3, StringLikeType = 4, BooleanType = 5, ArrayLikeType = 6, ESSymbolType = 7, - TypeWithCallSignature = 8, - ObjectType = 9, + Promise = 8, + TypeWithCallSignature = 9, + ObjectType = 10, } interface EmitResolver { hasGlobalName(name: string): boolean; - getReferencedExportContainer(node: Identifier): SourceFile | ModuleDeclaration | EnumDeclaration; + getReferencedExportContainer(node: Identifier, prefixLocals?: boolean): SourceFile | ModuleDeclaration | EnumDeclaration; getReferencedImportDeclaration(node: Identifier): Declaration; getReferencedDeclarationWithCollidingName(node: Identifier): Declaration; isDeclarationWithCollidingName(node: Declaration): boolean; @@ -1360,17 +1446,19 @@ declare namespace ts { writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; - isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult; - isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult; + isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; + isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; getReferencedValueDeclaration(reference: Identifier): Declaration; - getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind; + getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind; isOptionalParameter(node: ParameterDeclaration): boolean; moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean; isArgumentsLocalBinding(node: Identifier): boolean; getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile; - getTypeReferenceDirectivesForEntityName(name: EntityName | PropertyAccessExpression): string[]; + getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[]; getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[]; + isLiteralConstDeclaration(node: VariableDeclaration): boolean; + writeLiteralConstValue(node: VariableDeclaration, writer: SymbolWriter): void; } const enum SymbolFlags { None = 0, @@ -1408,18 +1496,18 @@ declare namespace ts { Enum = 384, Variable = 3, Value = 107455, - Type = 793056, - Namespace = 1536, + Type = 793064, + Namespace = 1920, Module = 1536, Accessor = 98304, FunctionScopedVariableExcludes = 107454, BlockScopedVariableExcludes = 107455, ParameterExcludes = 107455, PropertyExcludes = 0, - EnumMemberExcludes = 107455, + EnumMemberExcludes = 900095, FunctionExcludes = 106927, ClassExcludes = 899519, - InterfaceExcludes = 792960, + InterfaceExcludes = 792968, RegularEnumExcludes = 899327, ConstEnumExcludes = 899967, ValueModuleExcludes = 106639, @@ -1427,8 +1515,8 @@ declare namespace ts { MethodExcludes = 99263, GetAccessorExcludes = 41919, SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, + TypeParameterExcludes = 530920, + TypeAliasExcludes = 793064, AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, @@ -1455,6 +1543,8 @@ declare namespace ts { exportSymbol?: Symbol; constEnumOnlyModule?: boolean; isReferenced?: boolean; + isReplaceableByMethod?: boolean; + isAssigned?: boolean; } interface SymbolLinks { target?: Symbol; @@ -1466,6 +1556,8 @@ declare namespace ts { mapper?: TypeMapper; referenced?: boolean; containingType?: UnionOrIntersectionType; + hasCommonType?: boolean; + isDiscriminantProperty?: boolean; resolvedExports?: SymbolTable; exportsChecked?: boolean; isDeclarationWithCollidingName?: boolean; @@ -1474,9 +1566,7 @@ declare namespace ts { } interface TransientSymbol extends Symbol, SymbolLinks { } - interface SymbolTable { - [index: string]: Symbol; - } + type SymbolTable = Map; interface Pattern { prefix: string; suffix: string; @@ -1503,13 +1593,16 @@ declare namespace ts { ClassWithBodyScopedClassBinding = 524288, BodyScopedClassBinding = 1048576, NeedsLoopOutParameter = 2097152, + AssignmentsMarked = 4194304, + ClassWithConstructorReference = 8388608, + ConstructorReferenceInClass = 16777216, } interface NodeLinks { + flags?: NodeCheckFlags; resolvedType?: Type; resolvedSignature?: Signature; resolvedSymbol?: Symbol; resolvedIndexInfo?: IndexInfo; - flags?: NodeCheckFlags; enumMemberValue?: number; isVisible?: boolean; hasReportedStatementInAmbientContext?: boolean; @@ -1524,42 +1617,51 @@ declare namespace ts { String = 2, Number = 4, Boolean = 8, - Void = 16, - Undefined = 32, - Null = 64, - Enum = 128, - StringLiteral = 256, - TypeParameter = 512, - Class = 1024, - Interface = 2048, - Reference = 4096, - Tuple = 8192, - Union = 16384, - Intersection = 32768, - Anonymous = 65536, - Instantiated = 131072, - FromSignature = 262144, - ObjectLiteral = 524288, - FreshObjectLiteral = 1048576, - ContainsWideningType = 2097152, - ContainsObjectLiteral = 4194304, - ContainsAnyFunctionType = 8388608, - ESSymbol = 16777216, - ThisType = 33554432, - ObjectLiteralPatternWithComputedProperties = 67108864, - Never = 134217728, - Nullable = 96, - Falsy = 112, - Intrinsic = 150995071, - Primitive = 16777726, - StringLike = 258, - NumberLike = 132, - ObjectType = 80896, - UnionOrIntersection = 49152, - StructuredType = 130048, - Narrowable = 16908175, - RequiresWidening = 6291456, - PropagatingFlags = 14680064, + Enum = 16, + StringLiteral = 32, + NumberLiteral = 64, + BooleanLiteral = 128, + EnumLiteral = 256, + ESSymbol = 512, + Void = 1024, + Undefined = 2048, + Null = 4096, + Never = 8192, + TypeParameter = 16384, + Class = 32768, + Interface = 65536, + Reference = 131072, + Tuple = 262144, + Union = 524288, + Intersection = 1048576, + Anonymous = 2097152, + Instantiated = 4194304, + ObjectLiteral = 8388608, + FreshLiteral = 16777216, + ContainsWideningType = 33554432, + ContainsObjectLiteral = 67108864, + ContainsAnyFunctionType = 134217728, + ThisType = 268435456, + ObjectLiteralPatternWithComputedProperties = 536870912, + Nullable = 6144, + Literal = 480, + StringOrNumberLiteral = 96, + DefinitelyFalsy = 7392, + PossiblyFalsy = 7406, + Intrinsic = 16015, + Primitive = 8190, + StringLike = 34, + NumberLike = 340, + BooleanLike = 136, + EnumLike = 272, + ObjectType = 2588672, + UnionOrIntersection = 1572864, + StructuredType = 4161536, + StructuredOrTypeParameter = 4177920, + Narrowable = 4178943, + NotUnionOrUnit = 2589191, + RequiresWidening = 100663296, + PropagatingFlags = 234881024, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1567,12 +1669,22 @@ declare namespace ts { id: number; symbol?: Symbol; pattern?: DestructuringPattern; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; } interface IntrinsicType extends Type { intrinsicName: string; } - interface StringLiteralType extends Type { + interface LiteralType extends Type { text: string; + freshType?: LiteralType; + regularType?: LiteralType; + } + interface EnumType extends Type { + memberTypes: Map; + } + interface EnumLiteralType extends LiteralType { + baseType: EnumType & UnionType; } interface ObjectType extends Type { } @@ -1598,13 +1710,10 @@ declare namespace ts { interface GenericType extends InterfaceType, TypeReference { instantiations: Map; } - interface TupleType extends ObjectType { - elementTypes: Type[]; - } interface UnionOrIntersectionType extends Type { types: Type[]; - reducedType: Type; resolvedProperties: SymbolTable; + couldContainTypeParameters: boolean; } interface UnionType extends UnionOrIntersectionType { } @@ -1647,7 +1756,7 @@ declare namespace ts { resolvedReturnType: Type; minArgumentCount: number; hasRestParameter: boolean; - hasStringLiterals: boolean; + hasLiteralTypes: boolean; target?: Signature; mapper?: TypeMapper; unionSignatures?: Signature[]; @@ -1667,16 +1776,18 @@ declare namespace ts { interface TypeMapper { (t: TypeParameter): Type; mappedTypes?: Type[]; + targetTypes?: Type[]; instantiations?: Type[]; context?: InferenceContext; } interface TypeInferences { primary: Type[]; secondary: Type[]; + topLevel: boolean; isFixed: boolean; } interface InferenceContext { - typeParameters: TypeParameter[]; + signature: Signature; inferUnionTypes: boolean; inferences: TypeInferences[]; inferredTypes: Type[]; @@ -1720,7 +1831,7 @@ declare namespace ts { NodeJs = 2, } type RootPaths = string[]; - type PathSubstitutions = Map; + type PathSubstitutions = MapLike; type TsConfigOnlyOptions = RootPaths | PathSubstitutions; type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; interface CompilerOptions { @@ -1735,12 +1846,14 @@ declare namespace ts { declaration?: boolean; declarationDir?: string; diagnostics?: boolean; + extendedDiagnostics?: boolean; disableSizeLimit?: boolean; emitBOM?: boolean; emitDecoratorMetadata?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; help?: boolean; + importHelpers?: boolean; init?: boolean; inlineSourceMap?: boolean; inlineSources?: boolean; @@ -1860,7 +1973,7 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; - wildcardDirectories?: Map; + wildcardDirectories?: MapLike; } const enum WatchDirectoryFlags { None = 0, @@ -1868,7 +1981,7 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - wildcardDirectories: Map; + wildcardDirectories: MapLike; } interface CommandLineOptionBase { name: string; @@ -2027,6 +2140,7 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; realpath?(path: string): string; getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; } interface ResolvedModule { resolvedFileName: string; @@ -2050,7 +2164,6 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; - getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getDirectories(path: string): string[]; @@ -2059,6 +2172,87 @@ declare namespace ts { getNewLine(): string; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + getEnvironmentVariable?(name: string): string; + } + const enum TransformFlags { + None = 0, + TypeScript = 1, + ContainsTypeScript = 2, + Jsx = 4, + ContainsJsx = 8, + ES7 = 16, + ContainsES7 = 32, + ES6 = 64, + ContainsES6 = 128, + DestructuringAssignment = 256, + Generator = 512, + ContainsGenerator = 1024, + ContainsDecorators = 2048, + ContainsPropertyInitializer = 4096, + ContainsLexicalThis = 8192, + ContainsCapturedLexicalThis = 16384, + ContainsLexicalThisInComputedPropertyName = 32768, + ContainsDefaultValueAssignments = 65536, + ContainsParameterPropertyAssignments = 131072, + ContainsSpreadElementExpression = 262144, + ContainsComputedPropertyName = 524288, + ContainsBlockScopedBinding = 1048576, + ContainsBindingPattern = 2097152, + ContainsYield = 4194304, + ContainsHoistedDeclarationOrCompletion = 8388608, + HasComputedFlags = 536870912, + AssertTypeScript = 3, + AssertJsx = 12, + AssertES7 = 48, + AssertES6 = 192, + AssertGenerator = 1536, + NodeExcludes = 536871765, + ArrowFunctionExcludes = 550710101, + FunctionExcludes = 550726485, + ConstructorExcludes = 550593365, + MethodOrAccessorExcludes = 550593365, + ClassExcludes = 537590613, + ModuleExcludes = 546335573, + TypeExcludes = -3, + ObjectLiteralExcludes = 537430869, + ArrayLiteralOrCallOrNewExcludes = 537133909, + VariableDeclarationListExcludes = 538968917, + ParameterExcludes = 538968917, + TypeScriptClassSyntaxMask = 137216, + ES6FunctionSyntaxMask = 81920, + } + const enum NodeEmitFlags { + EmitEmitHelpers = 1, + EmitExportStar = 2, + EmitSuperHelper = 4, + EmitAdvancedSuperHelper = 8, + UMDDefine = 16, + SingleLine = 32, + AdviseOnEmitNode = 64, + NoSubstitution = 128, + CapturesThis = 256, + NoLeadingSourceMap = 512, + NoTrailingSourceMap = 1024, + NoSourceMap = 1536, + NoNestedSourceMaps = 2048, + NoTokenLeadingSourceMaps = 4096, + NoTokenTrailingSourceMaps = 8192, + NoTokenSourceMaps = 12288, + NoLeadingComments = 16384, + NoTrailingComments = 32768, + NoComments = 49152, + NoNestedComments = 65536, + ExportName = 131072, + LocalName = 262144, + Indented = 524288, + NoIndentation = 1048576, + AsyncFunctionBody = 2097152, + ReuseTempVariableScope = 4194304, + CustomPrologue = 8388608, + } + interface LexicalEnvironment { + startLexicalEnvironment(): void; + endLexicalEnvironment(): Statement[]; } interface TextSpan { start: number; @@ -2079,12 +2273,25 @@ declare namespace ts { _children: Node[]; } } +declare namespace ts { + const timestamp: () => number; +} +declare namespace ts.performance { + function mark(markName: string): void; + function measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + function getCount(markName: string): number; + function getDuration(measureName: string): number; + function forEachMeasure(cb: (measureName: string, duration: number) => void): void; + function enable(): void; + function disable(): void; +} declare namespace ts { const enum Ternary { False = 0, Maybe = 1, True = -1, } + function createMap(template?: MapLike): Map; function createFileMap(keyMapper?: (key: string) => string): FileMap; function toPath(fileName: string, basePath: string, getCanonicalFileName: (path: string) => string): Path; const enum Comparison { @@ -2092,37 +2299,59 @@ declare namespace ts { EqualTo = 0, GreaterThan = 1, } - function forEach(array: T[], callback: (element: T, index: number) => U): U; - function contains(array: T[], value: T, areEqual?: (a: T, b: T) => boolean): boolean; + function forEach(array: T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined; + function every(array: T[], callback: (element: T, index: number) => boolean): boolean; + function find(array: T[], predicate: (element: T, index: number) => boolean): T | undefined; + function findMap(array: T[], callback: (element: T, index: number) => U | undefined): U; + function contains(array: T[], value: T): boolean; function indexOf(array: T[], value: T): number; function indexOfAnyCharCode(text: string, charCodes: number[], start?: number): number; - function countWhere(array: T[], predicate: (x: T) => boolean): number; + function countWhere(array: T[], predicate: (x: T, i: number) => boolean): number; + function filter(array: T[], f: (x: T) => x is U): U[]; function filter(array: T[], f: (x: T) => boolean): T[]; + function removeWhere(array: T[], f: (x: T) => boolean): boolean; function filterMutate(array: T[], f: (x: T) => boolean): void; - function map(array: T[], f: (x: T) => U): U[]; + function map(array: T[], f: (x: T, i: number) => U): U[]; + function flatten(array: (T | T[])[]): T[]; + function flatMap(array: T[], mapfn: (x: T, i: number) => U | U[]): U[]; + function span(array: T[], f: (x: T, i: number) => boolean): [T[], T[]]; + function spanMap(array: T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[]; + function mapObject(object: MapLike, f: (key: string, x: T) => [string, U]): MapLike; function concatenate(array1: T[], array2: T[]): T[]; function deduplicate(array: T[], areEqual?: (a: T, b: T) => boolean): T[]; + function compact(array: T[]): T[]; function sum(array: any[], prop: string): number; function addRange(to: T[], from: T[]): void; function rangeEquals(array1: T[], array2: T[], pos: number, end: number): boolean; + function firstOrUndefined(array: T[]): T; + function singleOrUndefined(array: T[]): T; + function singleOrMany(array: T[]): T | T[]; function lastOrUndefined(array: T[]): T; function binarySearch(array: number[], value: number): number; - function reduceLeft(array: T[], f: (a: T, x: T) => T): T; - function reduceLeft(array: T[], f: (a: U, x: T) => U, initial: U): U; - function reduceRight(array: T[], f: (a: T, x: T) => T): T; - function reduceRight(array: T[], f: (a: U, x: T) => U, initial: U): U; - function hasProperty(map: Map, key: string): boolean; - function getKeys(map: Map): string[]; - function getProperty(map: Map, key: string): T; - function isEmpty(map: Map): boolean; - function clone(object: T): T; - function extend, T2 extends Map<{}>>(first: T1, second: T2): T1 & T2; - function forEachValue(map: Map, callback: (value: T) => U): U; - function forEachKey(map: Map, callback: (key: string) => U): U; - function lookUp(map: Map, key: string): T; - function copyMap(source: Map, target: Map): void; - function arrayToMap(array: T[], makeKey: (value: T) => string): Map; + function reduceLeft(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; + function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T): T; + function reduceRight(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; + function reduceRight(array: T[], f: (memo: T, value: T, i: number) => T): T; + function hasProperty(map: MapLike, key: string): boolean; + function getProperty(map: MapLike, key: string): T | undefined; + function getOwnKeys(map: MapLike): string[]; + function forEachProperty(map: Map, callback: (value: T, key: string) => U): U; + function someProperties(map: Map, predicate?: (value: T, key: string) => boolean): boolean; + function copyProperties(source: Map, target: MapLike): void; + function assign, T2, T3>(t: T1, arg1: T2, arg2: T3): T1 & T2 & T3; + function assign, T2>(t: T1, arg1: T2): T1 & T2; + function assign>(t: T1, ...args: any[]): any; function reduceProperties(map: Map, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; + function reduceOwnProperties(map: MapLike, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; + function equalOwnProperties(left: MapLike, right: MapLike, equalityComparer?: (left: T, right: T) => boolean): boolean; + function arrayToMap(array: T[], makeKey: (value: T) => string): Map; + function arrayToMap(array: T[], makeKey: (value: T) => string, makeValue: (value: T) => U): Map; + function isEmpty(map: Map): boolean; + function cloneMap(map: Map): Map; + function clone(object: T): T; + function extend(first: T1, second: T2): T1 & T2; + function multiMapAdd(map: Map, key: string, value: V): V[]; + function multiMapRemove(map: Map, key: string, value: V): void; function isArray(value: any): value is any[]; function memoize(callback: () => T): () => T; let localizedDiagnosticMessages: Map; @@ -2140,8 +2369,9 @@ declare namespace ts { function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[]; function normalizeSlashes(path: string): string; function getRootLength(path: string): number; - let directorySeparator: string; + const directorySeparator = "/"; function normalizePath(path: string): string; + function pathEndsWithDirectorySeparator(path: string): boolean; function getDirectoryPath(path: Path): Path; function getDirectoryPath(path: string): string; function isUrl(path: string): boolean; @@ -2156,6 +2386,8 @@ declare namespace ts { function ensureTrailingDirectorySeparator(path: string): string; function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; + function startsWith(str: string, prefix: string): boolean; + function endsWith(str: string, suffix: string): boolean; function fileExtensionIs(path: string, extension: string): boolean; function fileExtensionIsAny(path: string, extensions: string[]): boolean; function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude"): string; @@ -2174,6 +2406,7 @@ declare namespace ts { function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind; function getScriptKindFromFileName(fileName: string): ScriptKind; const supportedTypeScriptExtensions: string[]; + const supportedTypescriptExtensionsForExtractExtension: string[]; const supportedJavascriptExtensions: string[]; function getSupportedExtensions(options?: CompilerOptions): string[]; function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; @@ -2188,11 +2421,14 @@ declare namespace ts { function adjustExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; function removeFileExtension(path: string): string; - function tryRemoveExtension(path: string, extension: string): string; + function tryRemoveExtension(path: string, extension: string): string | undefined; + function removeExtension(path: string, extension: string): string; function isJsxOrTsxExtension(ext: string): boolean; function changeExtension(path: T, newExtension: string): T; interface ObjectAllocator { getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; + getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; + getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; @@ -2210,8 +2446,11 @@ declare namespace ts { function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void; function fail(message?: string): void; } - function copyListRemovingItem(item: T, list: T[]): T[]; - function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; + function getEnvironmentVariable(name: string, host?: CompilerHost): string; + function orderedRemoveItemAt(array: T[], index: number): void; + function unorderedRemoveItemAt(array: T[], index: number): void; + function unorderedRemoveItem(array: T[], item: T): void; + function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string; } declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; @@ -2244,6 +2483,8 @@ declare namespace ts { getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; + getEnvironmentVariable(name: string): string; + tryEnableSourceMapsForHost?(): void; } interface FileWatcher { close(): void; @@ -3486,6 +3727,12 @@ declare namespace ts { key: string; message: string; }; + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; with_statements_are_not_allowed_in_an_async_function_block: { code: number; category: DiagnosticCategory; @@ -3498,12 +3745,6 @@ declare namespace ts { key: string; message: string; }; - Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: number; category: DiagnosticCategory; @@ -3828,7 +4069,7 @@ declare namespace ts { key: string; message: string; }; - Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: number; category: DiagnosticCategory; key: string; @@ -3858,12 +4099,6 @@ declare namespace ts { key: string; message: string; }; - No_best_common_type_exists_among_return_expressions: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: number; category: DiagnosticCategory; @@ -4710,12 +4945,6 @@ declare namespace ts { key: string; message: string; }; - No_best_common_type_exists_among_yield_expressions: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; A_generator_cannot_have_a_void_type_annotation: { code: number; category: DiagnosticCategory; @@ -4812,7 +5041,7 @@ declare namespace ts { key: string; message: string; }; - The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: number; category: DiagnosticCategory; key: string; @@ -4890,6 +5119,12 @@ declare namespace ts { key: string; message: string; }; + Enum_type_0_has_members_with_initializers_that_are_not_literals: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; JSX_element_attributes_type_0_may_not_be_a_union_type: { code: number; category: DiagnosticCategory; @@ -5172,6 +5407,48 @@ declare namespace ts { key: string; message: string; }; + A_class_must_be_declared_after_its_base_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Namespace_0_has_no_exported_member_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Import_declaration_0_is_using_private_name_1: { code: number; category: DiagnosticCategory; @@ -5592,7 +5869,7 @@ declare namespace ts { key: string; message: string; }; - Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: number; category: DiagnosticCategory; key: string; @@ -5760,6 +6037,12 @@ declare namespace ts { key: string; message: string; }; + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Concatenate_and_emit_output_to_single_file: { code: number; category: DiagnosticCategory; @@ -5940,6 +6223,12 @@ declare namespace ts { key: string; message: string; }; + STRATEGY: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Compilation_complete_Watching_for_file_changes: { code: number; category: DiagnosticCategory; @@ -6456,13 +6745,13 @@ declare namespace ts { key: string; message: string; }; - Report_Errors_on_Unused_Locals: { + Report_errors_on_unused_locals: { code: number; category: DiagnosticCategory; key: string; message: string; }; - Report_Errors_on_Unused_Parameters: { + Report_errors_on_unused_parameters: { code: number; category: DiagnosticCategory; key: string; @@ -6480,6 +6769,18 @@ declare namespace ts { key: string; message: string; }; + Property_0_is_declared_but_never_used: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Import_emit_helpers_from_tslib: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Variable_0_implicitly_has_an_1_type: { code: number; category: DiagnosticCategory; @@ -6528,12 +6829,6 @@ declare namespace ts { key: string; message: string; }; - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Index_signature_of_object_type_implicitly_has_an_any_type: { code: number; category: DiagnosticCategory; @@ -6618,6 +6913,18 @@ declare namespace ts { key: string; message: string; }; + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; You_cannot_rename_this_element: { code: number; category: DiagnosticCategory; @@ -6786,6 +7093,18 @@ declare namespace ts { key: string; message: string; }; + Circularity_detected_while_resolving_configuration_Colon_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + The_path_in_an_extends_options_must_be_relative_or_rooted: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; }; } declare namespace ts { @@ -6809,6 +7128,7 @@ declare namespace ts { reScanSlashToken(): SyntaxKind; reScanTemplateToken(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; + scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; scanJSDocToken(): SyntaxKind; @@ -6841,12 +7161,16 @@ declare namespace ts { function isOctalDigit(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments?: boolean): number; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; function getShebang(text: string): string; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifier(name: string, languageVersion: ScriptTarget): boolean; + function isIdentifierText(name: string, languageVersion: ScriptTarget): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { @@ -6856,9 +7180,10 @@ declare namespace ts { optionNameMap: Map; shortOptionNames: Map; } + const defaultInitCompilerOptions: CompilerOptions; function getOptionNameMap(): OptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic; - function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]): number | string; + function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]): string | number; function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] | undefined; function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; function readConfigFile(fileName: string, readFile: (path: string) => string): { @@ -6869,7 +7194,10 @@ declare namespace ts { config?: any; error?: Diagnostic; }; - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; + function generateTSConfig(options: CompilerOptions, fileNames: string[]): { + compilerOptions: Map; + }; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -6880,17 +7208,13 @@ declare namespace ts { }; } declare namespace ts { + const externalHelpersModuleNameText = "tslib"; interface ReferencePathMatchResult { fileReference?: FileReference; diagnosticMessage?: DiagnosticMessage; isNoDefaultLib?: boolean; isTypeReferenceDirective?: boolean; } - interface SynthesizedNode extends Node { - leadingCommentRanges?: CommentRange[]; - trailingCommentRanges?: CommentRange[]; - startsOnNewLine: boolean; - } function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration; interface StringSymbolWriter extends SymbolWriter { string(): string; @@ -6907,7 +7231,6 @@ declare namespace ts { function getSingleLineStringWriter(): StringSymbolWriter; function releaseStringWriter(writer: StringSymbolWriter): void; function getFullWidth(node: Node): number; - function mapIsEqualTo(map1: Map, map2: Map): boolean; function arrayIsEqualTo(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean; function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean; function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule; @@ -6922,24 +7245,29 @@ declare namespace ts { function getStartPositionOfLine(line: number, sourceFile: SourceFile): number; function nodePosToString(node: Node): string; function getStartPosOfNode(node: Node): number; + function isDefined(value: any): boolean; function getEndLinePosition(line: number, sourceFile: SourceFile): number; function nodeIsMissing(node: Node): boolean; function nodeIsPresent(node: Node): boolean; function getTokenPosOfNode(node: Node, sourceFile?: SourceFile, includeJsDocComment?: boolean): number; function isJSDocNode(node: Node): boolean; + function isJSDocTag(node: Node): boolean; function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFile): number; function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia?: boolean): string; function getTextOfNodeFromSourceText(sourceText: string, node: Node): string; function getTextOfNode(node: Node, includeTrivia?: boolean): string; + function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, languageVersion: ScriptTarget): string; + function isBinaryOrOctalIntegerLiteral(node: LiteralLikeNode, text: string): boolean; function escapeIdentifier(identifier: string): string; function unescapeIdentifier(identifier: string): string; function makeIdentifierFromModuleName(moduleName: string): string; function isBlockOrCatchScoped(declaration: Declaration): boolean; function isAmbientModule(node: Node): boolean; - function isShorthandAmbientModule(node: Node): boolean; + function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean; function isBlockScopedContainerTopLevel(node: Node): boolean; function isGlobalScopeAugmentation(module: ModuleDeclaration): boolean; function isExternalModuleAugmentation(node: Node): boolean; + function isBlockScope(node: Node, parentNode: Node): boolean; function getEnclosingBlockScopeContainer(node: Node): Node; function isCatchClauseVariableDeclaration(declaration: Declaration): boolean; function declarationNameToString(name: DeclarationName): string; @@ -6950,7 +7278,6 @@ declare namespace ts { function isExternalOrCommonJsModule(file: SourceFile): boolean; function isDeclarationFile(file: SourceFile): boolean; function isConstEnumDeclaration(node: Node): boolean; - function getCombinedNodeFlags(node: Node): NodeFlags; function isConst(node: Node): boolean; function isLet(node: Node): boolean; function isSuperCallExpression(n: Node): boolean; @@ -6962,7 +7289,7 @@ declare namespace ts { let fullTripleSlashReferencePathRegEx: RegExp; let fullTripleSlashReferenceTypeReferenceDirectiveRegEx: RegExp; let fullTripleSlashAMDReferencePathRegEx: RegExp; - function isTypeNode(node: Node): boolean; + function isPartOfTypeNode(node: Node): boolean; function forEachReturnStatement(body: Block, visitor: (stmt: ReturnStatement) => T): T; function forEachYieldExpression(body: Block, visitor: (expr: YieldExpression) => void): void; function isVariableLike(node: Node): node is VariableLikeDeclaration; @@ -6971,7 +7298,7 @@ declare namespace ts { function isFunctionLike(node: Node): node is FunctionLikeDeclaration; function isFunctionLikeKind(kind: SyntaxKind): boolean; function introducesArgumentsExoticObject(node: Node): boolean; - function isIterationStatement(node: Node, lookInLabeledStatements: boolean): boolean; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; function isFunctionBlock(node: Node): boolean; function isObjectLiteralMethod(node: Node): node is MethodDeclaration; function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate; @@ -6981,15 +7308,16 @@ declare namespace ts { function getThisContainer(node: Node, includeArrowFunctions: boolean): Node; function getSuperContainer(node: Node, stopOnFunctions: boolean): Node; function getImmediatelyInvokedFunctionExpression(func: Node): CallExpression; - function isSuperPropertyOrElementAccess(node: Node): boolean; - function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression; + function isSuperProperty(node: Node): node is (PropertyAccessExpression | ElementAccessExpression); + function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression; + function isCallLikeExpression(node: Node): node is CallLikeExpression; function getInvokedExpression(node: CallLikeExpression): Expression; function nodeCanBeDecorated(node: Node): boolean; function nodeIsDecorated(node: Node): boolean; - function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; - function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function nodeOrChildIsDecorated(node: Node): boolean; + function childIsDecorated(node: Node): boolean; function isJSXTagName(node: Node): boolean; - function isExpression(node: Node): boolean; + function isPartOfExpression(node: Node): boolean; function isExternalModuleNameRelative(moduleName: string): boolean; function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; function isExternalModuleImportEqualsDeclaration(node: Node): boolean; @@ -7002,8 +7330,11 @@ declare namespace ts { function isDeclarationOfFunctionExpression(s: Symbol): boolean; function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind; function getExternalModuleName(node: Node): Expression; + function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): NamespaceImport; + function isDefaultImport(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean; function hasQuestionToken(node: Node): boolean; function isJSDocConstructSignature(node: Node): boolean; + function getJSDocComments(node: Node, checkParentVariableStatement: boolean): string[]; function getJSDocTypeTag(node: Node): JSDocTypeTag; function getJSDocReturnTag(node: Node): JSDocReturnTag; function getJSDocTemplateTag(node: Node): JSDocTemplateTag; @@ -7012,20 +7343,14 @@ declare namespace ts { function hasDeclaredRestParameter(s: SignatureDeclaration): boolean; function isRestParameter(node: ParameterDeclaration): boolean; function isDeclaredRestParam(node: ParameterDeclaration): boolean; - function isLiteralKind(kind: SyntaxKind): boolean; - function isTextualLiteralKind(kind: SyntaxKind): boolean; - function isTemplateLiteralKind(kind: SyntaxKind): boolean; - function isBindingPattern(node: Node): node is BindingPattern; function isAssignmentTarget(node: Node): boolean; - function isNodeDescendentOf(node: Node, ancestor: Node): boolean; + function isNodeDescendantOf(node: Node, ancestor: Node): boolean; function isInAmbientContext(node: Node): boolean; - function isDeclaration(node: Node): boolean; - function isStatement(n: Node): boolean; - function isClassElement(n: Node): boolean; function isDeclarationName(name: Node): boolean; function isLiteralComputedPropertyDeclarationName(node: Node): boolean; function isIdentifierName(node: Identifier): boolean; function isAliasSymbolDeclaration(node: Node): boolean; + function exportAssignmentIsAlias(node: ExportAssignment): boolean; function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments; function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration): NodeArray; function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray; @@ -7046,13 +7371,24 @@ declare namespace ts { function isModifierKind(token: SyntaxKind): boolean; function isParameterDeclaration(node: VariableLikeDeclaration): boolean; function getRootDeclaration(node: Node): Node; - function nodeStartsNewLexicalEnvironment(n: Node): boolean; - function cloneNode(node: T, location?: TextRange, flags?: NodeFlags, parent?: Node): T; - function cloneEntityName(node: EntityName, parent?: Node): EntityName; - function isQualifiedName(node: Node): node is QualifiedName; - function nodeIsSynthesized(node: Node): boolean; - function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node; - function createSynthesizedNodeArray(): NodeArray; + function nodeStartsNewLexicalEnvironment(node: Node): boolean; + function nodeIsSynthesized(node: TextRange): boolean; + function positionIsSynthesized(pos: number): boolean; + function getOriginalNode(node: Node): Node; + function isParseTreeNode(node: Node): boolean; + function getParseTreeNode(node: Node): Node; + function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; + function getOriginalSourceFiles(sourceFiles: SourceFile[]): SourceFile[]; + function getOriginalNodeId(node: Node): number; + const enum Associativity { + Left = 0, + Right = 1, + } + function getExpressionAssociativity(expression: Expression): Associativity; + function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, hasArguments?: boolean): Associativity; + function getExpressionPrecedence(expression: Expression): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; + function getOperator(expression: Expression): SyntaxKind; + function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; function createDiagnosticCollection(): DiagnosticCollection; function escapeString(s: string): string; function isIntrinsicJsxName(name: string): boolean; @@ -7070,11 +7406,14 @@ declare namespace ts { getLine(): number; getColumn(): number; getIndent(): number; + isAtStartOfLine(): boolean; reset(): void; } function getIndentString(level: number): string; function getIndentSize(): number; function createTextWriter(newLine: String): EmitTextWriter; + function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string; + function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string; function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string; function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string; function getDeclarationEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost): string; @@ -7085,6 +7424,8 @@ declare namespace ts { sourceMapFilePath: string; declarationFilePath: string; } + function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): SourceFile[]; + function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void): void; function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile): void; function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string; function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]): void; @@ -7092,33 +7433,149 @@ declare namespace ts { function getLineOfLocalPositionFromLineMap(lineMap: number[], pos: number): number; function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration; function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode; - function getAllAccessorDeclarations(declarations: NodeArray, accessor: AccessorDeclaration): { + interface AllAccessorDeclarations { firstAccessor: AccessorDeclaration; secondAccessor: AccessorDeclaration; getAccessor: AccessorDeclaration; setAccessor: AccessorDeclaration; - }; + } + function getAllAccessorDeclarations(declarations: NodeArray, accessor: AccessorDeclaration): AllAccessorDeclarations; function emitNewLineBeforeLeadingComments(lineMap: number[], writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]): void; - function emitComments(text: string, lineMap: number[], writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string, writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) => void): void; - function emitDetachedComments(text: string, lineMap: number[], writer: EmitTextWriter, writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean): { + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: number[], writer: EmitTextWriter, pos: number, leadingComments: CommentRange[]): void; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap: number[], writer: EmitTextWriter, pos: number, commentPos: number): void; + function emitComments(text: string, lineMap: number[], writer: EmitTextWriter, comments: CommentRange[], leadingSeparator: boolean, trailingSeparator: boolean, newLine: string, writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void): void; + function emitDetachedComments(text: string, lineMap: number[], writer: EmitTextWriter, writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean): { nodePos: number; detachedCommentEndPos: number; }; - function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string): void; - function modifierToFlag(token: SyntaxKind): NodeFlags; - function isLeftHandSideExpression(expr: Expression): boolean; + function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string): void; + function hasModifiers(node: Node): boolean; + function hasModifier(node: Node, flags: ModifierFlags): boolean; + function getModifierFlags(node: Node): ModifierFlags; + function modifierToFlag(token: SyntaxKind): ModifierFlags; + function isLogicalOperator(token: SyntaxKind): boolean; function isAssignmentOperator(token: SyntaxKind): boolean; - function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean; + function tryGetClassExtendingExpressionWithTypeArguments(node: Node): ClassLikeDeclaration | undefined; + function isDestructuringAssignment(node: Node): node is BinaryExpression; function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean; + function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean; + function isEntityNameExpression(node: Expression): node is EntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean; function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; function hasJavaScriptFileExtension(fileName: string): boolean; function hasTypeScriptFileExtension(fileName: string): boolean; + function tryExtractTypeScriptExtension(fileName: string): string | undefined; const stringify: (value: any) => string; function convertToBase64(input: string): string; function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; function getNewLineCharacter(options: CompilerOptions): string; + function isSimpleExpression(node: Expression): boolean; + function formatSyntaxKind(kind: SyntaxKind): string; + function movePos(pos: number, value: number): number; + function createRange(pos: number, end: number): TextRange; + function moveRangeEnd(range: TextRange, end: number): TextRange; + function moveRangePos(range: TextRange, pos: number): TextRange; + function moveRangePastDecorators(node: Node): TextRange; + function moveRangePastModifiers(node: Node): TextRange; + function isCollapsedRange(range: TextRange): boolean; + function collapseRangeToStart(range: TextRange): TextRange; + function collapseRangeToEnd(range: TextRange): TextRange; + function createTokenRange(pos: number, token: SyntaxKind): TextRange; + function rangeIsOnSingleLine(range: TextRange, sourceFile: SourceFile): boolean; + function rangeStartPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; + function rangeEndPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; + function rangeStartIsOnSameLineAsRangeEnd(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; + function rangeEndIsOnSameLineAsRangeStart(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; + function positionsAreOnSameLine(pos1: number, pos2: number, sourceFile: SourceFile): boolean; + function getStartPositionOfRange(range: TextRange, sourceFile: SourceFile): number; + function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver): { + externalImports: (ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration)[]; + exportSpecifiers: Map; + exportEquals: ExportAssignment; + hasExportStarsToExportValues: boolean; + }; + function getInitializedVariables(node: VariableDeclarationList): VariableDeclaration[]; + function isMergedWithClass(node: Node): boolean; + function isFirstDeclarationOfKind(node: Node, kind: SyntaxKind): boolean; + function isNodeArray(array: T[]): array is NodeArray; + function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isLiteralKind(kind: SyntaxKind): boolean; + function isTextualLiteralKind(kind: SyntaxKind): boolean; + function isLiteralExpression(node: Node): node is LiteralExpression; + function isTemplateLiteralKind(kind: SyntaxKind): boolean; + function isTemplateLiteralFragment(node: Node): node is TemplateLiteralFragment; + function isIdentifier(node: Node): node is Identifier; + function isGeneratedIdentifier(node: Node): boolean; + function isModifier(node: Node): node is Modifier; + function isQualifiedName(node: Node): node is QualifiedName; + function isComputedPropertyName(node: Node): node is ComputedPropertyName; + function isEntityName(node: Node): node is EntityName; + function isPropertyName(node: Node): node is PropertyName; + function isModuleName(node: Node): node is ModuleName; + function isBindingName(node: Node): node is BindingName; + function isTypeParameter(node: Node): node is TypeParameterDeclaration; + function isParameter(node: Node): node is ParameterDeclaration; + function isDecorator(node: Node): node is Decorator; + function isMethodDeclaration(node: Node): node is MethodDeclaration; + function isClassElement(node: Node): node is ClassElement; + function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + function isTypeNode(node: Node): node is TypeNode; + function isBindingPattern(node: Node): node is BindingPattern; + function isBindingElement(node: Node): node is BindingElement; + function isArrayBindingElement(node: Node): node is ArrayBindingElement; + function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; + function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function isBinaryExpression(node: Node): node is BinaryExpression; + function isConditionalExpression(node: Node): node is ConditionalExpression; + function isCallExpression(node: Node): node is CallExpression; + function isTemplate(node: Node): node is Template; + function isSpreadElementExpression(node: Node): node is SpreadElementExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression; + function isUnaryExpression(node: Node): node is UnaryExpression; + function isExpression(node: Node): node is Expression; + function isAssertionExpression(node: Node): node is AssertionExpression; + function isPartiallyEmittedExpression(node: Node): node is PartiallyEmittedExpression; + function isNotEmittedStatement(node: Node): node is NotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node: Node): node is NotEmittedStatement | PartiallyEmittedExpression; + function isOmittedExpression(node: Node): node is OmittedExpression; + function isTemplateSpan(node: Node): node is TemplateSpan; + function isBlock(node: Node): node is Block; + function isConciseBody(node: Node): node is ConciseBody; + function isFunctionBody(node: Node): node is FunctionBody; + function isForInitializer(node: Node): node is ForInitializer; + function isVariableDeclaration(node: Node): node is VariableDeclaration; + function isVariableDeclarationList(node: Node): node is VariableDeclarationList; + function isCaseBlock(node: Node): node is CaseBlock; + function isModuleBody(node: Node): node is ModuleBody; + function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; + function isImportClause(node: Node): node is ImportClause; + function isNamedImportBindings(node: Node): node is NamedImportBindings; + function isImportSpecifier(node: Node): node is ImportSpecifier; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; + function isModuleOrEnumDeclaration(node: Node): node is ModuleDeclaration | EnumDeclaration; + function isDeclaration(node: Node): node is Declaration; + function isDeclarationStatement(node: Node): node is DeclarationStatement; + function isStatementButNotDeclaration(node: Node): node is Statement; + function isStatement(node: Node): node is Statement; + function isModuleReference(node: Node): node is ModuleReference; + function isJsxOpeningElement(node: Node): node is JsxOpeningElement; + function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxTagNameExpression(node: Node): node is JsxTagNameExpression; + function isJsxChild(node: Node): node is JsxChild; + function isJsxAttributeLike(node: Node): node is JsxAttributeLike; + function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; + function isJsxAttribute(node: Node): node is JsxAttribute; + function isStringLiteralOrJsxExpression(node: Node): node is StringLiteral | JsxExpression; + function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + function isHeritageClause(node: Node): node is HeritageClause; + function isCatchClause(node: Node): node is CatchClause; + function isPropertyAssignment(node: Node): node is PropertyAssignment; + function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; + function isEnumMember(node: Node): node is EnumMember; + function isSourceFile(node: Node): node is SourceFile; function isWatchSet(options: CompilerOptions): boolean; } declare namespace ts { @@ -7143,18 +7600,274 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; - function startsWith(str: string, prefix: string): boolean; - function endsWith(str: string, suffix: string): boolean; + function getCombinedModifierFlags(node: Node): ModifierFlags; + function getCombinedNodeFlags(node: Node): NodeFlags; +} +declare namespace ts { + function updateNode(updated: T, original: T): T; + function createNodeArray(elements?: T[], location?: TextRange, hasTrailingComma?: boolean): NodeArray; + function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node; + function createSynthesizedNodeArray(elements?: T[]): NodeArray; + function getSynthesizedClone(node: T): T; + function getMutableClone(node: T): T; + function createLiteral(textSource: StringLiteral | Identifier, location?: TextRange): StringLiteral; + function createLiteral(value: string, location?: TextRange): StringLiteral; + function createLiteral(value: number, location?: TextRange): NumericLiteral; + function createLiteral(value: string | number | boolean, location?: TextRange): PrimaryExpression; + function createIdentifier(text: string, location?: TextRange): Identifier; + function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, location?: TextRange): Identifier; + function createLoopVariable(location?: TextRange): Identifier; + function createUniqueName(text: string, location?: TextRange): Identifier; + function getGeneratedNameForNode(node: Node, location?: TextRange): Identifier; + function createToken(token: SyntaxKind): Node; + function createSuper(): PrimaryExpression; + function createThis(location?: TextRange): PrimaryExpression; + function createNull(): PrimaryExpression; + function createComputedPropertyName(expression: Expression, location?: TextRange): ComputedPropertyName; + function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; + function createParameter(name: string | Identifier | BindingPattern, initializer?: Expression, location?: TextRange): ParameterDeclaration; + function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: Node, name: string | Identifier | BindingPattern, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags): ParameterDeclaration; + function updateParameterDeclaration(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], name: BindingName, type: TypeNode, initializer: Expression): ParameterDeclaration; + function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange): PropertyDeclaration; + function updateProperty(node: PropertyDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, type: TypeNode, initializer: Expression): PropertyDeclaration; + function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): MethodDeclaration; + function updateMethod(node: MethodDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): MethodDeclaration; + function createConstructor(decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block, location?: TextRange, flags?: NodeFlags): ConstructorDeclaration; + function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block): ConstructorDeclaration; + function createGetAccessor(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): GetAccessorDeclaration; + function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode, body: Block): GetAccessorDeclaration; + function createSetAccessor(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, parameters: ParameterDeclaration[], body: Block, location?: TextRange, flags?: NodeFlags): SetAccessorDeclaration; + function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, parameters: ParameterDeclaration[], body: Block): SetAccessorDeclaration; + function createObjectBindingPattern(elements: BindingElement[], location?: TextRange): ObjectBindingPattern; + function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; + function createArrayBindingPattern(elements: ArrayBindingElement[], location?: TextRange): ArrayBindingPattern; + function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ArrayBindingElement[]): ArrayBindingPattern; + function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: Node, name: string | BindingName, initializer?: Expression, location?: TextRange): BindingElement; + function updateBindingElement(node: BindingElement, propertyName: PropertyName, name: BindingName, initializer: Expression): BindingElement; + function createArrayLiteral(elements?: Expression[], location?: TextRange, multiLine?: boolean): ArrayLiteralExpression; + function updateArrayLiteral(node: ArrayLiteralExpression, elements: Expression[]): ArrayLiteralExpression; + function createObjectLiteral(properties?: ObjectLiteralElementLike[], location?: TextRange, multiLine?: boolean): ObjectLiteralExpression; + function updateObjectLiteral(node: ObjectLiteralExpression, properties: ObjectLiteralElementLike[]): ObjectLiteralExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier, location?: TextRange, flags?: NodeFlags): PropertyAccessExpression; + function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; + function createElementAccess(expression: Expression, index: number | Expression, location?: TextRange): ElementAccessExpression; + function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; + function createCall(expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[], location?: TextRange, flags?: NodeFlags): CallExpression; + function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): CallExpression; + function createNew(expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[], location?: TextRange, flags?: NodeFlags): NewExpression; + function updateNew(node: NewExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): NewExpression; + function createTaggedTemplate(tag: Expression, template: Template, location?: TextRange): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: Template): TaggedTemplateExpression; + function createParen(expression: Expression, location?: TextRange): ParenthesizedExpression; + function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; + function createFunctionExpression(asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionExpression; + function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: Node, body: ConciseBody, location?: TextRange, flags?: NodeFlags): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: ConciseBody): ArrowFunction; + function createDelete(expression: Expression, location?: TextRange): DeleteExpression; + function updateDelete(node: DeleteExpression, expression: Expression): Expression; + function createTypeOf(expression: Expression, location?: TextRange): TypeOfExpression; + function updateTypeOf(node: TypeOfExpression, expression: Expression): Expression; + function createVoid(expression: Expression, location?: TextRange): VoidExpression; + function updateVoid(node: VoidExpression, expression: Expression): VoidExpression; + function createAwait(expression: Expression, location?: TextRange): AwaitExpression; + function updateAwait(node: AwaitExpression, expression: Expression): AwaitExpression; + function createPrefix(operator: SyntaxKind, operand: Expression, location?: TextRange): PrefixUnaryExpression; + function updatePrefix(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; + function createPostfix(operand: Expression, operator: SyntaxKind, location?: TextRange): PostfixUnaryExpression; + function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; + function createBinary(left: Expression, operator: SyntaxKind | Node, right: Expression, location?: TextRange): BinaryExpression; + function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; + function createConditional(condition: Expression, questionToken: Node, whenTrue: Expression, colonToken: Node, whenFalse: Expression, location?: TextRange): ConditionalExpression; + function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + function createTemplateExpression(head: TemplateLiteralFragment, templateSpans: TemplateSpan[], location?: TextRange): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateLiteralFragment, templateSpans: TemplateSpan[]): TemplateExpression; + function createYield(asteriskToken: Node, expression: Expression, location?: TextRange): YieldExpression; + function updateYield(node: YieldExpression, expression: Expression): YieldExpression; + function createSpread(expression: Expression, location?: TextRange): SpreadElementExpression; + function updateSpread(node: SpreadElementExpression, expression: Expression): SpreadElementExpression; + function createClassExpression(modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[], location?: TextRange): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; + function createOmittedExpression(location?: TextRange): OmittedExpression; + function createExpressionWithTypeArguments(typeArguments: TypeNode[], expression: Expression, location?: TextRange): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; + function createTemplateSpan(expression: Expression, literal: TemplateLiteralFragment, location?: TextRange): TemplateSpan; + function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateLiteralFragment): TemplateSpan; + function createBlock(statements: Statement[], location?: TextRange, multiLine?: boolean, flags?: NodeFlags): Block; + function updateBlock(node: Block, statements: Statement[]): Block; + function createVariableStatement(modifiers: Modifier[], declarationList: VariableDeclarationList | VariableDeclaration[], location?: TextRange, flags?: NodeFlags): VariableStatement; + function updateVariableStatement(node: VariableStatement, modifiers: Modifier[], declarationList: VariableDeclarationList): VariableStatement; + function createVariableDeclarationList(declarations: VariableDeclaration[], location?: TextRange, flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList; + function createVariableDeclaration(name: string | BindingPattern | Identifier, type?: TypeNode, initializer?: Expression, location?: TextRange, flags?: NodeFlags): VariableDeclaration; + function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode, initializer: Expression): VariableDeclaration; + function createEmptyStatement(location: TextRange): EmptyStatement; + function createStatement(expression: Expression, location?: TextRange, flags?: NodeFlags): ExpressionStatement; + function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; + function createIf(expression: Expression, thenStatement: Statement, elseStatement?: Statement, location?: TextRange): IfStatement; + function updateIf(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement): IfStatement; + function createDo(statement: Statement, expression: Expression, location?: TextRange): DoStatement; + function updateDo(node: DoStatement, statement: Statement, expression: Expression): DoStatement; + function createWhile(expression: Expression, statement: Statement, location?: TextRange): WhileStatement; + function updateWhile(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement; + function createFor(initializer: ForInitializer, condition: Expression, incrementor: Expression, statement: Statement, location?: TextRange): ForStatement; + function updateFor(node: ForStatement, initializer: ForInitializer, condition: Expression, incrementor: Expression, statement: Statement): ForStatement; + function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForInStatement; + function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function createForOf(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForOfStatement; + function updateForOf(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; + function createContinue(label?: Identifier, location?: TextRange): BreakStatement; + function updateContinue(node: ContinueStatement, label: Identifier): BreakStatement; + function createBreak(label?: Identifier, location?: TextRange): BreakStatement; + function updateBreak(node: BreakStatement, label: Identifier): BreakStatement; + function createReturn(expression?: Expression, location?: TextRange): ReturnStatement; + function updateReturn(node: ReturnStatement, expression: Expression): ReturnStatement; + function createWith(expression: Expression, statement: Statement, location?: TextRange): WithStatement; + function updateWith(node: WithStatement, expression: Expression, statement: Statement): WithStatement; + function createSwitch(expression: Expression, caseBlock: CaseBlock, location?: TextRange): SwitchStatement; + function updateSwitch(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement; + function createLabel(label: string | Identifier, statement: Statement, location?: TextRange): LabeledStatement; + function updateLabel(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement; + function createThrow(expression: Expression, location?: TextRange): ThrowStatement; + function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement; + function createTry(tryBlock: Block, catchClause: CatchClause, finallyBlock: Block, location?: TextRange): TryStatement; + function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause, finallyBlock: Block): TryStatement; + function createCaseBlock(clauses: CaseOrDefaultClause[], location?: TextRange): CaseBlock; + function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionDeclaration; + function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionDeclaration; + function createClassDeclaration(decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[], location?: TextRange): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; + function createImportDeclaration(decorators: Decorator[], modifiers: Modifier[], importClause: ImportClause, moduleSpecifier?: Expression, location?: TextRange): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: Decorator[], modifiers: Modifier[], importClause: ImportClause, moduleSpecifier: Expression): ImportDeclaration; + function createImportClause(name: Identifier, namedBindings: NamedImportBindings, location?: TextRange): ImportClause; + function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings): ImportClause; + function createNamespaceImport(name: Identifier, location?: TextRange): NamespaceImport; + function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; + function createNamedImports(elements: ImportSpecifier[], location?: TextRange): NamedImports; + function updateNamedImports(node: NamedImports, elements: ImportSpecifier[]): NamedImports; + function createImportSpecifier(propertyName: Identifier, name: Identifier, location?: TextRange): ImportSpecifier; + function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier, name: Identifier): ImportSpecifier; + function createExportAssignment(decorators: Decorator[], modifiers: Modifier[], isExportEquals: boolean, expression: Expression, location?: TextRange): ExportAssignment; + function updateExportAssignment(node: ExportAssignment, decorators: Decorator[], modifiers: Modifier[], expression: Expression): ExportAssignment; + function createExportDeclaration(decorators: Decorator[], modifiers: Modifier[], exportClause: NamedExports, moduleSpecifier?: Expression, location?: TextRange): ExportDeclaration; + function updateExportDeclaration(node: ExportDeclaration, decorators: Decorator[], modifiers: Modifier[], exportClause: NamedExports, moduleSpecifier: Expression): ExportDeclaration; + function createNamedExports(elements: ExportSpecifier[], location?: TextRange): NamedExports; + function updateNamedExports(node: NamedExports, elements: ExportSpecifier[]): NamedExports; + function createExportSpecifier(name: string | Identifier, propertyName?: string | Identifier, location?: TextRange): ExportSpecifier; + function updateExportSpecifier(node: ExportSpecifier, name: Identifier, propertyName: Identifier): ExportSpecifier; + function createJsxElement(openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement, location?: TextRange): JsxElement; + function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement): JsxElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributeLike[], location?: TextRange): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributeLike[]): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributeLike[], location?: TextRange): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributeLike[]): JsxOpeningElement; + function createJsxClosingElement(tagName: JsxTagNameExpression, location?: TextRange): JsxClosingElement; + function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; + function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression, location?: TextRange): JsxAttribute; + function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; + function createJsxSpreadAttribute(expression: Expression, location?: TextRange): JsxSpreadAttribute; + function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; + function createJsxExpression(expression: Expression, location?: TextRange): JsxExpression; + function updateJsxExpression(node: JsxExpression, expression: Expression): JsxExpression; + function createHeritageClause(token: SyntaxKind, types: ExpressionWithTypeArguments[], location?: TextRange): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause; + function createCaseClause(expression: Expression, statements: Statement[], location?: TextRange): CaseClause; + function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause; + function createDefaultClause(statements: Statement[], location?: TextRange): DefaultClause; + function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause; + function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block, location?: TextRange): CatchClause; + function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause; + function createPropertyAssignment(name: string | PropertyName, initializer: Expression, location?: TextRange): PropertyAssignment; + function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; + function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer: Expression, location?: TextRange): ShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression): ShorthandPropertyAssignment; + function updateSourceFileNode(node: SourceFile, statements: Statement[]): SourceFile; + function createNotEmittedStatement(original: Node): NotEmittedStatement; + function createPartiallyEmittedExpression(expression: Expression, original?: Node, location?: TextRange): PartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createComma(left: Expression, right: Expression): Expression; + function createLessThan(left: Expression, right: Expression, location?: TextRange): Expression; + function createAssignment(left: Expression, right: Expression, location?: TextRange): BinaryExpression; + function createStrictEquality(left: Expression, right: Expression): BinaryExpression; + function createStrictInequality(left: Expression, right: Expression): BinaryExpression; + function createAdd(left: Expression, right: Expression): BinaryExpression; + function createSubtract(left: Expression, right: Expression): BinaryExpression; + function createPostfixIncrement(operand: Expression, location?: TextRange): PostfixUnaryExpression; + function createLogicalAnd(left: Expression, right: Expression): BinaryExpression; + function createLogicalOr(left: Expression, right: Expression): BinaryExpression; + function createLogicalNot(operand: Expression): PrefixUnaryExpression; + function createVoidZero(): VoidExpression; + function createMemberAccessForPropertyName(target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression; + function createRestParameter(name: string | Identifier): ParameterDeclaration; + function createFunctionCall(func: Expression, thisArg: Expression, argumentsList: Expression[], location?: TextRange): CallExpression; + function createFunctionApply(func: Expression, thisArg: Expression, argumentsExpression: Expression, location?: TextRange): CallExpression; + function createArraySlice(array: Expression, start?: number | Expression): CallExpression; + function createArrayConcat(array: Expression, values: Expression[]): CallExpression; + function createMathPow(left: Expression, right: Expression, location?: TextRange): CallExpression; + function createReactCreateElement(reactNamespace: string, tagName: Expression, props: Expression, children: Expression[], parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression; + function createLetDeclarationList(declarations: VariableDeclaration[], location?: TextRange): VariableDeclarationList; + function createConstDeclarationList(declarations: VariableDeclaration[], location?: TextRange): VariableDeclarationList; + function createHelperName(externalHelpersModuleName: Identifier | undefined, name: string): Identifier | PropertyAccessExpression; + function createExtendsHelper(externalHelpersModuleName: Identifier | undefined, name: Identifier): CallExpression; + function createAssignHelper(externalHelpersModuleName: Identifier | undefined, attributesSegments: Expression[]): CallExpression; + function createParamHelper(externalHelpersModuleName: Identifier | undefined, expression: Expression, parameterOffset: number, location?: TextRange): CallExpression; + function createMetadataHelper(externalHelpersModuleName: Identifier | undefined, metadataKey: string, metadataValue: Expression): CallExpression; + function createDecorateHelper(externalHelpersModuleName: Identifier | undefined, decoratorExpressions: Expression[], target: Expression, memberName?: Expression, descriptor?: Expression, location?: TextRange): CallExpression; + function createAwaiterHelper(externalHelpersModuleName: Identifier | undefined, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block): CallExpression; + function createHasOwnProperty(target: LeftHandSideExpression, propertyName: Expression): CallExpression; + function createAdvancedAsyncSuperHelper(): VariableStatement; + function createSimpleAsyncSuperHelper(): VariableStatement; + interface CallBinding { + target: LeftHandSideExpression; + thisArg: Expression; + } + function createCallBinding(expression: Expression, recordTempVariable: (temp: Identifier) => void, languageVersion?: ScriptTarget, cacheIdentifiers?: boolean): CallBinding; + function inlineExpressions(expressions: Expression[]): Expression; + function createExpressionFromEntityName(node: EntityName | Expression): Expression; + function createExpressionForPropertyName(memberName: PropertyName): Expression; + function createExpressionForObjectLiteralElementLike(node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression; + function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number; + function parenthesizeBinaryOperand(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand?: Expression): Expression; + function parenthesizeForNew(expression: Expression): LeftHandSideExpression; + function parenthesizeForAccess(expression: Expression): LeftHandSideExpression; + function parenthesizePostfixOperand(operand: Expression): LeftHandSideExpression; + function parenthesizePrefixOperand(operand: Expression): UnaryExpression; + function parenthesizeExpressionForList(expression: Expression): Expression; + function parenthesizeExpressionForExpressionStatement(expression: Expression): Expression; + function parenthesizeConciseBody(body: ConciseBody): ConciseBody; + const enum OuterExpressionKinds { + Parentheses = 1, + Assertions = 2, + PartiallyEmittedExpressions = 4, + All = 7, + } + function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKinds): Expression; + function skipOuterExpressions(node: Node, kinds?: OuterExpressionKinds): Node; + function skipParentheses(node: Expression): Expression; + function skipParentheses(node: Node): Node; + function skipAssertions(node: Expression): Expression; + function skipAssertions(node: Node): Node; + function skipPartiallyEmittedExpressions(node: Expression): Expression; + function skipPartiallyEmittedExpressions(node: Node): Node; + function startOnNewLine(node: T): T; + function setOriginalNode(node: T, original: Node): T; + function setTextRange(node: T, location: TextRange): T; + function setNodeFlags(node: T, flags: NodeFlags): T; + function setMultiLine(node: T, multiLine: boolean): T; + function setHasTrailingComma(nodes: NodeArray, hasTrailingComma: boolean): NodeArray; + function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile): Identifier; + function getExternalModuleNameLiteral(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions): StringLiteral; + function tryGetModuleNameFromFile(file: SourceFile, host: EmitHost, options: CompilerOptions): StringLiteral; } declare namespace ts { - let parseTime: number; function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function parseIsolatedJSDocComment(content: string, start?: number, length?: number): { - jsDocComment: JSDocComment; + jsDoc: JSDoc; diagnostics: Diagnostic[]; }; function parseJSDocTypeExpressionForTests(content: string, start?: number, length?: number): { @@ -7163,7 +7876,6 @@ declare namespace ts { }; } declare namespace ts { - let bindTime: number; const enum ModuleInstanceState { NonInstantiated = 0, Instantiated = 1, @@ -7171,48 +7883,146 @@ declare namespace ts { } function getModuleInstanceState(node: Node): ModuleInstanceState; function bindSourceFile(file: SourceFile, options: CompilerOptions): void; + function computeTransformFlagsForNode(node: Node, subtreeFlags: TransformFlags): TransformFlags; } declare namespace ts { function getNodeId(node: Node): number; - let checkTime: number; function getSymbolId(symbol: Symbol): number; function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker; } declare namespace ts { - interface SourceMapWriter { - getSourceMapData(): SourceMapData; - setSourceFile(sourceFile: SourceFile): void; - emitPos(pos: number): void; - emitStart(range: TextRange): void; - emitEnd(range: TextRange, stopOverridingSpan?: boolean): void; - changeEmitSourcePos(): void; - getText(): string; - getSourceMappingURL(): string; - initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void; - reset(): void; + type VisitResult = T | T[]; + function reduceEachChild(node: Node, f: (memo: T, node: Node) => T, initial: T): T; + function visitNode(node: T, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray) => T): T; + function visitNode(node: T, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, optional: boolean, lift: (node: NodeArray) => T, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): T; + function visitNodes(nodes: NodeArray, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, start?: number, count?: number): NodeArray; + function visitNodes(nodes: NodeArray, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, start: number, count: number, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): NodeArray; + function visitEachChild(node: T, visitor: (node: Node) => VisitResult, context: LexicalEnvironment): T; + function mergeFunctionBodyLexicalEnvironment(body: FunctionBody, declarations: Statement[]): FunctionBody; + function mergeFunctionBodyLexicalEnvironment(body: ConciseBody, declarations: Statement[]): ConciseBody; + function liftToBlock(nodes: Node[]): Statement; + function aggregateTransformFlags(node: T): T; + namespace Debug { + const failNotOptional: (message?: string) => void; + const failBadSyntaxKind: (node: Node, message?: string) => void; + const assertNode: (node: Node, test: (node: Node) => boolean, message?: string) => void; } - function getNullSourceMapWriter(): SourceMapWriter; - function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter; +} +declare namespace ts { + function flattenDestructuringAssignment(context: TransformationContext, node: BinaryExpression, needsValue: boolean, recordTempVariable: (node: Identifier) => void, visitor?: (node: Node) => VisitResult): Expression; + function flattenParameterDestructuring(context: TransformationContext, node: ParameterDeclaration, value: Expression, visitor?: (node: Node) => VisitResult): VariableDeclaration[]; + function flattenVariableDestructuring(context: TransformationContext, node: VariableDeclaration, value?: Expression, visitor?: (node: Node) => VisitResult, recordTempVariable?: (node: Identifier) => void): VariableDeclaration[]; + function flattenVariableDestructuringToExpression(context: TransformationContext, node: VariableDeclaration, recordTempVariable: (name: Identifier) => void, nameSubstitution?: (name: Identifier) => Expression, visitor?: (node: Node) => VisitResult): Expression; +} +declare namespace ts { + function transformTypeScript(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformJsx(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformES7(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformES6(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformGenerators(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformModule(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformSystemModule(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformES6Module(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + interface TransformationResult { + getSourceFiles(): SourceFile[]; + getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; + isSubstitutionEnabled(node: Node): boolean; + isEmitNotificationEnabled(node: Node): boolean; + onSubstituteNode(node: Node, isExpression: boolean): Node; + onEmitNode(node: Node, emitCallback: (node: Node) => void): void; + dispose(): void; + } + interface TransformationContext extends LexicalEnvironment { + getCompilerOptions(): CompilerOptions; + getEmitResolver(): EmitResolver; + getEmitHost(): EmitHost; + getNodeEmitFlags(node: Node): NodeEmitFlags; + setNodeEmitFlags(node: T, flags: NodeEmitFlags): T; + getSourceMapRange(node: Node): TextRange; + setSourceMapRange(node: T, range: TextRange): T; + getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; + setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange): T; + getCommentRange(node: Node): TextRange; + setCommentRange(node: T, range: TextRange): T; + hoistFunctionDeclaration(node: FunctionDeclaration): void; + hoistVariableDeclaration(node: Identifier): void; + enableSubstitution(kind: SyntaxKind): void; + isSubstitutionEnabled(node: Node): boolean; + onSubstituteNode?: (node: Node, isExpression: boolean) => Node; + enableEmitNotification(kind: SyntaxKind): void; + isEmitNotificationEnabled(node: Node): boolean; + onEmitNode?: (node: Node, emit: (node: Node) => void) => void; + } + type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile; + function getTransformers(compilerOptions: CompilerOptions): Transformer[]; + function transformFiles(resolver: EmitResolver, host: EmitHost, sourceFiles: SourceFile[], transformers: Transformer[]): TransformationResult; } declare namespace ts { function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[]; function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection): boolean; } declare namespace ts { - function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string; - function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string; + interface SourceMapWriter { + initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void; + reset(): void; + getSourceMapData(): SourceMapData; + setSourceFile(sourceFile: SourceFile): void; + emitPos(pos: number): void; + emitStart(range: TextRange): void; + emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; + emitEnd(range: TextRange): void; + emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; + emitTokenStart(token: SyntaxKind, tokenStartPos: number): number; + emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; + emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number; + emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; + changeEmitSourcePos(): void; + stopOverridingSpan(): void; + getText(): string; + getSourceMappingURL(): string; + } + function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter; + function getNullSourceMapWriter(): SourceMapWriter; +} +declare namespace ts { + interface CommentWriter { + reset(): void; + setSourceFile(sourceFile: SourceFile): void; + emitNodeWithComments(node: Node, emitCallback: (node: Node) => void): void; + emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void; + emitTrailingCommentsOfPosition(pos: number): void; + } + function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter; +} +declare namespace ts { function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult; } declare namespace ts { - let programTime: number; - let emitTime: number; - let ioReadTime: number; - let ioWriteTime: number; - const version: string; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; + const version = "2.1.0"; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: (fileName: string) => string): string; function hasZeroOrOneAsteriskCharacter(str: string): boolean; + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; @@ -7222,64 +8032,536 @@ declare namespace ts { directoryExists?: (directoryName: string) => boolean; }): boolean; function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - const defaultInitCompilerOptions: CompilerOptions; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } -declare namespace ts.BreakpointResolver { - function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number): TextSpan; -} -declare namespace ts.OutliningElementsCollector { - function collectElements(sourceFile: SourceFile): OutliningSpan[]; -} -declare namespace ts.NavigateTo { - function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; -} -declare namespace ts.NavigationBar { - function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; -} declare namespace ts { - enum PatternMatchKind { - exact = 0, - prefix = 1, - substring = 2, - camelCase = 3, + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFile): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node; + getLastToken(sourceFile?: SourceFile): Node; } - interface PatternMatch { - kind: PatternMatchKind; - camelCaseWeight?: number; + interface Symbol { + getFlags(): SymbolFlags; + getName(): string; + getDeclarations(): Declaration[]; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol; + getApparentProperties(): Symbol[]; + getCallSignatures(): Signature[]; + getConstructSignatures(): Signature[]; + getStringIndexType(): Type; + getNumberIndexType(): Type; + getBaseTypes(): ObjectType[]; + getNonNullableType(): Type; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): Type[]; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface SourceFile { + version: string; + scriptSnapshot: IScriptSnapshot; + nameTable: Map; + getNamedDeclarations(): Map; + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineStarts(): number[]; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + interface IScriptSnapshot { + getText(start: number, end: number): string; + getLength(): number; + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; + dispose?(): void; + } + namespace ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + typeReferenceDirectives: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface LanguageServiceHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptKind?(fileName: string): ScriptKind; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readFile?(path: string, encoding?: string): string; + fileExists?(path: string): boolean; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + directoryExists?(directoryName: string): boolean; + getDirectories?(directoryName: string): string[]; + } + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + 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; + getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + findReferences(fileName: string, position: number): ReferencedSymbol[]; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; + getEmitOutput(fileName: string): EmitOutput; + getProgram(): Program; + getNonBoundSourceFile(fileName: string): SourceFile; + getSourceFile(fileName: string): SourceFile; + dispose(): void; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: string; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + class TextChange { + span: TextSpan; + newText: string; + } + interface TextInsertion { + newText: string; + caretOffset: number; + } + interface RenameLocation { + textSpan: TextSpan; + fileName: string; + } + interface ReferenceEntry { + textSpan: TextSpan; + fileName: string; + isWriteAccess: boolean; + isDefinition: boolean; + } + interface ImplementationLocation { + textSpan: TextSpan; + fileName: string; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + namespace HighlightSpanKind { + const none = "none"; + const definition = "definition"; + const reference = "reference"; + const writtenReference = "writtenReference"; + } + interface HighlightSpan { + fileName?: string; + textSpan: TextSpan; + kind: string; + } + interface NavigateToItem { + name: string; + kind: string; + kindModifiers: string; + matchKind: string; isCaseSensitive: boolean; - punctuationStripped: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: string; } - interface PatternMatcher { - getMatchesForLastSegmentOfPattern(candidate: string): PatternMatch[]; - getMatches(candidateContainers: string[], candidate: string): PatternMatch[]; - patternContainsDots: boolean; + interface EditorOptions { + BaseIndentSize?: number; + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + IndentStyle: IndentStyle; } - function createPatternMatcher(pattern: string): PatternMatcher; - function breakIntoCharacterSpans(identifier: string): TextSpan[]; - function breakIntoWordSpans(identifier: string): TextSpan[]; -} -declare namespace ts.SignatureHelp { - const enum ArgumentListKind { - TypeArguments = 0, - CallArguments = 1, - TaggedTemplateArguments = 2, + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, } - interface ArgumentListInfo { - kind: ArgumentListKind; - invocation: CallLikeExpression; - argumentsSpan: TextSpan; - argumentIndex?: number; + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; + InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + InsertSpaceAfterTypeAssertion?: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + [s: string]: boolean | number | string | undefined; + } + interface DefinitionInfo { + fileName: string; + textSpan: TextSpan; + kind: string; + name: string; + containerKind: string; + containerName: string; + } + interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { + displayParts: SymbolDisplayPart[]; + } + interface ReferencedSymbol { + definition: ReferencedSymbolDefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21, + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface QuickInfo { + kind: string; + kindModifiers: string; + textSpan: TextSpan; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; argumentCount: number; } - function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, cancellationToken: CancellationToken): SignatureHelpItems; - function getContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile): ArgumentListInfo; + interface CompletionInfo { + isMemberCompletion: boolean; + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + replacementSpan?: TextSpan; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface OutliningSpan { + textSpan: TextSpan; + hintSpan: TextSpan; + bannerText: string; + autoCollapse: boolean; + } + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + const enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2, + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } + const enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6, + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + StringLiteral = 7, + RegExpLiteral = 8, + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + namespace ScriptElementKind { + const unknown = ""; + const warning = "warning"; + const keyword = "keyword"; + const scriptElement = "script"; + const moduleElement = "module"; + const classElement = "class"; + const localClassElement = "local class"; + const interfaceElement = "interface"; + const typeElement = "type"; + const enumElement = "enum"; + const enumMemberElement = "const"; + const variableElement = "var"; + const localVariableElement = "local var"; + const functionElement = "function"; + const localFunctionElement = "local function"; + const memberFunctionElement = "method"; + const memberGetAccessorElement = "getter"; + const memberSetAccessorElement = "setter"; + const memberVariableElement = "property"; + const constructorImplementationElement = "constructor"; + const callSignatureElement = "call"; + const indexSignatureElement = "index"; + const constructSignatureElement = "construct"; + const parameterElement = "parameter"; + const typeParameterElement = "type parameter"; + const primitiveType = "primitive type"; + const label = "label"; + const alias = "alias"; + const constElement = "const"; + const letElement = "let"; + const directory = "directory"; + const externalModuleName = "external module name"; + } + namespace ScriptElementKindModifier { + const none = ""; + const publicMemberModifier = "public"; + const privateMemberModifier = "private"; + const protectedMemberModifier = "protected"; + const exportedModifier = "export"; + const ambientModifier = "declare"; + const staticModifier = "static"; + const abstractModifier = "abstract"; + } + class ClassificationTypeNames { + static comment: string; + static identifier: string; + static keyword: string; + static numericLiteral: string; + static operator: string; + static stringLiteral: string; + static whiteSpace: string; + static text: string; + static punctuation: string; + static className: string; + static enumName: string; + static interfaceName: string; + static moduleName: string; + static typeParameterName: string; + static typeAliasName: string; + static parameterName: string; + static docCommentTagName: string; + static jsxOpenTagName: string; + static jsxCloseTagName: string; + static jsxSelfClosingTagName: string; + static jsxAttribute: string; + static jsxText: string; + static jsxAttributeStringLiteralValue: 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, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + } } declare namespace ts { + const scanner: Scanner; + const emptyArray: any[]; + const enum SemanticMeaning { + None = 0, + Value = 1, + Type = 2, + Namespace = 4, + All = 7, + } + function getMeaningFromDeclaration(node: Node): SemanticMeaning; + function getMeaningFromLocation(node: Node): SemanticMeaning; + function isCallExpressionTarget(node: Node): boolean; + function isNewExpressionTarget(node: Node): boolean; + function climbPastPropertyAccess(node: Node): Node; + function getTargetLabel(referenceNode: Node, labelName: string): Identifier; + function isJumpStatementTarget(node: Node): boolean; + function isLabelName(node: Node): boolean; + function isRightSideOfQualifiedName(node: Node): boolean; + function isRightSideOfPropertyAccess(node: Node): boolean; + function isNameOfModuleDeclaration(node: Node): boolean; + function isNameOfFunctionDeclaration(node: Node): boolean; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node: Node): boolean; + function isExpressionOfExternalModuleImportEqualsDeclaration(node: Node): boolean; + function isInsideComment(sourceFile: SourceFile, token: Node, position: number): boolean; + function getContainerNode(node: Node): Declaration; + function getNodeKind(node: Node): string; + function getStringLiteralTypeForNode(node: StringLiteral | LiteralTypeNode, typeChecker: TypeChecker): LiteralType; + function isThis(node: Node): boolean; interface ListItemInfo { listItemIndex: number; list: Node; @@ -7321,6 +8603,9 @@ declare namespace ts { function isAccessibilityModifier(kind: SyntaxKind): boolean; function compareDataObjects(dst: any, src: any): boolean; function isArrayLiteralOrObjectLiteralDestructuringPattern(node: Node): boolean; + function hasTrailingDirectorySeparator(path: string): boolean; + function isInReferenceComment(sourceFile: SourceFile, position: number): boolean; + function isInNonReferenceComment(sourceFile: SourceFile, position: number): boolean; } declare namespace ts { function isFirstDeclarationOfSymbolParameter(symbol: Symbol): boolean; @@ -7343,6 +8628,63 @@ declare namespace ts { function stripQuotes(name: string): string; function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean; function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind; + function parseAndReEmitConfigJSONFile(content: string): { + configJsonObject: any; + diagnostics: Diagnostic[]; + }; +} +declare namespace ts.BreakpointResolver { + function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number): TextSpan; +} +declare namespace ts { + function createClassifier(): Classifier; + function getSemanticClassifications(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, classifiableNames: Map, span: TextSpan): ClassifiedSpan[]; + function getEncodedSemanticClassifications(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, classifiableNames: Map, span: TextSpan): Classifications; + function getSyntacticClassifications(cancellationToken: CancellationToken, sourceFile: SourceFile, span: TextSpan): ClassifiedSpan[]; + function getEncodedSyntacticClassifications(cancellationToken: CancellationToken, sourceFile: SourceFile, span: TextSpan): Classifications; +} +declare namespace ts.Completions { + function getCompletionsAtPosition(host: LanguageServiceHost, typeChecker: TypeChecker, log: (message: string) => void, compilerOptions: CompilerOptions, sourceFile: SourceFile, position: number): CompletionInfo; + function getCompletionEntryDetails(typeChecker: TypeChecker, log: (message: string) => void, compilerOptions: CompilerOptions, sourceFile: SourceFile, position: number, entryName: string): CompletionEntryDetails; + function getCompletionEntrySymbol(typeChecker: TypeChecker, log: (message: string) => void, compilerOptions: CompilerOptions, sourceFile: SourceFile, position: number, entryName: string): Symbol; +} +declare namespace ts.DocumentHighlights { + function getDocumentHighlights(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[]; +} +declare namespace ts { + interface DocumentRegistry { + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + reportStats(): string; + } + type DocumentRegistryBucketKey = string & { + __bucketKey: any; + }; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; +} +declare namespace ts.FindAllReferences { + function findReferencedSymbols(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, findInStrings: boolean, findInComments: boolean): ReferencedSymbol[]; + function getReferencedSymbolsForNode(typeChecker: TypeChecker, cancellationToken: CancellationToken, node: Node, sourceFiles: SourceFile[], findInStrings: boolean, findInComments: boolean, implementations: boolean): ReferencedSymbol[]; + function convertReferences(referenceSymbols: ReferencedSymbol[]): ReferenceEntry[]; + function getReferenceEntriesForShorthandPropertyAssignment(node: Node, typeChecker: TypeChecker, result: ReferenceEntry[]): void; + function getReferenceEntryFromNode(node: Node): ReferenceEntry; +} +declare namespace ts.GoToDefinition { + function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): DefinitionInfo[]; + function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[]; +} +declare namespace ts.GoToImplementation { + function getImplementationAtPosition(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): ImplementationLocation[]; +} +declare namespace ts.JsDoc { + function getJsDocCommentsFromDeclarations(declarations: Declaration[], name: string, canUseParsedParamTagComments: boolean): SymbolDisplayPart[]; + function getAllJsDocCompletionEntries(): CompletionEntry[]; + function getDocCommentTemplateAtPosition(newLine: string, sourceFile: SourceFile, position: number): TextInsertion; } declare namespace ts.JsTyping { interface TypingResolutionHost { @@ -7357,6 +8699,84 @@ declare namespace ts.JsTyping { filesToWatch: string[]; }; } +declare namespace ts.NavigateTo { + function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; +} +declare namespace ts.NavigationBar { + function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; +} +declare namespace ts.OutliningElementsCollector { + function collectElements(sourceFile: SourceFile): OutliningSpan[]; +} +declare namespace ts { + enum PatternMatchKind { + exact = 0, + prefix = 1, + substring = 2, + camelCase = 3, + } + interface PatternMatch { + kind: PatternMatchKind; + camelCaseWeight?: number; + isCaseSensitive: boolean; + punctuationStripped: boolean; + } + interface PatternMatcher { + getMatchesForLastSegmentOfPattern(candidate: string): PatternMatch[]; + getMatches(candidateContainers: string[], candidate: string): PatternMatch[]; + patternContainsDots: boolean; + } + function createPatternMatcher(pattern: string): PatternMatcher; + function breakIntoCharacterSpans(identifier: string): TextSpan[]; + function breakIntoWordSpans(identifier: string): TextSpan[]; +} +declare namespace ts { + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; +} +declare namespace ts.Rename { + function getRenameInfo(typeChecker: TypeChecker, defaultLibFileName: string, getCanonicalFileName: (fileName: string) => string, sourceFile: SourceFile, position: number): RenameInfo; +} +declare namespace ts.SignatureHelp { + const enum ArgumentListKind { + TypeArguments = 0, + CallArguments = 1, + TaggedTemplateArguments = 2, + } + interface ArgumentListInfo { + kind: ArgumentListKind; + invocation: CallLikeExpression; + argumentsSpan: TextSpan; + argumentIndex?: number; + argumentCount: number; + } + function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, cancellationToken: CancellationToken): SignatureHelpItems; + function getContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile): ArgumentListInfo; +} +declare namespace ts.SymbolDisplay { + function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): string; + function getSymbolModifiers(symbol: Symbol): string; + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node, location: Node, semanticMeaning?: SemanticMeaning): { + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + symbolKind: string; + }; +} +declare namespace ts { + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: MapLike; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; +} declare namespace ts.formatting { interface FormattingScanner { advance(): void; @@ -7482,6 +8902,8 @@ declare namespace ts.formatting { NoSpaceAfterCloseBracket: Rule; SpaceAfterOpenBrace: Rule; SpaceBeforeCloseBrace: Rule; + NoSpaceAfterOpenBrace: Rule; + NoSpaceBeforeCloseBrace: Rule; NoSpaceBetweenEmptyBraceBrackets: Rule; NewLineAfterOpenBraceInBlockContext: Rule; NewLineBeforeCloseBraceInBlockContext: Rule; @@ -7523,7 +8945,6 @@ declare namespace ts.formatting { NoSpaceAfterOpenAngularBracket: Rule; NoSpaceBeforeCloseAngularBracket: Rule; NoSpaceAfterCloseAngularBracket: Rule; - NoSpaceAfterTypeAssertion: Rule; NoSpaceBetweenEmptyInterfaceBraceBrackets: Rule; HighPriorityCommonRules: Rule[]; LowPriorityCommonRules: Rule[]; @@ -7576,6 +8997,13 @@ declare namespace ts.formatting { SpaceAfterOpenBraceInJsxExpression: Rule; NoSpaceBeforeCloseBraceInJsxExpression: Rule; SpaceBeforeCloseBraceInJsxExpression: Rule; + SpaceBeforeJsxAttribute: Rule; + SpaceBeforeSlashInJsxOpeningElement: Rule; + NoSpaceBeforeGreaterThanTokenInJsxOpeningElement: Rule; + NoSpaceBeforeEqualInJsxAttribute: Rule; + NoSpaceAfterEqualInJsxAttribute: Rule; + NoSpaceAfterTypeAssertion: Rule; + SpaceAfterTypeAssertion: Rule; constructor(); static IsForContext(context: FormattingContext): boolean; static IsNotForContext(context: FormattingContext): boolean; @@ -7603,8 +9031,11 @@ declare namespace ts.formatting { static IsNextTokenNotCloseBracket(context: FormattingContext): boolean; static IsArrowFunctionContext(context: FormattingContext): boolean; static IsNonJsxSameLineTokenContext(context: FormattingContext): boolean; - static isNonJsxElementContext(context: FormattingContext): boolean; - static isJsxExpressionContext(context: FormattingContext): boolean; + static IsNonJsxElementContext(context: FormattingContext): boolean; + static IsJsxExpressionContext(context: FormattingContext): boolean; + static IsNextTokenParentJsxAttribute(context: FormattingContext): boolean; + static IsJsxAttributeContext(context: FormattingContext): boolean; + static IsJsxSelfClosingElementContext(context: FormattingContext): boolean; static IsNotBeforeBlockInFunctionDeclarationContext(context: FormattingContext): boolean; static IsEndOfDecoratorContextOnSameLine(context: FormattingContext): boolean; static NodeIsInDecoratorContext(node: Node): boolean; @@ -7753,517 +9184,17 @@ declare namespace ts.formatting { } } declare namespace ts { - const servicesVersion: string; - interface Node { - getSourceFile(): SourceFile; - getChildCount(sourceFile?: SourceFile): number; - getChildAt(index: number, sourceFile?: SourceFile): Node; - getChildren(sourceFile?: SourceFile): Node[]; - getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; - getFullStart(): number; - getEnd(): number; - getWidth(sourceFile?: SourceFile): number; - getFullWidth(): number; - getLeadingTriviaWidth(sourceFile?: SourceFile): number; - getFullText(sourceFile?: SourceFile): string; - getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; - } - interface Symbol { - getFlags(): SymbolFlags; - getName(): string; - getDeclarations(): Declaration[]; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface Type { - getFlags(): TypeFlags; - getSymbol(): Symbol; - getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol; - getApparentProperties(): Symbol[]; - getCallSignatures(): Signature[]; - getConstructSignatures(): Signature[]; - getStringIndexType(): Type; - getNumberIndexType(): Type; - getBaseTypes(): ObjectType[]; - getNonNullableType(): Type; - } - interface Signature { - getDeclaration(): SignatureDeclaration; - getTypeParameters(): Type[]; - getParameters(): Symbol[]; - getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface SourceFile { - version: string; - scriptSnapshot: IScriptSnapshot; - nameTable: Map; - getNamedDeclarations(): Map; - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - getLineStarts(): number[]; - getPositionOfLineAndCharacter(line: number, character: number): number; - update(newText: string, textChangeRange: TextChangeRange): SourceFile; - } - interface IScriptSnapshot { - getText(start: number, end: number): string; - getLength(): number; - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; - dispose?(): void; - } - namespace ScriptSnapshot { - function fromString(text: string): IScriptSnapshot; - } - interface PreProcessedFileInfo { - referencedFiles: FileReference[]; - typeReferenceDirectives: FileReference[]; - importedFiles: FileReference[]; - ambientExternalModules: string[]; - isLibFile: boolean; - } - interface HostCancellationToken { - isCancellationRequested(): boolean; - } - interface LanguageServiceHost { - getCompilationSettings(): CompilerOptions; - getNewLine?(): string; - getProjectVersion?(): string; - getScriptFileNames(): string[]; - getScriptKind?(fileName: string): ScriptKind; - getScriptVersion(fileName: string): string; - getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; - getLocalizedDiagnosticMessages?(): any; - getCancellationToken?(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(options: CompilerOptions): string; - log?(s: string): void; - trace?(s: string): void; - error?(s: string): void; - useCaseSensitiveFileNames?(): boolean; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - directoryExists?(directoryName: string): boolean; - getDirectories?(directoryName: string): string[]; - } - interface LanguageService { - cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; - getSemanticDiagnostics(fileName: string): Diagnostic[]; - getCompilerOptionsDiagnostics(): Diagnostic[]; - getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - 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; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; - getRenameInfo(fileName: string, position: number): RenameInfo; - 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[]; - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; - getNavigationBarItems(fileName: string): NavigationBarItem[]; - getOutliningSpans(fileName: string): OutliningSpan[]; - getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; - getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; - isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; - getProgram(): Program; - getNonBoundSourceFile(fileName: string): SourceFile; - dispose(): void; - } - interface Classifications { - spans: number[]; - endOfLineState: EndOfLineState; - } - interface ClassifiedSpan { - textSpan: TextSpan; - classificationType: string; - } - interface NavigationBarItem { - text: string; - kind: string; - kindModifiers: string; - spans: TextSpan[]; - childItems: NavigationBarItem[]; - indent: number; - bolded: boolean; - grayed: boolean; - } - interface TodoCommentDescriptor { - text: string; - priority: number; - } - interface TodoComment { - descriptor: TodoCommentDescriptor; - message: string; - position: number; - } - class TextChange { - span: TextSpan; - newText: string; - } - interface TextInsertion { - newText: string; - caretOffset: number; - } - interface RenameLocation { - textSpan: TextSpan; - fileName: string; - } - interface ReferenceEntry { - textSpan: TextSpan; - fileName: string; - isWriteAccess: boolean; - isDefinition: boolean; - } - interface DocumentHighlights { - fileName: string; - highlightSpans: HighlightSpan[]; - } - namespace HighlightSpanKind { - const none: string; - const definition: string; - const reference: string; - const writtenReference: string; - } - interface HighlightSpan { - fileName?: string; - textSpan: TextSpan; - kind: string; - } - interface NavigateToItem { - name: string; - kind: string; - kindModifiers: string; - matchKind: string; - isCaseSensitive: boolean; - fileName: string; - textSpan: TextSpan; - containerName: string; - containerKind: string; - } - interface EditorOptions { - BaseIndentSize?: number; - IndentSize: number; - TabSize: number; - NewLineCharacter: string; - ConvertTabsToSpaces: boolean; - IndentStyle: IndentStyle; - } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, - } - interface FormatCodeOptions extends EditorOptions { - InsertSpaceAfterCommaDelimiter: boolean; - InsertSpaceAfterSemicolonInForStatements: boolean; - InsertSpaceBeforeAndAfterBinaryOperators: boolean; - InsertSpaceAfterKeywordsInControlFlowStatements: boolean; - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - PlaceOpenBraceOnNewLineForFunctions: boolean; - PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; - } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; - kind: string; - name: string; - containerKind: string; - containerName: string; - } - interface ReferencedSymbol { - definition: DefinitionInfo; - references: ReferenceEntry[]; - } - enum SymbolDisplayPartKind { - aliasName = 0, - className = 1, - enumName = 2, - fieldName = 3, - interfaceName = 4, - keyword = 5, - lineBreak = 6, - numericLiteral = 7, - stringLiteral = 8, - localName = 9, - methodName = 10, - moduleName = 11, - operator = 12, - parameterName = 13, - propertyName = 14, - punctuation = 15, - space = 16, - text = 17, - typeParameterName = 18, - enumMemberName = 19, - functionName = 20, - regularExpressionLiteral = 21, - } - interface SymbolDisplayPart { - text: string; - kind: string; - } - interface QuickInfo { - kind: string; - kindModifiers: string; - textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage: string; - displayName: string; - fullDisplayName: string; - kind: string; - kindModifiers: string; - triggerSpan: TextSpan; - } - interface SignatureHelpParameter { - name: string; - documentation: SymbolDisplayPart[]; - displayParts: SymbolDisplayPart[]; - isOptional: boolean; - } - interface SignatureHelpItem { - isVariadic: boolean; - prefixDisplayParts: SymbolDisplayPart[]; - suffixDisplayParts: SymbolDisplayPart[]; - separatorDisplayParts: SymbolDisplayPart[]; - parameters: SignatureHelpParameter[]; - documentation: SymbolDisplayPart[]; - } - interface SignatureHelpItems { - items: SignatureHelpItem[]; - applicableSpan: TextSpan; - selectedItemIndex: number; - argumentIndex: number; - argumentCount: number; - } - interface CompletionInfo { - isMemberCompletion: boolean; - isNewIdentifierLocation: boolean; - entries: CompletionEntry[]; - } - interface CompletionEntry { - name: string; - kind: string; - kindModifiers: string; - sortText: string; - } - interface CompletionEntryDetails { - name: string; - kind: string; - kindModifiers: string; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface OutliningSpan { - textSpan: TextSpan; - hintSpan: TextSpan; - bannerText: string; - autoCollapse: boolean; - } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - const enum OutputFileType { - JavaScript = 0, - SourceMap = 1, - Declaration = 2, - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } - const enum EndOfLineState { - None = 0, - InMultiLineCommentTrivia = 1, - InSingleQuoteStringLiteral = 2, - InDoubleQuoteStringLiteral = 3, - InTemplateHeadOrNoSubstitutionTemplate = 4, - InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, - } - enum TokenClass { - Punctuation = 0, - Keyword = 1, - Operator = 2, - Comment = 3, - Whitespace = 4, - Identifier = 5, - NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8, - } - interface ClassificationResult { - finalLexState: EndOfLineState; - entries: ClassificationInfo[]; - } - interface ClassificationInfo { - length: number; - classification: TokenClass; - } - interface Classifier { - getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; - getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; - } - interface DocumentRegistry { - acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; - reportStats(): string; - } - type DocumentRegistryBucketKey = string & { - __bucketKey: any; - }; - namespace ScriptElementKind { - const unknown: string; - const warning: string; - const keyword: string; - const scriptElement: string; - const moduleElement: string; - const classElement: string; - const localClassElement: string; - const interfaceElement: string; - const typeElement: string; - const enumElement: string; - const variableElement: string; - const localVariableElement: string; - const functionElement: string; - const localFunctionElement: string; - const memberFunctionElement: string; - const memberGetAccessorElement: string; - const memberSetAccessorElement: string; - const memberVariableElement: string; - const constructorImplementationElement: string; - const callSignatureElement: string; - const indexSignatureElement: string; - const constructSignatureElement: string; - const parameterElement: string; - const typeParameterElement: string; - const primitiveType: string; - const label: string; - const alias: string; - const constElement: string; - const letElement: string; - } - namespace ScriptElementKindModifier { - const none: string; - const publicMemberModifier: string; - const privateMemberModifier: string; - const protectedMemberModifier: string; - const exportedModifier: string; - const ambientModifier: string; - const staticModifier: string; - const abstractModifier: string; - } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - static jsxOpenTagName: string; - static jsxCloseTagName: string; - static jsxSelfClosingTagName: string; - static jsxAttribute: string; - static jsxText: string; - static jsxAttributeStringLiteralValue: 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, - docCommentTagName = 18, - jsxOpenTagName = 19, - jsxCloseTagName = 20, - jsxSelfClosingTagName = 21, - jsxAttribute = 22, - jsxText = 23, - jsxAttributeStringLiteralValue = 24, - } + const servicesVersion = "0.5"; interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; - interface TranspileOptions { - compilerOptions?: CompilerOptions; - fileName?: string; - reportDiagnostics?: boolean; - moduleName?: string; - renamedDependencies?: Map; - } - interface TranspileOutput { - outputText: string; - diagnostics?: Diagnostic[]; - sourceMapText?: string; - } - function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; - function getContainerNode(node: Node): Declaration; - function getNodeKind(node: Node): string; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function getNameTable(sourceFile: SourceFile): Map; - function createClassifier(): Classifier; function getDefaultLibFilePath(options: CompilerOptions): string; } declare namespace ts.server { @@ -8274,35 +9205,36 @@ declare namespace ts.server { project: Project; } namespace CommandNames { - const Brace: string; - const Change: string; - const Close: string; - const Completions: string; - const CompletionDetails: string; - const Configure: string; - const Definition: string; - const Exit: string; - const Format: string; - const Formatonkey: string; - const Geterr: string; - const GeterrForProject: string; - const SemanticDiagnosticsSync: string; - const SyntacticDiagnosticsSync: string; - const NavBar: string; - const Navto: string; - const Occurrences: string; - const DocumentHighlights: string; - const Open: string; - const Quickinfo: string; - const References: string; - const Reload: string; - const Rename: string; - const Saveto: string; - const SignatureHelp: string; - const TypeDefinition: string; - const ProjectInfo: string; - const ReloadProjects: string; - const Unknown: string; + const Brace = "brace"; + const Change = "change"; + const Close = "close"; + const Completions = "completions"; + const CompletionDetails = "completionEntryDetails"; + const Configure = "configure"; + const Definition = "definition"; + const Exit = "exit"; + const Format = "format"; + const Formatonkey = "formatonkey"; + const Geterr = "geterr"; + const GeterrForProject = "geterrForProject"; + const Implementation = "implementation"; + const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + const NavBar = "navbar"; + const Navto = "navto"; + const Occurrences = "occurrences"; + const DocumentHighlights = "documentHighlights"; + const Open = "open"; + const Quickinfo = "quickinfo"; + const References = "references"; + const Reload = "reload"; + const Rename = "rename"; + const Saveto = "saveto"; + const SignatureHelp = "signatureHelp"; + const TypeDefinition = "typeDefinition"; + const ProjectInfo = "projectInfo"; + const ReloadProjects = "reloadProjects"; + const Unknown = "unknown"; } interface ServerHost extends ts.System { setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; @@ -8318,7 +9250,7 @@ declare namespace ts.server { private immediateId; private changeSeq; constructor(host: ServerHost, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger); - private handleEvent(eventName, project, fileName); + private handleEvent(event); logError(err: Error, cmd: string): void; private sendLineToClient(line); send(msg: protocol.Message): void; @@ -8333,6 +9265,7 @@ declare namespace ts.server { private updateErrorCheck(checkList, seq, matchSeq, ms?, followMs?, requireOpen?); private getDefinition(line, offset, fileName); private getTypeDefinition(line, offset, fileName); + private getImplementation(line, offset, fileName); private getOccurrences(line, offset, fileName); private getDiagnosticsWorker(args, selector); private getSyntacticDiagnosticsSync(args); @@ -8355,7 +9288,7 @@ declare namespace ts.server { private closeClientFile(fileName); private decorateNavigationBarItem(project, fileName, items, lineIndex); private getNavigationBarItems(fileName); - private getNavigateToItems(searchValue, fileName, maxResultCount?); + private getNavigateToItems(searchValue, fileName, maxResultCount?, currentFileOnly?); private getBraceMatching(line, offset, fileName); getDiagnosticsForProject(delay: number, fileName: string): void; getCanonicalFileName(fileName: string): string; @@ -8388,7 +9321,6 @@ declare namespace ts.server { class ScriptInfo { private host; fileName: string; - content: string; isOpen: boolean; svc: ScriptVersionCache; children: ScriptInfo[]; @@ -8440,10 +9372,11 @@ declare namespace ts.server { saveTo(filename: string, tmpfilename: string): void; reloadScript(filename: string, tmpfilename: string, cb: () => any): void; editScript(filename: string, start: number, end: number, newText: string): void; - resolvePath(path: string): string; fileExists(path: string): boolean; directoryExists(path: string): boolean; getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readFile(path: string, encoding?: string): string; lineToTextSpan(filename: string, line: number): ts.TextSpan; lineOffsetToPosition(filename: string, line: number, offset: number): number; positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo; @@ -8451,12 +9384,12 @@ declare namespace ts.server { } interface ProjectOptions { files?: string[]; - wildcardDirectories?: ts.Map; + wildcardDirectories?: ts.MapLike; compilerOptions?: ts.CompilerOptions; } class Project { projectService: ProjectService; - projectOptions?: ProjectOptions; + projectOptions: ProjectOptions; languageServiceDiabled: boolean; compilerService: CompilerService; projectFilename: string; @@ -8465,7 +9398,7 @@ declare namespace ts.server { directoriesWatchedForWildcards: Map; directoriesWatchedForTsconfig: string[]; program: ts.Program; - filenameToSourceFile: ts.Map; + filenameToSourceFile: Map; updateGraphSeq: number; openRefCount: number; constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean); @@ -8495,8 +9428,22 @@ declare namespace ts.server { project?: Project; } function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; + type ProjectServiceEvent = { + eventName: "context"; + data: { + project: Project; + fileName: string; + }; + } | { + eventName: "configFileDiag"; + data: { + triggerFile?: string; + configFileName: string; + diagnostics: Diagnostic[]; + }; + }; interface ProjectServiceEventHandler { - (eventName: string, project: Project, fileName: string): void; + (event: ProjectServiceEvent): void; } interface HostConfiguration { formatCodeOptions: ts.FormatCodeOptions; @@ -8505,15 +9452,15 @@ declare namespace ts.server { class ProjectService { host: ServerHost; psLogger: Logger; - eventHandler?: ProjectServiceEventHandler; - filenameToScriptInfo: ts.Map; + eventHandler: ProjectServiceEventHandler; + filenameToScriptInfo: Map; openFileRoots: ScriptInfo[]; inferredProjects: Project[]; configuredProjects: Project[]; openFilesReferenced: ScriptInfo[]; openFileRootsConfigured: ScriptInfo[]; - directoryWatchersForTsconfig: ts.Map; - directoryWatchersRefCount: ts.Map; + directoryWatchersForTsconfig: Map; + directoryWatchersRefCount: Map; hostConfiguration: HostConfiguration; timerForDetectingProjectFileListChanges: Map; constructor(host: ServerHost, psLogger: Logger, eventHandler?: ProjectServiceEventHandler); @@ -8523,6 +9470,7 @@ declare namespace ts.server { directoryWatchedForSourceFilesChanged(project: Project, fileName: string): void; startTimerForDetectingProjectFileListChanges(project: Project): void; handleProjectFileListChanges(project: Project): void; + reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string): void; directoryWatchedForTsconfigChanged(fileName: string): void; getCanonicalFileName(fileName: string): string; watchedProjectConfigFileChanged(project: Project): void; @@ -8557,15 +9505,13 @@ declare namespace ts.server { configProjectIsActive(fileName: string): boolean; findConfiguredProjectByConfigFile(configFileName: string): Project; configFileToProjectOptions(configFilename: string): { - succeeded: boolean; projectOptions?: ProjectOptions; - errors?: Diagnostic[]; + errors: Diagnostic[]; }; private exceedTotalNonTsFileSizeLimit(fileNames); openConfigFile(configFilename: string, clientFileName?: string): { - success: boolean; project?: Project; - errors?: Diagnostic[]; + errors: Diagnostic[]; }; updateConfiguredProject(project: Project): Diagnostic[]; createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project; @@ -8612,7 +9558,7 @@ declare namespace ts.server { class TextChange { pos: number; deleteLen: number; - insertedText?: string; + insertedText: string; constructor(pos: number, deleteLen: number, insertedText?: string); getTextChangeRange(): TextChangeRange; } @@ -8729,20 +9675,28 @@ declare namespace ts { getLocalizedDiagnosticMessages(): string; getCancellationToken(): HostCancellationToken; getCurrentDirectory(): string; - getDirectories(path: string): string[]; + getDirectories(path: string): string; getDefaultLibFileName(options: string): string; getNewLine?(): string; getProjectVersion?(): string; useCaseSensitiveFileNames?(): boolean; + readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; + readFile(path: string, encoding?: string): string; + fileExists(path: string): boolean; getModuleResolutionsForFile?(fileName: string): string; getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string; directoryExists(directoryName: string): boolean; } - interface CoreServicesShimHost extends Logger, ModuleResolutionHost { - readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; - useCaseSensitiveFileNames?(): boolean; + interface CoreServicesShimHost extends Logger { + directoryExists(directoryName: string): boolean; + fileExists(fileName: string): boolean; getCurrentDirectory(): string; + getDirectories(path: string): string; + readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; + readFile(fileName: string): string; + realpath?(path: string): string; trace(s: string): void; + useCaseSensitiveFileNames?(): boolean; } interface IFileReference { path: string; @@ -8778,11 +9732,12 @@ declare namespace ts { findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string; getDefinitionAtPosition(fileName: string, position: number): string; getTypeDefinitionAtPosition(fileName: string, position: number): string; + getImplementationAtPosition(fileName: string, position: number): string; getReferencesAtPosition(fileName: string, position: number): string; findReferences(fileName: string, position: number): string; getOccurrencesAtPosition(fileName: string, position: number): string; getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; - getNavigateToItems(searchValue: string, maxResultCount?: number): string; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string; getNavigationBarItems(fileName: string): string; getOutliningSpans(fileName: string): string; getTodoComments(fileName: string, todoCommentDescriptors: string): string; @@ -8801,6 +9756,7 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string; } interface CoreServicesShim extends Shim { + getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string; getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string; getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string; getDefaultCompilationSettings(): string; @@ -8830,6 +9786,9 @@ declare namespace ts { getCurrentDirectory(): string; getDirectories(path: string): string[]; getDefaultLibFileName(options: CompilerOptions): string; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[], depth?: number): string[]; + readFile(path: string, encoding?: string): string; + fileExists(path: string): boolean; } class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost { private shimHost; @@ -8841,6 +9800,7 @@ declare namespace ts { fileExists(fileName: string): boolean; readFile(fileName: string): string; private readDirectoryFallback(rootDir, extension, exclude); + getDirectories(path: string): string[]; } function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; @@ -8864,4 +9824,4 @@ declare namespace ts { declare namespace TypeScript.Services { const TypeScriptServicesFactory: typeof ts.TypeScriptServicesFactory; } -declare const toolsVersion: string; +declare const toolsVersion = "2.1"; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 5dafd5528a8..a8fa909efcc 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -35,14 +35,15 @@ var ts; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidType"] = 2] = "VoidType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 8] = "TypeWithCallSignature"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 9] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; (function (DiagnosticCategory) { @@ -69,8 +70,80 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var performance; + (function (performance) { + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true + ? onProfilerEvent + : function (markName) { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + function mark(markName) { + if (enabled) { + marks[markName] = ts.timestamp(); + counts[markName] = (counts[markName] || 0) + 1; + profilerEvent(markName); + } + } + performance.mark = mark; + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks[endMarkName] || ts.timestamp(); + var start = startMarkName && marks[startMarkName] || profilerStart; + measures[measureName] = (measures[measureName] || 0) + (end - start); + } + } + performance.measure = measure; + function getCount(markName) { + return counts && counts[markName] || 0; + } + performance.getCount = getCount; + function getDuration(measureName) { + return measures && measures[measureName] || 0; + } + performance.getDuration = getDuration; + function forEachMeasure(cb) { + for (var key in measures) { + cb(key, measures[key]); + } + } + performance.forEachMeasure = forEachMeasure; + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var createObject = Object.create; + function createMap(template) { + var map = createObject(null); + map["__"] = undefined; + delete map["__"]; + for (var key in template) + if (hasOwnProperty.call(template, key)) { + map[key] = template[key]; + } + return map; + } + ts.createMap = createMap; function createFileMap(keyMapper) { - var files = {}; + var files = createMap(); return { get: get, set: set, @@ -91,14 +164,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return hasProperty(files, toKey(path)); + return toKey(path) in files; } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = {}; + files = createMap(); } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -124,11 +197,42 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + function every(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0, len = array.length; i < len; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findMap(array, callback) { + for (var i = 0, len = array.length; i < len; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (areEqual ? areEqual(v, value) : v === value) { + if (v === value) { return true; } } @@ -159,9 +263,9 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var v = array_2[_i]; - if (predicate(v)) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { count++; } } @@ -170,23 +274,47 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { - var result; if (array) { - result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - result.push(item); + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; } + return result; } } - return result; + return array; } ts.filter = filter; + function removeWhere(array, f) { + var outIndex = 0; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var item = array_2[_i]; + if (!f(item)) { + array[outIndex] = item; + outIndex++; + } + } + if (outIndex !== array.length) { + array.length = outIndex; + return true; + } + return false; + } + ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var item = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { array[outIndex] = item; outIndex++; @@ -199,14 +327,114 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; - result.push(f(v)); + for (var i = 0; i < array.length; i++) { + var v = array[i]; + result.push(f(v, i)); } } return result; } ts.map = map; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + function flatMap(array, mapfn) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMap = flatMap; + function span(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!f(array[i], i)) { + return [array.slice(0, i), array.slice(i)]; + } + } + return [array.slice(0), []]; + } + return undefined; + } + ts.span = span; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapObject(object, f) { + var result; + if (object) { + result = {}; + for (var _i = 0, _a = getOwnKeys(object); _i < _a.length; _i++) { + var v = _a[_i]; + var _b = f(v, object[v]) || [undefined, undefined], key = _b[0], value = _b[1]; + if (key !== undefined) { + result[key] = value; + } + } + } + return result; + } + ts.mapObject = mapObject; function concatenate(array1, array2) { if (!array2 || !array2.length) return array1; @@ -219,20 +447,42 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; - if (!contains(result, item, areEqual)) { - result.push(item); + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; + for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { + var res = result_1[_a]; + if (areEqual ? areEqual(res, item) : res === item) { + continue loop; + } } + result.push(item); } } return result; } ts.deduplicate = deduplicate; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -242,7 +492,9 @@ var ts; if (to && from) { for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { var v = from_1[_i]; - to.push(v); + if (v !== undefined) { + to.push(v); + } } } } @@ -257,11 +509,28 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function firstOrUndefined(array) { + return array && array.length > 0 + ? array[0] + : undefined; + } + ts.firstOrUndefined = firstOrUndefined; + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; function lastOrUndefined(array) { - if (array.length === 0) { - return undefined; - } - return array[array.length - 1]; + return array && array.length > 0 + ? array[array.length - 1] + : undefined; } ts.lastOrUndefined = lastOrUndefined; function binarySearch(array, value) { @@ -283,11 +552,12 @@ var ts; return ~low; } ts.binarySearch = binarySearch; - function reduceLeft(array, f, initial) { - if (array) { - var count = array.length; - if (count > 0) { - var pos = 0; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -296,8 +566,8 @@ var ts; else { result = initial; } - while (pos < count) { - result = f(result, array[pos]); + while (pos <= end) { + result = f(result, array[pos], pos); pos++; } return result; @@ -306,10 +576,12 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial) { + function reduceRight(array, f, initial, start, count) { if (array) { - var pos = array.length - 1; - if (pos >= 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start > size - 1 ? size - 1 : start; + var end = count === undefined || pos - count < 0 ? 0 : pos - count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -318,8 +590,8 @@ var ts; else { result = initial; } - while (pos >= 0) { - result = f(result, array[pos]); + while (pos >= end) { + result = f(result, array[pos], pos); pos--; } return result; @@ -333,18 +605,103 @@ var ts; return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; - function getKeys(map) { - var keys = []; - for (var key in map) { - keys.push(key); - } - return keys; - } - ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; + function getOwnKeys(map) { + var keys = []; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function forEachProperty(map, callback) { + var result; + for (var key in map) { + if (result = callback(map[key], key)) + break; + } + return result; + } + ts.forEachProperty = forEachProperty; + function someProperties(map, predicate) { + for (var key in map) { + if (!predicate || predicate(map[key], key)) + return true; + } + return false; + } + ts.someProperties = someProperties; + function copyProperties(source, target) { + for (var key in source) { + target[key] = source[key]; + } + } + ts.copyProperties = copyProperties; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var _b = 0, _c = getOwnKeys(arg); _b < _c.length; _b++) { + var p = _c[_b]; + t[p] = arg[p]; + } + } + return t; + } + ts.assign = assign; + function reduceProperties(map, callback, initial) { + var result = initial; + for (var key in map) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceProperties = reduceProperties; + function reduceOwnProperties(map, callback, initial) { + var result = initial; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceOwnProperties = reduceOwnProperties; + function equalOwnProperties(left, right, equalityComparer) { + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key) === undefined) + return false; + if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + return false; + } + for (var key in right) + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; function isEmpty(map) { for (var id in map) { if (hasProperty(map, id)) { @@ -354,75 +711,56 @@ var ts; return true; } ts.isEmpty = isEmpty; + function cloneMap(map) { + var clone = createMap(); + copyProperties(map, clone); + return clone; + } + ts.cloneMap = cloneMap; function clone(object) { var result = {}; for (var id in object) { - result[id] = object[id]; + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in first) { - result[id] = first[id]; - } - for (var id in second) { - if (!hasProperty(result, id)) { + for (var id in second) + if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - } + for (var id in first) + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } return result; } ts.extend = extend; - function forEachValue(map, callback) { - var result; - for (var id in map) { - if (result = callback(map[id])) - break; + function multiMapAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + return values; } - return result; - } - ts.forEachValue = forEachValue; - function forEachKey(map, callback) { - var result; - for (var id in map) { - if (result = callback(id)) - break; - } - return result; - } - ts.forEachKey = forEachKey; - function lookUp(map, key) { - return hasProperty(map, key) ? map[key] : undefined; - } - ts.lookUp = lookUp; - function copyMap(source, target) { - for (var p in source) { - target[p] = source[p]; + else { + return map[key] = [value]; } } - ts.copyMap = copyMap; - function arrayToMap(array, makeKey) { - var result = {}; - forEach(array, function (value) { - result[makeKey(value)] = value; - }); - return result; - } - ts.arrayToMap = arrayToMap; - function reduceProperties(map, callback, initial) { - var result = initial; - if (map) { - for (var key in map) { - if (hasProperty(map, key)) { - result = callback(result, map[key], String(key)); - } + ts.multiMapAdd = multiMapAdd; + function multiMapRemove(map, key, value) { + var values = map[key]; + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + delete map[key]; } } - return result; } - ts.reduceProperties = reduceProperties; + ts.multiMapRemove = multiMapRemove; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -444,9 +782,7 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] - ? ts.localizedDiagnosticMessages[message.key] - : message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -631,6 +967,7 @@ var ts; } ts.getRootLength = getRootLength; ts.directorySeparator = "/"; + var directorySeparatorCharCode = 47; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; @@ -652,10 +989,21 @@ var ts; function normalizePath(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); + var root = path.substr(0, rootLength); var normalized = getNormalizedParts(path, rootLength); - return path.substr(0, rootLength) + normalized.join(ts.directorySeparator); + if (normalized.length) { + var joinedParts = root + normalized.join(ts.directorySeparator); + return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + } + else { + return root; + } } ts.normalizePath = normalizePath; + function pathEndsWithDirectorySeparator(path) { + return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; + } + ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; function getDirectoryPath(path) { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); } @@ -830,10 +1178,17 @@ var ts; return true; } ts.containsPath = containsPath; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - var pathLen = path.length; - var extLen = extension.length; - return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; + return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -848,10 +1203,15 @@ var ts; ts.fileExtensionIsAny = fileExtensionIsAny; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; + var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; + var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } + var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; + var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; + var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -874,7 +1234,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -886,6 +1246,16 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } + if (usage !== "exclude") { + if (component.charCodeAt(0) === 42) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + subpattern += "[^./]"; + component = component.substr(1); + } + } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -906,8 +1276,14 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildcardCharacter(match) { - return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + function replaceWildCardCharacterFiles(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); + } + function replaceWildCardCharacterOther(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1006,6 +1382,7 @@ var ts; } ts.getScriptKindFromFileName = getScriptKindFromFileName; ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { @@ -1068,9 +1445,13 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; + return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -1090,14 +1471,21 @@ var ts; function Signature(checker) { } function Node(kind, pos, end) { + this.id = 0; this.kind = kind; this.pos = pos; this.end = end; this.flags = 0; + this.modifierFlagsCache = 0; + this.transformFlags = 0; this.parent = undefined; + this.original = undefined; + this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -1105,9 +1493,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel = 0; + var currentAssertionLevel; function shouldAssert(level) { - return currentAssertionLevel >= level; + return getCurrentAssertionLevel() >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1125,20 +1513,56 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; + function getCurrentAssertionLevel() { + if (currentAssertionLevel !== undefined) { + return currentAssertionLevel; + } + if (ts.sys === undefined) { + return 0; + } + var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); + currentAssertionLevel = developmentMode + ? 1 + : 0; + return currentAssertionLevel; + } })(Debug = ts.Debug || (ts.Debug = {})); - function copyListRemovingItem(item, list) { - var copiedList = []; - for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { - var e = list_1[_i]; - if (e !== item) { - copiedList.push(e); + function getEnvironmentVariable(name, host) { + if (host && host.getEnvironmentVariable) { + return host.getEnvironmentVariable(name); + } + if (ts.sys && ts.sys.getEnvironmentVariable) { + return ts.sys.getEnvironmentVariable(name); + } + return ""; + } + ts.getEnvironmentVariable = getEnvironmentVariable; + function orderedRemoveItemAt(array, index) { + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + function unorderedRemoveItem(array, item) { + unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + break; } } - return copiedList; } - ts.copyListRemovingItem = copyListRemovingItem; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? (function (fileName) { return fileName; }) : (function (fileName) { return fileName.toLowerCase(); }); } @@ -1229,7 +1653,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - return { + var wscriptSystem = { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -1248,7 +1672,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!wscriptSystem.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -1259,6 +1683,9 @@ var ts; return shell.CurrentDirectory; }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%" + name + "%"); + }, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -1268,6 +1695,7 @@ var ts; } } }; + return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -1276,13 +1704,13 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = {}; - var fileWatcherCallbacks = {}; + var dirWatchers = ts.createMap(); + var fileWatcherCallbacks = ts.createMap(); return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - if (ts.hasProperty(dirWatchers, dirName)) { - var watcher = dirWatchers[dirName]; + var watcher = dirWatchers[dirName]; + if (watcher) { watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -1291,23 +1719,18 @@ var ts; } } function addDirWatcher(dirPath) { - if (ts.hasProperty(dirWatchers, dirPath)) { - var watcher_1 = dirWatchers[dirPath]; - watcher_1.referenceCount += 1; + var watcher = dirWatchers[dirPath]; + if (watcher) { + watcher.referenceCount += 1; return; } - var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - fileWatcherCallbacks[filePath].push(callback); - } - else { - fileWatcherCallbacks[filePath] = [callback]; - } + ts.multiMapAdd(fileWatcherCallbacks, filePath, callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1319,21 +1742,13 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); - if (newCallbacks.length === 0) { - delete fileWatcherCallbacks[filePath]; - } - else { - fileWatcherCallbacks[filePath] = newCallbacks; - } - } + ts.multiMapRemove(fileWatcherCallbacks, filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { var fileName = typeof relativeFileName !== "string" ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -1438,9 +1853,9 @@ var ts; return fileSystemEntryExists(path, 1); } function getDirectories(path) { - return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - return { + var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -1490,7 +1905,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!nodeSystem.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -1501,6 +1916,9 @@ var ts; return process.cwd(); }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -1536,8 +1954,16 @@ var ts; }, realpath: function (path) { return _fs.realpathSync(path); + }, + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (e) { + } } }; + return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -1562,6 +1988,7 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), readDirectory: function (path, extensions, excludes, includes) { var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); @@ -1792,9 +2219,9 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher_1311", message: "Async functions are only available when targeting ECMAScript 2015 or higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, @@ -1849,12 +2276,11 @@ var ts; Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, - Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_2349", message: "Cannot invoke an expression whose type lacks a call signature." }, + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, @@ -1996,7 +2422,6 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_yield_expressions_2504", message: "No best common type exists among yield expressions." }, A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, @@ -2013,7 +2438,7 @@ var ts; A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, @@ -2026,6 +2451,7 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, + Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2073,6 +2499,13 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, + A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, + Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2143,7 +2576,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -2171,6 +2604,7 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2201,6 +2635,7 @@ var ts; VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, + STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, @@ -2287,10 +2722,12 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, - Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, + Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, + Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, + Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2299,7 +2736,6 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -2314,6 +2750,8 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2341,7 +2779,9 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." } + Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } }; })(ts || (ts = {})); var ts; @@ -2350,7 +2790,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115, "any": 117, "as": 116, @@ -2474,7 +2914,7 @@ var ts; "|=": 67, "^=": 68, "@": 55 - }; + }); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -2515,9 +2955,7 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - if (source.hasOwnProperty(name_4)) { - result[source[name_4]] = name_4; - } + result[source[name_4]] = name_4; } return result; } @@ -2644,7 +3082,7 @@ var ts; ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { if (stopAtComments === void 0) { stopAtComments = false; } - if (!(pos >= 0)) { + if (ts.positionIsSynthesized(pos)) { return pos; } while (true) { @@ -2767,10 +3205,15 @@ var ts; pos = pos + shebang.length; return pos; } - function getCommentRanges(text, pos, trailing) { - var result; + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; var collecting = trailing || pos === 0; - while (pos < text.length) { + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13: @@ -2780,11 +3223,11 @@ var ts; case 10: pos++; if (trailing) { - return result; + break scan; } collecting = true; - if (result && result.length) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; } continue; case 9: @@ -2819,34 +3262,67 @@ var ts; } } if (collecting) { - if (!result) { - result = []; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + return accumulator; + } + hasPendingCommentRange = false; } - result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; } continue; } - break; + break scan; default: if (ch > 127 && (isWhiteSpace(ch))) { - if (result && result.length && isLineBreak(ch)) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; } pos++; continue; } - break; + break scan; } - return result; } - return result; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(false, text, pos, true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(true, text, pos, true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + if (!comments) { + comments = []; + } + comments.push({ pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + return comments; } function getLeadingCommentRanges(text, pos) { - return getCommentRanges(text, pos, false); + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getLeadingCommentRanges = getLeadingCommentRanges; function getTrailingCommentRanges(text, pos) { - return getCommentRanges(text, pos, true); + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getTrailingCommentRanges = getTrailingCommentRanges; function getShebang(text) { @@ -2867,7 +3343,7 @@ var ts; ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; - function isIdentifier(name, languageVersion) { + function isIdentifierText(name, languageVersion) { if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { return false; } @@ -2878,7 +3354,7 @@ var ts; } return true; } - ts.isIdentifier = isIdentifier; + ts.isIdentifierText = isIdentifierText; function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } var pos; @@ -2907,6 +3383,7 @@ var ts; reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, scanJSDocToken: scanJSDocToken, @@ -2990,7 +3467,8 @@ var ts; } return value; } - function scanString() { + function scanString(allowEscapes) { + if (allowEscapes === void 0) { allowEscapes = true; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -3008,7 +3486,7 @@ var ts; pos++; break; } - if (ch === 92) { + if (ch === 92 && allowEscapes) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; @@ -3709,42 +4187,61 @@ var ts; } return token; } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34: + case 39: + tokenValue = scanString(false); + return token = 9; + default: + return scan(); + } + } function scanJSDocToken() { if (pos >= end) { return token = 1; } startPos = pos; - var ch = text.charCodeAt(pos); - while (pos < end) { - ch = text.charCodeAt(pos); - if (isWhiteSpaceSingleLine(ch)) { - pos++; - } - else { - break; - } - } tokenPos = pos; + var ch = text.charCodeAt(pos); switch (ch) { + case 9: + case 11: + case 12: + case 32: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5; case 64: - return pos += 1, token = 55; + pos++; + return token = 55; case 10: case 13: - return pos += 1, token = 4; + pos++; + return token = 4; case 42: - return pos += 1, token = 37; + pos++; + return token = 37; case 123: - return pos += 1, token = 15; + pos++; + return token = 15; case 125: - return pos += 1, token = 16; + pos++; + return token = 16; case 91: - return pos += 1, token = 19; + pos++; + return token = 19; case 93: - return pos += 1, token = 20; + pos++; + return token = 20; case 61: - return pos += 1, token = 56; + pos++; + return token = 56; case 44: - return pos += 1, token = 24; + pos++; + return token = 24; } if (isIdentifierStart(ch, 2)) { pos++; @@ -3858,6 +4355,11 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean", + experimental: true + }, { name: "emitBOM", type: "boolean" @@ -3888,10 +4390,10 @@ var ts; }, { name: "jsx", - type: { + type: ts.createMap({ "preserve": 1, "react": 2 - }, + }), paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -3918,7 +4420,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -3926,16 +4428,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }, + }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: { + type: ts.createMap({ "crlf": 0, "lf": 1 - }, + }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -3953,6 +4455,10 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, + { + name: "noErrorTruncation", + type: "boolean" + }, { name: "noImplicitAny", type: "boolean", @@ -3966,12 +4472,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Locals + description: ts.Diagnostics.Report_errors_on_unused_locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters }, { name: "noLib", @@ -4076,12 +4582,12 @@ var ts; { name: "target", shortName: "t", - type: { + type: ts.createMap({ "es3": 0, "es5": 1, "es6": 2, "es2015": 2 - }, + }), description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -4110,11 +4616,12 @@ var ts; }, { name: "moduleResolution", - type: { + type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }, - description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 + }), + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + paramType: ts.Diagnostics.STRATEGY }, { name: "allowUnusedLabels", @@ -4214,7 +4721,7 @@ var ts; type: "list", element: { name: "lib", - type: { + type: ts.createMap({ "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", "es2015": "lib.es2015.d.ts", @@ -4222,6 +4729,7 @@ var ts; "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", "dom": "lib.dom.d.ts", + "dom.iterable": "lib.dom.iterable.d.ts", "webworker": "lib.webworker.d.ts", "scripthost": "lib.scripthost.d.ts", "es2015.core": "lib.es2015.core.d.ts", @@ -4236,7 +4744,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - } + }) }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -4248,6 +4756,11 @@ var ts; name: "strictNullChecks", type: "boolean", description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "importHelpers", + type: "boolean", + description: ts.Diagnostics.Import_emit_helpers_from_tslib } ]; ts.typingOptionDeclarations = [ @@ -4272,13 +4785,19 @@ var ts; } } ]; + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1, + noImplicitAny: false, + sourceMap: false + }; var optionNameMapCache; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = {}; - var shortOptionNames = {}; + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -4291,16 +4810,16 @@ var ts; ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - ts.forEachKey(opt.type, function (key) { + for (var key in opt.type) { namesOfType.push(" '" + key + "'"); - }); + } return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (ts.hasProperty(map, key)) { + if (key in map) { return map[key]; } else { @@ -4349,10 +4868,10 @@ var ts; } else if (s.charCodeAt(0) === 45) { s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - if (ts.hasProperty(shortOptionNames, s)) { + if (s in shortOptionNames) { s = shortOptionNames[s]; } - if (ts.hasProperty(optionNameMap, s)) { + if (s in optionNameMap) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -4453,6 +4972,76 @@ var ts; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function generateTSConfig(options, fileNames) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var configurations = { + compilerOptions: serializeCompilerOptions(compilerOptions) + }; + if (fileNames && fileNames.length) { + configurations.files = fileNames; + } + return configurations; + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + for (var key in customTypeMap) { + if (customTypeMap[key] === value) { + return key; + } + } + return undefined; + } + function serializeCompilerOptions(options) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name_5 in options) { + if (ts.hasProperty(options, name_5)) { + switch (name_5) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_5]; + var optionDefinition = optionsNameMap[name_5.toLowerCase()]; + if (optionDefinition) { + var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + result[name_5] = value; + } + else { + if (optionDefinition.type === "list") { + var convertedValue = []; + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); + } + result[name_5] = convertedValue; + } + else { + result[name_5] = getNameOfCompilerOptionValue(value, customTypeMap); + } + } + } + break; + } + } + } + return result; + } + } + ts.generateTSConfig = generateTSConfig; function removeComments(jsonText) { var output = ""; var scanner = ts.createScanner(1, false, 0, jsonText); @@ -4470,15 +5059,46 @@ var ts; } return output; } - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } var errors = []; - var compilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var options = ts.extend(existingOptions, compilerOptions); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + return { + options: {}, + fileNames: [], + typingOptions: {}, + raw: json, + errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], + wildcardDirectories: {} + }; + } + var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + if (json["extends"]) { + var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; + if (typeof json["extends"] === "string") { + _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseOptions = _b[3]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + if (include && !json["include"]) { + json["include"] = include; + } + if (exclude && !json["exclude"]) { + json["exclude"] = exclude; + } + if (files && !json["files"]) { + json["files"] = files; + } + options = ts.assign({}, baseOptions, options); + } + options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; return { options: options, fileNames: fileNames, @@ -4487,6 +5107,36 @@ var ts; errors: errors, wildcardDirectories: wildcardDirectories }; + function tryExtendsName(extendedConfig) { + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + return; + } + var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); + errors.push.apply(errors, result.errors); + var _a = ts.map(["include", "exclude", "files"], function (key) { + if (!json[key] && extendedResult.config[key]) { + return ts.map(extendedResult.config[key], updatePath); + } + }), include = _a[0], exclude = _a[1], files = _a[2]; + return [include, exclude, files, result.options]; + } function getFileNames(errors) { var fileNames; if (ts.hasProperty(json, "files")) { @@ -4520,16 +5170,17 @@ var ts; } else { excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - excludeSpecs.push(outDir); + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } + var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { @@ -4545,7 +5196,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -4562,7 +5213,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (ts.hasProperty(optionNameMap, id)) { + if (id in optionNameMap) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -4597,7 +5248,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (ts.hasProperty(opt.type, key)) { + if (key in opt.type) { return opt.type[key]; } else { @@ -4618,8 +5269,8 @@ var ts; function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; - var literalFileMap = {}; - var wildcardFileMap = {}; + var literalFileMap = ts.createMap(); + var wildcardFileMap = ts.createMap(); if (include) { include = validateSpecs(include, errors, false); } @@ -4641,12 +5292,9 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } - if (ignoreFileNamePattern.test(file)) { - continue; - } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + if (!(key in literalFileMap) && !(key in wildcardFileMap)) { wildcardFileMap[key] = file; } } @@ -4681,20 +5329,20 @@ var ts; function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = {}; + var wildcardDirectories = ts.createMap(); if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_5 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_5)) { + var name_6 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_6)) { continue; } - var match = wildcardDirectoryPattern.exec(name_5); + var match = wildcardDirectoryPattern.exec(name_6); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_5) ? 1 : 0; - var existingFlags = ts.getProperty(wildcardDirectories, key); + var flags = watchRecursivePattern.test(name_6) ? 1 : 0; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1) { @@ -4704,12 +5352,10 @@ var ts; } } for (var key in wildcardDirectories) { - if (ts.hasProperty(wildcardDirectories, key)) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; - } + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; } } } @@ -4722,7 +5368,7 @@ var ts; for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { return true; } } @@ -4750,6 +5396,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -4797,24 +5444,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function mapIsEqualTo(map1, map2) { - if (!map1 || !map2) { - return map1 === map2; - } - return containsAll(map1, map2) && containsAll(map2, map1); - } - ts.mapIsEqualTo = mapIsEqualTo; - function containsAll(map, other) { - for (var key in map) { - if (!ts.hasProperty(map, key)) { - continue; - } - if (!ts.hasProperty(other, key) || map[key] !== other[key]) { - return false; - } - } - return true; - } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -4832,7 +5461,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -4841,14 +5470,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = {}; + sourceFile.resolvedModules = ts.createMap(); } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = {}; + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -4867,7 +5496,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; + var oldResolution = oldResolutions && oldResolutions[names[i]]; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -4880,17 +5509,17 @@ var ts; ts.hasChangesInResolutions = hasChangesInResolutions; function containsParseError(node) { aggregateChildData(node); - return (node.flags & 268435456) !== 0; + return (node.flags & 2097152) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 536870912)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864) !== 0) || + if (!(node.flags & 4194304)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 524288) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.flags |= 268435456; + node.flags |= 2097152; } - node.flags |= 536870912; + node.flags |= 4194304; } } function getSourceFileOfNode(node) { @@ -4927,6 +5556,10 @@ var ts; return node.pos; } ts.getStartPosOfNode = getStartPosOfNode; + function isDefined(value) { + return value !== undefined; + } + ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -4947,7 +5580,7 @@ var ts; } ts.getEndLinePosition = getEndLinePosition; function nodeIsMissing(node) { - if (!node) { + if (node === undefined) { return true; } return node.pos === node.end && node.pos >= 0 && node.kind !== 1; @@ -4967,16 +5600,20 @@ var ts; if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { return getTokenPosOfNode(node.jsDocComments[0]); } - if (node.kind === 282 && node._children.length > 0) { + if (node.kind === 286 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 281; + return node.kind >= 257 && node.kind <= 282; } ts.isJSDocNode = isJSDocNode; + function isJSDocTag(node) { + return node.kind >= 273 && node.kind <= 285; + } + ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5005,6 +5642,50 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getLiteralText(node, sourceFile, languageVersion) { + if (languageVersion < 2 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + return getQuotedEscapedLiteralText('"', node.text, '"'); + } + if (!nodeIsSynthesized(node) && node.parent) { + var text = getSourceTextOfNodeFromSourceFile(sourceFile, node); + if (languageVersion < 2 && isBinaryOrOctalIntegerLiteral(node, text)) { + return node.text; + } + return text; + } + switch (node.kind) { + case 9: + return getQuotedEscapedLiteralText('"', node.text, '"'); + case 11: + return getQuotedEscapedLiteralText("`", node.text, "`"); + case 12: + return getQuotedEscapedLiteralText("`", node.text, "${"); + case 13: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 14: + return getQuotedEscapedLiteralText("}", node.text, "`"); + case 8: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function isBinaryOrOctalIntegerLiteral(node, text) { + if (node.kind === 8 && text.length > 1) { + switch (text.charCodeAt(1)) { + case 98: + case 66: + case 111: + case 79: + return true; + } + } + return false; + } + ts.isBinaryOrOctalIntegerLiteral = isBinaryOrOctalIntegerLiteral; + function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { + return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + } function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; } @@ -5018,7 +5699,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 3072) !== 0 || + return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -5027,19 +5708,21 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { return node.kind === 225 && (!node.body); } - ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || - isFunctionLike(node) || - isFunctionBlock(node); + isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { - return !!(module.flags & 131072); + return !!(module.flags & 512); } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { @@ -5055,26 +5738,35 @@ var ts; return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 256: + case 227: + case 252: + case 225: + case 206: + case 207: + case 208: + case 148: + case 147: + case 149: + case 150: + case 220: + case 179: + case 180: + return true; + case 199: + return parentNode && !isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { - if (isFunctionLike(current)) { + if (isBlockScope(current, current.parent)) { return current; } - switch (current.kind) { - case 256: - case 227: - case 252: - case 225: - case 206: - case 207: - case 208: - return current; - case 199: - if (!isFunctionLike(current.parent)) { - return current; - } - } current = current.parent; } } @@ -5176,34 +5868,13 @@ var ts; return node.kind === 224 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 || isBindingPattern(node))) { - node = node.parent; - } - return node; - } - function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 218) { - node = node.parent; - } - if (node && node.kind === 219) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 200) { - flags |= node.flags; - } - return flags; - } - ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 2048); + return !!(ts.getCombinedNodeFlags(node) & 2) + || !!(ts.getCombinedModifierFlags(node) & 2048); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 1024); + return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; function isSuperCallExpression(n) { @@ -5244,7 +5915,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; - function isTypeNode(node) { + function isPartOfTypeNode(node) { if (154 <= node.kind && node.kind <= 166) { return true; } @@ -5268,7 +5939,7 @@ var ts; else if (node.parent.kind === 172 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 139: case 172: case 97: @@ -5313,7 +5984,7 @@ var ts; } return false; } - ts.isTypeNode = isTypeNode; + ts.isPartOfTypeNode = isPartOfTypeNode; function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { @@ -5359,13 +6030,13 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_6 = node.name; - if (name_6 && name_6.kind === 140) { - traverse(name_6.expression); + var name_7 = node.name; + if (name_7 && name_7.kind === 140) { + traverse(name_7.expression); return; } } - else if (!isTypeNode(node)) { + else if (!isPartOfTypeNode(node)) { ts.forEachChild(node, traverse); } } @@ -5578,18 +6249,19 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; - function isSuperPropertyOrElementAccess(node) { - return (node.kind === 172 - || node.kind === 173) + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 172 || kind === 173) && node.expression.kind === 95; } - ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; + ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { case 155: return node.typeName; case 194: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -5599,6 +6271,18 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function isCallLikeExpression(node) { + switch (node.kind) { + case 174: + case 175: + case 176: + case 143: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { if (node.kind === 176) { return node.tag; @@ -5632,14 +6316,20 @@ var ts; && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function isPropertyAccessExpression(node) { - return node.kind === 172; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isElementAccessExpression(node) { - return node.kind === 173; + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 221: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 147: + case 150: + return ts.forEach(node.parameters, nodeIsDecorated); + } } - ts.isElementAccessExpression = isElementAccessExpression; + ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; if (parent.kind === 243 || @@ -5650,7 +6340,7 @@ var ts; return false; } ts.isJSXTagName = isJSXTagName; - function isExpression(node) { + function isPartOfExpression(node) { switch (node.kind) { case 97: case 95: @@ -5745,16 +6435,16 @@ var ts; case 194: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: - if (isExpression(parent_3)) { + if (isPartOfExpression(parent_3)) { return true; } } } return false; } - ts.isExpression = isExpression; + ts.isPartOfExpression = isPartOfExpression; function isExternalModuleNameRelative(moduleName) { - return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + return /^\.\.?($|[\\/])/.test(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { @@ -5781,7 +6471,7 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 134217728); + return node && !!(node.flags & 1048576); } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression, checkArgumentIsStringLiteral) { @@ -5861,6 +6551,22 @@ var ts; } } ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + if (node.kind === 229) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { + return importClause.namedBindings; + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 230 + && node.importClause + && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { @@ -5887,31 +6593,62 @@ var ts; if (!node) { return undefined; } - var jsDocComments = getJSDocComments(node, checkParentVariableStatement); - if (!jsDocComments) { + var jsDocTags = getJSDocTags(node, checkParentVariableStatement); + if (!jsDocTags) { return undefined; } - for (var _i = 0, jsDocComments_1 = jsDocComments; _i < jsDocComments_1.length; _i++) { - var jsDocComment = jsDocComments_1[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === kind) { - return tag; - } + for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { + var tag = jsDocTags_1[_i]; + if (tag.kind === kind) { + return tag; } } } - function getJSDocComments(node, checkParentVariableStatement) { - if (node.jsDocComments) { - return node.jsDocComments; + function append(previous, additional) { + if (additional) { + if (!previous) { + previous = []; + } + for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { + var x = additional_1[_i]; + previous.push(x); + } } + return previous; + } + function getJSDocComments(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); + } + ts.getJSDocComments = getJSDocComments; + function getJSDocTags(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { + var result = []; + for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { + var doc = docs_1[_i]; + if (doc.tags) { + result.push.apply(result, doc.tags); + } + } + return result; + }, function (tags) { return tags; }); + } + function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { + var result = undefined; if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 218 && - node.parent.initializer === node && + var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && + (node.parent).initializer === node && node.parent.parent.parent.kind === 200; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + var isVariableOfVariableDeclarationStatement = isVariableLike(node) && + node.parent.parent.kind === 200; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : + isVariableOfVariableDeclarationStatement ? node.parent.parent : + undefined; if (variableStatementNode) { - return variableStatementNode.jsDocComments; + result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 225 && + node.parent && node.parent.kind === 225) { + result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } var parent_4 = node.parent; var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && @@ -5919,14 +6656,52 @@ var ts; parent_4.operatorToken.kind === 56 && parent_4.parent.kind === 202; if (isSourceOfAssignmentExpressionStatement) { - return parent_4.parent.jsDocComments; + result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); } var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; if (isPropertyAssignmentExpression) { - return parent_4.jsDocComments; + result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 142) { + var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); + if (paramTags) { + result = append(result, getTags(paramTags)); + } } } - return undefined; + if (isVariableLike(node) && node.initializer) { + result = append(result, getJSDocs(node.initializer, false, getDocs, getTags)); + } + if (node.jsDocComments) { + if (result) { + result = append(result, getDocs(node.jsDocComments)); + } + else { + return getDocs(node.jsDocComments); + } + } + return result; + } + function getJSDocParameterTag(param, checkParentVariableStatement) { + var func = param.parent; + var tags = getJSDocTags(func, checkParentVariableStatement); + if (!param.name) { + var i = func.parameters.indexOf(param); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275; }); + if (paramTags && 0 <= i && i < paramTags.length) { + return [paramTags[i]]; + } + } + else if (param.name.kind === 69) { + var name_8 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); + if (paramTags) { + return paramTags; + } + } + else { + return undefined; + } } function getJSDocTypeTag(node) { return getJSDocTag(node, 277, false); @@ -5943,19 +6718,16 @@ var ts; function getCorrespondingJSDocParameterTag(parameter) { if (parameter.name && parameter.name.kind === 69) { var parameterName = parameter.name.text; - var jsDocComments = getJSDocComments(parameter.parent, true); - if (jsDocComments) { - for (var _i = 0, jsDocComments_2 = jsDocComments; _i < jsDocComments_2.length; _i++) { - var jsDocComment = jsDocComments_2[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === 275) { - var parameterTag = tag; - var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_7.text === parameterName) { - return parameterTag; - } - } + var jsDocTags = getJSDocTags(parameter.parent, true); + if (!jsDocTags) { + return undefined; + } + for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { + var tag = jsDocTags_2[_i]; + if (tag.kind === 275) { + var parameterTag = tag; + if (parameterTag.parameterName.text === parameterName) { + return parameterTag; } } } @@ -5972,7 +6744,7 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 134217728)) { + if (node && (node.flags & 1048576)) { if (node.type && node.type.kind === 270) { return true; } @@ -5988,22 +6760,6 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isLiteralKind(kind) { - return 8 <= kind && kind <= 11; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 || kind === 11; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isTemplateLiteralKind(kind) { - return 11 <= kind && kind <= 14; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isBindingPattern(node) { - return !!node && (node.kind === 168 || node.kind === 167); - } - ts.isBindingPattern = isBindingPattern; function isAssignmentTarget(node) { while (node.parent.kind === 178) { node = node.parent; @@ -6019,14 +6775,14 @@ var ts; continue; } return parent_5.kind === 187 && - parent_5.operatorToken.kind === 56 && + isAssignmentOperator(parent_5.operatorToken.kind) && parent_5.left === node || (parent_5.kind === 207 || parent_5.kind === 208) && parent_5.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; - function isNodeDescendentOf(node, ancestor) { + function isNodeDescendantOf(node, ancestor) { while (node) { if (node === ancestor) return true; @@ -6034,10 +6790,10 @@ var ts; } return false; } - ts.isNodeDescendentOf = isNodeDescendentOf; + ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (node.flags & 2 || (node.kind === 256 && node.isDeclarationFile)) { + if (hasModifier(node, 2) || (node.kind === 256 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6045,84 +6801,6 @@ var ts; return false; } ts.isInAmbientContext = isInAmbientContext; - function isDeclaration(node) { - switch (node.kind) { - case 180: - case 169: - case 221: - case 192: - case 148: - case 224: - case 255: - case 238: - case 220: - case 179: - case 149: - case 231: - case 229: - case 234: - case 222: - case 147: - case 146: - case 225: - case 232: - case 142: - case 253: - case 145: - case 144: - case 150: - case 254: - case 223: - case 141: - case 218: - case 279: - return true; - } - return false; - } - ts.isDeclaration = isDeclaration; - function isStatement(n) { - switch (n.kind) { - case 210: - case 209: - case 217: - case 204: - case 202: - case 201: - case 207: - case 208: - case 206: - case 203: - case 214: - case 211: - case 213: - case 215: - case 216: - case 200: - case 205: - case 212: - case 235: - return true; - default: - return false; - } - } - ts.isStatement = isStatement; - function isClassElement(n) { - switch (n.kind) { - case 148: - case 145: - case 147: - case 149: - case 150: - case 146: - case 153: - return true; - default: - return false; - } - } - ts.isClassElement = isClassElement; function isDeclarationName(name) { if (name.kind !== 69 && name.kind !== 9 && name.kind !== 8) { return false; @@ -6182,9 +6860,13 @@ var ts; node.kind === 232 || node.kind === 234 || node.kind === 238 || - node.kind === 235 && node.expression.kind === 69; + node.kind === 235 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + return isEntityNameExpression(node.expression); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -6272,7 +6954,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node); + return isFunctionLike(node) && hasModifier(node, 256) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; function isStringOrNumericLiteral(kind) { @@ -6348,63 +7030,238 @@ var ts; return node; } ts.getRootDeclaration = getRootDeclaration; - function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 225 || n.kind === 256; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 148 + || kind === 179 + || kind === 220 + || kind === 180 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 225 + || kind === 256; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneNode(node, location, flags, parent) { - var clone = location !== undefined - ? ts.createNode(node.kind, location.pos, location.end) - : createSynthesizedNode(node.kind); - for (var key in node) { - if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { - continue; - } - clone[key] = node[key]; - } - if (flags !== undefined) { - clone.flags = flags; - } - if (parent !== undefined) { - clone.parent = parent; - } - return clone; - } - ts.cloneNode = cloneNode; - function cloneEntityName(node, parent) { - var clone = cloneNode(node, node, node.flags, parent); - if (isQualifiedName(clone)) { - var left = clone.left, right = clone.right; - clone.left = cloneEntityName(left, clone); - clone.right = cloneNode(right, right, right.flags, parent); - } - return clone; - } - ts.cloneEntityName = cloneEntityName; - function isQualifiedName(node) { - return node.kind === 139; - } - ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { - return node.pos === -1; + return positionIsSynthesized(node.pos) + || positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function createSynthesizedNode(kind, startsOnNewLine) { - var node = ts.createNode(kind, -1, -1); - node.startsOnNewLine = startsOnNewLine; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function getOriginalNode(node) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } return node; } - ts.createSynthesizedNode = createSynthesizedNode; - function createSynthesizedNodeArray() { - var array = []; - array.pos = -1; - array.end = -1; - return array; + ts.getOriginalNode = getOriginalNode; + function isParseTreeNode(node) { + return (node.flags & 8) === 0; } - ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function getOriginalSourceFiles(sourceFiles) { + var originalSourceFiles = []; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + var originalSourceFile = getParseTreeNode(sourceFile, isSourceFile); + if (originalSourceFile) { + originalSourceFiles.push(originalSourceFile); + } + } + return originalSourceFiles; + } + ts.getOriginalSourceFiles = getOriginalSourceFiles; + function getOriginalNodeId(node) { + node = getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 175: + return hasArguments ? 0 : 1; + case 185: + case 182: + case 183: + case 181: + case 184: + case 188: + case 190: + return 1; + case 187: + switch (operator) { + case 38: + case 56: + case 57: + case 58: + case 60: + case 59: + case 61: + case 62: + case 63: + case 64: + case 65: + case 66: + case 68: + case 67: + return 1; + } + } + return 0; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 187) { + return expression.operatorToken.kind; + } + else if (expression.kind === 185 || expression.kind === 186) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 97: + case 95: + case 69: + case 93: + case 99: + case 84: + case 8: + case 9: + case 170: + case 171: + case 179: + case 180: + case 192: + case 241: + case 242: + case 10: + case 11: + case 189: + case 178: + case 193: + return 19; + case 176: + case 172: + case 173: + return 18; + case 175: + return hasArguments ? 18 : 17; + case 174: + return 17; + case 186: + return 16; + case 185: + case 182: + case 183: + case 181: + case 184: + return 15; + case 187: + switch (operatorKind) { + case 49: + case 50: + return 15; + case 38: + case 37: + case 39: + case 40: + return 14; + case 35: + case 36: + return 13; + case 43: + case 44: + case 45: + return 12; + case 25: + case 28: + case 27: + case 29: + case 90: + case 91: + return 11; + case 30: + case 32: + case 31: + case 33: + return 10; + case 46: + return 9; + case 48: + return 8; + case 47: + return 7; + case 51: + return 6; + case 52: + return 5; + case 56: + case 57: + case 58: + case 60: + case 59: + case 61: + case 62: + case 63: + case 64: + case 65: + case 66: + case 68: + case 67: + return 3; + case 24: + return 0; + default: + return -1; + } + case 188: + return 4; + case 190: + return 2; + case 191: + return 1; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6457,9 +7314,7 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); - } + ts.forEach(fileDiagnostics[key], pushDiagnostic); } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -6470,15 +7325,13 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); - } + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } } } ts.createDiagnosticCollection = createDiagnosticCollection; var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { + var escapedCharsMap = ts.createMap({ "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -6491,7 +7344,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }; + }); function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -6594,10 +7447,23 @@ var ts; getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, reset: reset }; } ts.createTextWriter = createTextWriter; + function getResolvedExternalModuleName(host, file) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; function getExternalModuleNameFromPath(host, fileName) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); @@ -6639,6 +7505,69 @@ var ts; getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; } ts.getEmitModuleKind = getEmitModuleKind; + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + var moduleKind = getEmitModuleKind(options); + var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var sourceFiles = host.getSourceFiles(); + return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, isNonDeclarationFile); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function isNonDeclarationFile(sourceFile) { + return !isDeclarationFile(sourceFile); + } + function isBundleEmitNonExternalModule(sourceFile) { + return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + function forEachTransformedEmitFile(host, sourceFiles, action) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + onBundledEmit(host, sourceFiles); + } + else { + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var extension = ".js"; + if (options.jsx === 1) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); + } + function onBundledEmit(host, sourceFiles) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, true); + } + } + } + ts.forEachTransformedEmitFile = forEachTransformedEmitFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -6646,8 +7575,8 @@ var ts; } else { var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { onSingleFileEmit(host, sourceFile); } @@ -6688,9 +7617,6 @@ var ts; action(emitFileNames, bundledSources, true); } } - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } } ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { @@ -6752,7 +7678,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 149 || member.kind === 150) - && (member.flags & 32) === (accessor.flags & 32)) { + && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -6781,30 +7707,47 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { - if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } - ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { - var emitLeadingSpace = !trailingSeparator; - ts.forEach(comments, function (comment) { - if (emitLeadingSpace) { - writer.write(" "); - emitLeadingSpace = false; - } - writeComment(text, lineMap, writer, comment, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - else if (trailingSeparator) { + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { writer.write(" "); } - else { - emitLeadingSpace = true; + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.write(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } } - }); + if (emitInterveningSeparator && trailingSeparator) { + writer.write(" "); + } + } } ts.emitComments = emitComments; function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { @@ -6838,7 +7781,7 @@ var ts; var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments(text, lineMap, writer, detachedComments, true, newLine, writeComment); + emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } @@ -6850,18 +7793,18 @@ var ts; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(text, lineMap, writer, comment, newLine) { - if (text.charCodeAt(comment.pos + 1) === 42) { - var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); var lineCount = lineMap.length; var firstCommentLineIndent = void 0; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount ? text.length + 1 : lineMap[currentLine + 1]; - if (pos !== comment.pos) { + if (pos !== commentPos) { if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); } var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); @@ -6878,21 +7821,21 @@ var ts; writer.rawWrite(""); } } - writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { - writer.write(text.substring(comment.pos, comment.end)); + writer.write(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; - function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { writer.write(currentLineText); - if (end !== comment.end) { + if (end !== commentEnd) { writer.writeLine(); } } @@ -6912,6 +7855,32 @@ var ts; } return currentLineIndent; } + function hasModifiers(node) { + return getModifierFlags(node) !== 0; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return (getModifierFlags(node) & flags) !== 0; + } + ts.hasModifier = hasModifier; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912) { + return node.modifierFlagsCache & ~536870912; + } + var flags = 0; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4) { + flags |= 1; + } + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { case 113: return 32; @@ -6929,49 +7898,35 @@ var ts; return 0; } ts.modifierToFlag = modifierToFlag; - function isLeftHandSideExpression(expr) { - if (expr) { - switch (expr.kind) { - case 172: - case 173: - case 175: - case 174: - case 196: - case 241: - case 242: - case 176: - case 170: - case 178: - case 171: - case 192: - case 179: - case 69: - case 10: - case 8: - case 9: - case 11: - case 189: - case 84: - case 93: - case 97: - case 99: - case 95: - return true; - } - } - return false; + function isLogicalOperator(token) { + return token === 52 + || token === 51 + || token === 49; } - ts.isLeftHandSideExpression = isLeftHandSideExpression; + ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { return token >= 56 && token <= 68; } ts.isAssignmentOperator = isAssignmentOperator; - function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 194 && + function tryGetClassExtendingExpressionWithTypeArguments(node) { + if (node.kind === 194 && node.parent.token === 83 && - isClassLike(node.parent.parent); + isClassLike(node.parent.parent)) { + return node.parent.parent; + } } - ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isDestructuringAssignment(node) { + if (isBinaryExpression(node)) { + if (node.operatorToken.kind === 56) { + var kind = node.left.kind; + return kind === 171 + || kind === 170; + } + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; function isSupportedExpressionWithTypeArguments(node) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } @@ -6987,6 +7942,15 @@ var ts; return false; } } + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 69 || + node.kind === 172 && isEntityNameExpression(node.expression); + } + ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 && node.parent.right === node) || (node.parent.kind === 172 && node.parent.name === node); @@ -7004,7 +7968,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { @@ -7015,6 +7979,10 @@ var ts; return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function tryExtractTypeScriptExtension(fileName) { + return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -7071,7 +8039,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -7122,6 +8090,738 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; + function isSimpleExpression(node) { + return isSimpleExpressionWorker(node, 0); + } + ts.isSimpleExpression = isSimpleExpression; + function isSimpleExpressionWorker(node, depth) { + if (depth <= 5) { + var kind = node.kind; + if (kind === 9 + || kind === 8 + || kind === 10 + || kind === 11 + || kind === 69 + || kind === 97 + || kind === 95 + || kind === 99 + || kind === 84 + || kind === 93) { + return true; + } + else if (kind === 172) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 173) { + return isSimpleExpressionWorker(node.expression, depth + 1) + && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + } + else if (kind === 185 + || kind === 186) { + return isSimpleExpressionWorker(node.operand, depth + 1); + } + else if (kind === 187) { + return node.operatorToken.kind !== 38 + && isSimpleExpressionWorker(node.left, depth + 1) + && isSimpleExpressionWorker(node.right, depth + 1); + } + else if (kind === 188) { + return isSimpleExpressionWorker(node.condition, depth + 1) + && isSimpleExpressionWorker(node.whenTrue, depth + 1) + && isSimpleExpressionWorker(node.whenFalse, depth + 1); + } + else if (kind === 183 + || kind === 182 + || kind === 181) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 170) { + return node.elements.length === 0; + } + else if (kind === 171) { + return node.properties.length === 0; + } + else if (kind === 174) { + if (!isSimpleExpressionWorker(node.expression, depth + 1)) { + return false; + } + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (!isSimpleExpressionWorker(argument, depth + 1)) { + return false; + } + } + return true; + } + } + return false; + } + var syntaxKindCache = ts.createMap(); + function formatSyntaxKind(kind) { + var syntaxKindEnum = ts.SyntaxKind; + if (syntaxKindEnum) { + if (syntaxKindCache[kind]) { + return syntaxKindCache[kind]; + } + for (var name_9 in syntaxKindEnum) { + if (syntaxKindEnum[name_9] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")"; + } + } + } + else { + return kind.toString(); + } + } + ts.formatSyntaxKind = formatSyntaxKind; + function movePos(pos, value) { + return positionIsSynthesized(pos) ? -1 : pos + value; + } + ts.movePos = movePos; + function createRange(pos, end) { + return { pos: pos, end: end }; + } + ts.createRange = createRange; + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + function collapseRangeToStart(range) { + return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); + } + ts.collapseRangeToStart = collapseRangeToStart; + function collapseRangeToEnd(range) { + return isCollapsedRange(range) ? range : moveRangePos(range, range.end); + } + ts.collapseRangeToEnd = collapseRangeToEnd; + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function collectExternalModuleInfo(sourceFile, resolver) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 230: + if (!node.importClause || + resolver.isReferencedAliasDeclaration(node.importClause, true)) { + externalImports.push(node); + } + break; + case 229: + if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { + externalImports.push(node); + } + break; + case 236: + if (node.moduleSpecifier) { + if (!node.exportClause) { + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + } + else if (resolver.isValueAliasDeclaration(node)) { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + var name_10 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); + } + } + break; + case 235: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isMergedWithClass(node) { + if (node.symbol) { + for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 221 && declaration !== node) { + return true; + } + } + } + return false; + } + ts.isMergedWithClass = isMergedWithClass; + function isFirstDeclarationOfKind(node, kind) { + return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; + } + ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 11; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 11; + } + ts.isLiteralKind = isLiteralKind; + function isTextualLiteralKind(kind) { + return kind === 9 || kind === 11; + } + ts.isTextualLiteralKind = isTextualLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 11 <= kind && kind <= 14; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralFragmentKind(kind) { + return kind === 12 + || kind === 13 + || kind === 14; + } + function isTemplateLiteralFragment(node) { + return isTemplateLiteralFragmentKind(node.kind); + } + ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + function isIdentifier(node) { + return node.kind === 69; + } + ts.isIdentifier = isIdentifier; + function isGeneratedIdentifier(node) { + return isIdentifier(node) && node.autoGenerateKind > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isQualifiedName(node) { + return node.kind === 139; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 140; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isEntityName(node) { + var kind = node.kind; + return kind === 139 + || kind === 69; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 69 + || kind === 9 + || kind === 8 + || kind === 140; + } + ts.isPropertyName = isPropertyName; + function isModuleName(node) { + var kind = node.kind; + return kind === 69 + || kind === 9; + } + ts.isModuleName = isModuleName; + function isBindingName(node) { + var kind = node.kind; + return kind === 69 + || kind === 167 + || kind === 168; + } + ts.isBindingName = isBindingName; + function isTypeParameter(node) { + return node.kind === 141; + } + ts.isTypeParameter = isTypeParameter; + function isParameter(node) { + return node.kind === 142; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 143; + } + ts.isDecorator = isDecorator; + function isMethodDeclaration(node) { + return node.kind === 147; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isClassElement(node) { + var kind = node.kind; + return kind === 148 + || kind === 145 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 153 + || kind === 198; + } + ts.isClassElement = isClassElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 253 + || kind === 254 + || kind === 147 + || kind === 149 + || kind === 150 + || kind === 239; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNodeKind(kind) { + return (kind >= 154 && kind <= 166) + || kind === 117 + || kind === 130 + || kind === 120 + || kind === 132 + || kind === 133 + || kind === 103 + || kind === 127 + || kind === 194; + } + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 168 + || kind === 167; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isBindingElement(node) { + return node.kind === 169; + } + ts.isBindingElement = isBindingElement; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 169 + || kind === 193; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isPropertyAccessExpression(node) { + return node.kind === 172; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 173; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isBinaryExpression(node) { + return node.kind === 187; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 188; + } + ts.isConditionalExpression = isConditionalExpression; + function isCallExpression(node) { + return node.kind === 174; + } + ts.isCallExpression = isCallExpression; + function isTemplate(node) { + var kind = node.kind; + return kind === 189 + || kind === 11; + } + ts.isTemplate = isTemplate; + function isSpreadElementExpression(node) { + return node.kind === 191; + } + ts.isSpreadElementExpression = isSpreadElementExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 194; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isLeftHandSideExpressionKind(kind) { + return kind === 172 + || kind === 173 + || kind === 175 + || kind === 174 + || kind === 241 + || kind === 242 + || kind === 176 + || kind === 170 + || kind === 178 + || kind === 171 + || kind === 192 + || kind === 179 + || kind === 69 + || kind === 10 + || kind === 8 + || kind === 9 + || kind === 11 + || kind === 189 + || kind === 84 + || kind === 93 + || kind === 97 + || kind === 99 + || kind === 95 + || kind === 196; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 185 + || kind === 186 + || kind === 181 + || kind === 182 + || kind === 183 + || kind === 184 + || kind === 177 + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 188 + || kind === 190 + || kind === 180 + || kind === 187 + || kind === 191 + || kind === 195 + || kind === 193 + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 177 + || kind === 195; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isOmittedExpression(node) { + return node.kind === 193; + } + ts.isOmittedExpression = isOmittedExpression; + function isTemplateSpan(node) { + return node.kind === 197; + } + ts.isTemplateSpan = isTemplateSpan; + function isBlock(node) { + return node.kind === 199; + } + ts.isBlock = isBlock; + function isConciseBody(node) { + return isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isVariableDeclaration(node) { + return node.kind === 218; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 219; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isCaseBlock(node) { + return node.kind === 227; + } + ts.isCaseBlock = isCaseBlock; + function isModuleBody(node) { + var kind = node.kind; + return kind === 226 + || kind === 225; + } + ts.isModuleBody = isModuleBody; + function isImportEqualsDeclaration(node) { + return node.kind === 229; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportClause(node) { + return node.kind === 231; + } + ts.isImportClause = isImportClause; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 233 + || kind === 232; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isImportSpecifier(node) { + return node.kind === 234; + } + ts.isImportSpecifier = isImportSpecifier; + function isNamedExports(node) { + return node.kind === 237; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 238; + } + ts.isExportSpecifier = isExportSpecifier; + function isModuleOrEnumDeclaration(node) { + return node.kind === 225 || node.kind === 224; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 180 + || kind === 169 + || kind === 221 + || kind === 192 + || kind === 148 + || kind === 224 + || kind === 255 + || kind === 238 + || kind === 220 + || kind === 179 + || kind === 149 + || kind === 231 + || kind === 229 + || kind === 234 + || kind === 222 + || kind === 147 + || kind === 146 + || kind === 225 + || kind === 228 + || kind === 232 + || kind === 142 + || kind === 253 + || kind === 145 + || kind === 144 + || kind === 150 + || kind === 254 + || kind === 223 + || kind === 141 + || kind === 218 + || kind === 279; + } + function isDeclarationStatementKind(kind) { + return kind === 220 + || kind === 239 + || kind === 221 + || kind === 222 + || kind === 223 + || kind === 224 + || kind === 225 + || kind === 230 + || kind === 229 + || kind === 236 + || kind === 235 + || kind === 228; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 210 + || kind === 209 + || kind === 217 + || kind === 204 + || kind === 202 + || kind === 201 + || kind === 207 + || kind === 208 + || kind === 206 + || kind === 203 + || kind === 214 + || kind === 211 + || kind === 213 + || kind === 215 + || kind === 216 + || kind === 200 + || kind === 205 + || kind === 212 + || kind === 287; + } + function isDeclaration(node) { + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 199; + } + ts.isStatement = isStatement; + function isModuleReference(node) { + var kind = node.kind; + return kind === 240 + || kind === 139 + || kind === 69; + } + ts.isModuleReference = isModuleReference; + function isJsxOpeningElement(node) { + return node.kind === 243; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 245; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 97 + || kind === 69 + || kind === 172; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 241 + || kind === 248 + || kind === 242 + || kind === 244; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 246 + || kind === 247; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isJsxSpreadAttribute(node) { + return node.kind === 247; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxAttribute(node) { + return node.kind === 246; + } + ts.isJsxAttribute = isJsxAttribute; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 + || kind === 248; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 249 + || kind === 250; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isHeritageClause(node) { + return node.kind === 251; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 252; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 253; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 254; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isEnumMember(node) { + return node.kind === 255; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 256; + } + ts.isSourceFile = isSourceFile; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } @@ -7259,28 +8959,2230 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 169 || ts.isBindingPattern(node))) { + node = node.parent; + } + return node; } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return str.indexOf(suffix, expectedPos) === expectedPos; + function getCombinedModifierFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = ts.getModifierFlags(node); + if (node.kind === 218) { + node = node.parent; + } + if (node && node.kind === 219) { + flags |= ts.getModifierFlags(node); + node = node.parent; + } + if (node && node.kind === 200) { + flags |= ts.getModifierFlags(node); + } + return flags; } - ts.endsWith = endsWith; + ts.getCombinedModifierFlags = getCombinedModifierFlags; + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 218) { + node = node.parent; + } + if (node && node.kind === 219) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 200) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; })(ts || (ts = {})); var ts; (function (ts) { - ts.parseTime = 0; var NodeConstructor; var SourceFileConstructor; + function createNode(kind, location, flags) { + var ConstructorForKind = kind === 256 + ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) + : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); + var node = location + ? new ConstructorForKind(kind, location.pos, location.end) + : new ConstructorForKind(kind, -1, -1); + node.flags = flags | 8; + return node; + } + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + if (original.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + function createNodeArray(elements, location, hasTrailingComma) { + if (elements) { + if (ts.isNodeArray(elements)) { + return elements; + } + } + else { + elements = []; + } + var array = elements; + if (location) { + array.pos = location.pos; + array.end = location.end; + } + else { + array.pos = -1; + array.end = -1; + } + if (hasTrailingComma) { + array.hasTrailingComma = true; + } + return array; + } + ts.createNodeArray = createNodeArray; + function createSynthesizedNode(kind, startsOnNewLine) { + var node = createNode(kind, undefined); + node.startsOnNewLine = startsOnNewLine; + return node; + } + ts.createSynthesizedNode = createSynthesizedNode; + function createSynthesizedNodeArray(elements) { + return createNodeArray(elements, undefined); + } + ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + function getSynthesizedClone(node) { + var clone = createNode(node.kind, undefined, node.flags); + clone.original = node; + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + function createLiteral(value, location) { + if (typeof value === "number") { + var node = createNode(8, location, undefined); + node.text = value.toString(); + return node; + } + else if (typeof value === "boolean") { + return createNode(value ? 99 : 84, location, undefined); + } + else if (typeof value === "string") { + var node = createNode(9, location, undefined); + node.text = value; + return node; + } + else { + var node = createNode(9, location, undefined); + node.textSourceNode = value; + node.text = value.text; + return node; + } + } + ts.createLiteral = createLiteral; + var nextAutoGenerateId = 0; + function createIdentifier(text, location) { + var node = createNode(69, location); + node.text = ts.escapeIdentifier(text); + node.originalKeywordKind = ts.stringToToken(text); + node.autoGenerateKind = 0; + node.autoGenerateId = 0; + return node; + } + ts.createIdentifier = createIdentifier; + function createTempVariable(recordTempVariable, location) { + var name = createNode(69, location); + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 1; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + return name; + } + ts.createTempVariable = createTempVariable; + function createLoopVariable(location) { + var name = createNode(69, location); + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 2; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + function createUniqueName(text, location) { + var name = createNode(69, location); + name.text = text; + name.originalKeywordKind = 0; + name.autoGenerateKind = 3; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function getGeneratedNameForNode(node, location) { + var name = createNode(69, location); + name.original = node; + name.text = ""; + name.originalKeywordKind = 0; + name.autoGenerateKind = 4; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + function createToken(token) { + return createNode(token); + } + ts.createToken = createToken; + function createSuper() { + var node = createNode(95); + return node; + } + ts.createSuper = createSuper; + function createThis(location) { + var node = createNode(97, location); + return node; + } + ts.createThis = createThis; + function createNull() { + var node = createNode(93); + return node; + } + ts.createNull = createNull; + function createComputedPropertyName(expression, location) { + var node = createNode(140, location); + node.expression = expression; + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + if (node.expression !== expression) { + return updateNode(createComputedPropertyName(expression, node), node); + } + return node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + function createParameter(name, initializer, location) { + return createParameterDeclaration(undefined, undefined, undefined, name, undefined, undefined, initializer, location); + } + ts.createParameter = createParameter; + function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(142, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameterDeclaration = createParameterDeclaration; + function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); + } + return node; + } + ts.updateParameterDeclaration = updateParameterDeclaration; + function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { + var node = createNode(145, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer, node), node); + } + return node; + } + ts.updateProperty = updateProperty; + function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(147, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createMethod(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body, location, flags) { + var node = createNode(148, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body) { + return updateNode(createConstructor(decorators, modifiers, parameters, body, node, node.flags), node); + } + return node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { + var node = createNode(149, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { + var node = createNode(150, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body) { + return updateNode(createSetAccessor(decorators, modifiers, name, parameters, body, node, node.flags), node); + } + return node; + } + ts.updateSetAccessor = updateSetAccessor; + function createObjectBindingPattern(elements, location) { + var node = createNode(167, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createObjectBindingPattern(elements, node), node); + } + return node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements, location) { + var node = createNode(168, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayBindingPattern(elements, node), node); + } + return node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { + var node = createNode(169, location); + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + } + return node; + } + ts.updateBindingElement = updateBindingElement; + function createArrayLiteral(elements, location, multiLine) { + var node = createNode(170, location); + node.elements = parenthesizeListElements(createNodeArray(elements)); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayLiteral(elements, node, node.multiLine), node); + } + return node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, location, multiLine) { + var node = createNode(171, location); + node.properties = createNodeArray(properties); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + if (node.properties !== properties) { + return updateNode(createObjectLiteral(properties, node, node.multiLine), node); + } + return node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name, location, flags) { + var node = createNode(172, location, flags); + node.expression = parenthesizeForAccess(expression); + node.emitFlags = 1048576; + node.name = typeof name === "string" ? createIdentifier(name) : name; + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + if (node.expression !== expression || node.name !== name) { + var propertyAccess = createPropertyAccess(expression, name, node, node.flags); + propertyAccess.emitFlags = node.emitFlags; + return updateNode(propertyAccess, node); + } + return node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index, location) { + var node = createNode(173, location); + node.expression = parenthesizeForAccess(expression); + node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + if (node.expression !== expression || node.argumentExpression !== argumentExpression) { + return updateNode(createElementAccess(expression, argumentExpression, node), node); + } + return node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(174, location, flags); + node.expression = parenthesizeForAccess(expression); + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + node.arguments = parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + if (expression !== node.expression || typeArguments !== node.typeArguments || argumentsArray !== node.arguments) { + return updateNode(createCall(expression, typeArguments, argumentsArray, node, node.flags), node); + } + return node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(175, location, flags); + node.expression = parenthesizeForNew(expression); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + if (node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray) { + return updateNode(createNew(expression, typeArguments, argumentsArray, node, node.flags), node); + } + return node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, template, location) { + var node = createNode(176, location); + node.tag = parenthesizeForAccess(tag); + node.template = template; + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, template) { + if (node.tag !== tag || node.template !== template) { + return updateNode(createTaggedTemplate(tag, template, node), node); + } + return node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createParen(expression, location) { + var node = createNode(178, location); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + if (node.expression !== expression) { + return updateNode(createParen(expression, node), node); + } + return node; + } + ts.updateParen = updateParen; + function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(179, location, flags); + node.modifiers = undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { + var node = createNode(180, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.body = parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + if (node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body, node, node.flags), node); + } + return node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression, location) { + var node = createNode(181, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + if (node.expression !== expression) { + return updateNode(createDelete(expression, node), expression); + } + return node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression, location) { + var node = createNode(182, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + if (node.expression !== expression) { + return updateNode(createTypeOf(expression, node), expression); + } + return node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression, location) { + var node = createNode(183, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + if (node.expression !== expression) { + return updateNode(createVoid(expression, node), node); + } + return node; + } + ts.updateVoid = updateVoid; + function createAwait(expression, location) { + var node = createNode(184, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + if (node.expression !== expression) { + return updateNode(createAwait(expression, node), node); + } + return node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand, location) { + var node = createNode(185, location); + node.operator = operator; + node.operand = parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPrefix(node.operator, operand, node), node); + } + return node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator, location) { + var node = createNode(186, location); + node.operand = parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPostfix(operand, node.operator, node), node); + } + return node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right, location) { + var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorKind = operatorToken.kind; + var node = createNode(187, location); + node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); + node.operatorToken = operatorToken; + node.right = parenthesizeBinaryOperand(operatorKind, right, false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right) { + if (node.left !== left || node.right !== right) { + return updateNode(createBinary(left, node.operatorToken, right, node), node); + } + return node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { + var node = createNode(188, location); + node.condition = condition; + node.questionToken = questionToken; + node.whenTrue = whenTrue; + node.colonToken = colonToken; + node.whenFalse = whenFalse; + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, whenTrue, whenFalse) { + if (node.condition !== condition || node.whenTrue !== whenTrue || node.whenFalse !== whenFalse) { + return updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse, node), node); + } + return node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans, location) { + var node = createNode(189, location); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + if (node.head !== head || node.templateSpans !== templateSpans) { + return updateNode(createTemplateExpression(head, templateSpans, node), node); + } + return node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createYield(asteriskToken, expression, location) { + var node = createNode(190, location); + node.asteriskToken = asteriskToken; + node.expression = expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, expression) { + if (node.expression !== expression) { + return updateNode(createYield(node.asteriskToken, expression, node), node); + } + return node; + } + ts.updateYield = updateYield; + function createSpread(expression, location) { + var node = createNode(191, location); + node.expression = parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpread(expression, node), node); + } + return node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(192, location); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + if (node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression(location) { + var node = createNode(193, location); + return node; + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression, location) { + var node = createNode(194, location); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.expression = parenthesizeForAccess(expression); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + if (node.typeArguments !== typeArguments || node.expression !== expression) { + return updateNode(createExpressionWithTypeArguments(typeArguments, expression, node), node); + } + return node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + function createTemplateSpan(expression, literal, location) { + var node = createNode(197, location); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + if (node.expression !== expression || node.literal !== literal) { + return updateNode(createTemplateSpan(expression, literal, node), node); + } + return node; + } + ts.updateTemplateSpan = updateTemplateSpan; + function createBlock(statements, location, multiLine, flags) { + var block = createNode(199, location, flags); + block.statements = createNodeArray(statements); + if (multiLine) { + block.multiLine = true; + } + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + if (statements !== node.statements) { + return updateNode(createBlock(statements, node, node.multiLine, node.flags), node); + } + return node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList, location, flags) { + var node = createNode(200, location, flags); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + if (node.modifiers !== modifiers || node.declarationList !== declarationList) { + return updateNode(createVariableStatement(modifiers, declarationList, node, node.flags), node); + } + return node; + } + ts.updateVariableStatement = updateVariableStatement; + function createVariableDeclarationList(declarations, location, flags) { + var node = createNode(219, location, flags); + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + if (node.declarations !== declarations) { + return updateNode(createVariableDeclarationList(declarations, node, node.flags), node); + } + return node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createVariableDeclaration(name, type, initializer, location, flags) { + var node = createNode(218, location, flags); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.type = type; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + if (node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createVariableDeclaration(name, type, initializer, node, node.flags), node); + } + return node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createEmptyStatement(location) { + return createNode(201, location); + } + ts.createEmptyStatement = createEmptyStatement; + function createStatement(expression, location, flags) { + var node = createNode(202, location, flags); + node.expression = parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createStatement = createStatement; + function updateStatement(node, expression) { + if (node.expression !== expression) { + return updateNode(createStatement(expression, node, node.flags), node); + } + return node; + } + ts.updateStatement = updateStatement; + function createIf(expression, thenStatement, elseStatement, location) { + var node = createNode(203, location); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + if (node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement) { + return updateNode(createIf(expression, thenStatement, elseStatement, node), node); + } + return node; + } + ts.updateIf = updateIf; + function createDo(statement, expression, location) { + var node = createNode(204, location); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + if (node.statement !== statement || node.expression !== expression) { + return updateNode(createDo(statement, expression, node), node); + } + return node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement, location) { + var node = createNode(205, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWhile(expression, statement, node), node); + } + return node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement, location) { + var node = createNode(206, location, undefined); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + if (node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement) { + return updateNode(createFor(initializer, condition, incrementor, statement, node), node); + } + return node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement, location) { + var node = createNode(207, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForIn(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForIn = updateForIn; + function createForOf(initializer, expression, statement, location) { + var node = createNode(208, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForOf(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForOf = updateForOf; + function createContinue(label, location) { + var node = createNode(209, location); + if (label) { + node.label = label; + } + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + if (node.label !== label) { + return updateNode(createContinue(label, node), node); + } + return node; + } + ts.updateContinue = updateContinue; + function createBreak(label, location) { + var node = createNode(210, location); + if (label) { + node.label = label; + } + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + if (node.label !== label) { + return updateNode(createBreak(label, node), node); + } + return node; + } + ts.updateBreak = updateBreak; + function createReturn(expression, location) { + var node = createNode(211, location); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + if (node.expression !== expression) { + return updateNode(createReturn(expression, node), node); + } + return node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement, location) { + var node = createNode(212, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWith(expression, statement, node), node); + } + return node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock, location) { + var node = createNode(213, location); + node.expression = parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + if (node.expression !== expression || node.caseBlock !== caseBlock) { + return updateNode(createSwitch(expression, caseBlock, node), node); + } + return node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement, location) { + var node = createNode(214, location); + node.label = typeof label === "string" ? createIdentifier(label) : label; + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + if (node.label !== label || node.statement !== statement) { + return updateNode(createLabel(label, statement, node), node); + } + return node; + } + ts.updateLabel = updateLabel; + function createThrow(expression, location) { + var node = createNode(215, location); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + if (node.expression !== expression) { + return updateNode(createThrow(expression, node), node); + } + return node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock, location) { + var node = createNode(216, location); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + if (node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock) { + return updateNode(createTry(tryBlock, catchClause, finallyBlock, node), node); + } + return node; + } + ts.updateTry = updateTry; + function createCaseBlock(clauses, location) { + var node = createNode(227, location); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + if (node.clauses !== clauses) { + return updateNode(createCaseBlock(clauses, node), node); + } + return node; + } + ts.updateCaseBlock = updateCaseBlock; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(220, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionDeclaration(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + } + return node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(221, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { + var node = createNode(230, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings, location) { + var node = createNode(231, location); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + if (node.name !== name || node.namedBindings !== namedBindings) { + return updateNode(createImportClause(name, namedBindings, node), node); + } + return node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name, location) { + var node = createNode(232, location); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + if (node.name !== name) { + return updateNode(createNamespaceImport(name, node), node); + } + return node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements, location) { + var node = createNode(233, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedImports(elements, node), node); + } + return node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name, location) { + var node = createNode(234, location); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + if (node.propertyName !== propertyName || node.name !== name) { + return updateNode(createImportSpecifier(propertyName, name, node), node); + } + return node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { + var node = createNode(235, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.isExportEquals = isExportEquals; + node.expression = expression; + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.expression !== expression) { + return updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression, node), node); + } + return node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { + var node = createNode(236, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements, location) { + var node = createNode(237, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedExports(elements, node), node); + } + return node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(name, propertyName, location) { + var node = createNode(238, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, name, propertyName) { + if (node.name !== name || node.propertyName !== propertyName) { + return updateNode(createExportSpecifier(name, propertyName, node), node); + } + return node; + } + ts.updateExportSpecifier = updateExportSpecifier; + function createJsxElement(openingElement, children, closingElement, location) { + var node = createNode(241, location); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + if (node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement) { + return updateNode(createJsxElement(openingElement, children, closingElement, node), node); + } + return node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, attributes, location) { + var node = createNode(242, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxSelfClosingElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, attributes, location) { + var node = createNode(243, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxOpeningElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName, location) { + var node = createNode(245, location); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + if (node.tagName !== tagName) { + return updateNode(createJsxClosingElement(tagName, node), node); + } + return node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxAttribute(name, initializer, location) { + var node = createNode(246, location); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createJsxAttribute(name, initializer, node), node); + } + return node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxSpreadAttribute(expression, location) { + var node = createNode(247, location); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxSpreadAttribute(expression, node), node); + } + return node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(expression, location) { + var node = createNode(248, location); + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxExpression(expression, node), node); + } + return node; + } + ts.updateJsxExpression = updateJsxExpression; + function createHeritageClause(token, types, location) { + var node = createNode(251, location); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + if (node.types !== types) { + return updateNode(createHeritageClause(node.token, types, node), node); + } + return node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCaseClause(expression, statements, location) { + var node = createNode(249, location); + node.expression = parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + if (node.expression !== expression || node.statements !== statements) { + return updateNode(createCaseClause(expression, statements, node), node); + } + return node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements, location) { + var node = createNode(250, location); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + if (node.statements !== statements) { + return updateNode(createDefaultClause(statements, node), node); + } + return node; + } + ts.updateDefaultClause = updateDefaultClause; + function createCatchClause(variableDeclaration, block, location) { + var node = createNode(252, location); + node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + if (node.variableDeclaration !== variableDeclaration || node.block !== block) { + return updateNode(createCatchClause(variableDeclaration, block, node), node); + } + return node; + } + ts.updateCatchClause = updateCatchClause; + function createPropertyAssignment(name, initializer, location) { + var node = createNode(253, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = undefined; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createPropertyAssignment(name, initializer, node), node); + } + return node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { + var node = createNode(254, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { + return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); + } + return node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSourceFileNode(node, statements) { + if (node.statements !== statements) { + var updated = createNode(256, node, node.flags); + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.referencedFiles !== undefined) + updated.referencedFiles = node.referencedFiles; + if (node.typeReferenceDirectives !== undefined) + updated.typeReferenceDirectives = node.typeReferenceDirectives; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.isDeclarationFile !== undefined) + updated.isDeclarationFile = node.isDeclarationFile; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.hasNoDefaultLib !== undefined) + updated.hasNoDefaultLib = node.hasNoDefaultLib; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.externalHelpersModuleName !== undefined) + updated.externalHelpersModuleName = node.externalHelpersModuleName; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + function createNotEmittedStatement(original) { + var node = createNode(287, original); + node.original = original; + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + function createPartiallyEmittedExpression(expression, original, location) { + var node = createNode(288, location || original); + node.expression = expression; + node.original = original; + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original, node), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function createComma(left, right) { + return createBinary(left, 24, right); + } + ts.createComma = createComma; + function createLessThan(left, right, location) { + return createBinary(left, 25, right, location); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right, location) { + return createBinary(left, 56, right, location); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 32, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 33, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 35, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 36, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand, location) { + return createPostfix(operand, 41, location); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 51, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 52, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(49, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return createElementAccess(target, memberName.expression, location); + } + else { + var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); + expression.emitFlags |= 2048; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createRestParameter(name) { + return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + } + ts.createRestParameter = createRestParameter; + function createFunctionCall(func, thisArg, argumentsList, location) { + return createCall(createPropertyAccess(func, "call"), undefined, [ + thisArg + ].concat(argumentsList), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return createCall(createPropertyAccess(func, "apply"), undefined, [ + thisArg, + argumentsExpression + ], location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? createLiteral(start) : start); + } + return createCall(createPropertyAccess(array, "slice"), undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return createCall(createPropertyAccess(array, "concat"), undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return createCall(createPropertyAccess(createIdentifier("Math"), "pow"), undefined, [left, right], location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + var react = createIdentifier(reactNamespace || "React"); + react.flags &= ~8; + react.parent = parent; + return react; + } + function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + child.startsOnNewLine = true; + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), undefined, argumentsList, location); + } + ts.createReactCreateElement = createReactCreateElement; + function createLetDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 1); + } + ts.createLetDeclarationList = createLetDeclarationList; + function createConstDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 2); + } + ts.createConstDeclarationList = createConstDeclarationList; + function createHelperName(externalHelpersModuleName, name) { + return externalHelpersModuleName + ? createPropertyAccess(externalHelpersModuleName, name) + : createIdentifier(name); + } + ts.createHelperName = createHelperName; + function createExtendsHelper(externalHelpersModuleName, name) { + return createCall(createHelperName(externalHelpersModuleName, "__extends"), undefined, [ + name, + createIdentifier("_super") + ]); + } + ts.createExtendsHelper = createExtendsHelper; + function createAssignHelper(externalHelpersModuleName, attributesSegments) { + return createCall(createHelperName(externalHelpersModuleName, "__assign"), undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { + return createCall(createHelperName(externalHelpersModuleName, "__param"), undefined, [ + createLiteral(parameterOffset), + expression + ], location); + } + ts.createParamHelper = createParamHelper; + function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { + return createCall(createHelperName(externalHelpersModuleName, "__metadata"), undefined, [ + createLiteral(metadataKey), + metadataValue + ]); + } + ts.createMetadataHelper = createMetadataHelper; + function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(createArrayLiteral(decoratorExpressions, undefined, true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return createCall(createHelperName(externalHelpersModuleName, "__decorate"), undefined, argumentsArray, location); + } + ts.createDecorateHelper = createDecorateHelper; + function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { + var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); + generatorFunc.emitFlags |= 2097152; + return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ + createThis(), + hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), + promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), + generatorFunc + ]); + } + ts.createAwaiterHelper = createAwaiterHelper; + function createHasOwnProperty(target, propertyName) { + return createCall(createPropertyAccess(target, "hasOwnProperty"), undefined, [propertyName]); + } + ts.createHasOwnProperty = createHasOwnProperty; + function createObjectCreate(prototype) { + return createCall(createPropertyAccess(createIdentifier("Object"), "create"), undefined, [prototype]); + } + function createGeti(target) { + return createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createElementAccess(target, createIdentifier("name"))); + } + function createSeti(target) { + return createArrowFunction(undefined, undefined, [ + createParameter("name"), + createParameter("value") + ], undefined, undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); + } + function createAdvancedAsyncSuperHelper() { + var createCache = createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("cache", undefined, createObjectCreate(createNull())) + ])); + var getter = createGetAccessor(undefined, undefined, "value", [], undefined, createBlock([ + createReturn(createCall(createIdentifier("geti"), undefined, [createIdentifier("name")])) + ])); + var setter = createSetAccessor(undefined, undefined, "value", [createParameter("v")], createBlock([ + createStatement(createCall(createIdentifier("seti"), undefined, [ + createIdentifier("name"), + createIdentifier("v") + ])) + ])); + var getOrCreateAccessorsForName = createReturn(createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ + getter, + setter + ])))))); + return createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("_super", undefined, createCall(createParen(createFunctionExpression(undefined, undefined, undefined, [ + createParameter("geti"), + createParameter("seti") + ], undefined, createBlock([ + createCache, + getOrCreateAccessorsForName + ]))), undefined, [ + createGeti(createSuper()), + createSeti(createSuper()) + ])) + ])); + } + ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; + function createSimpleAsyncSuperHelper() { + return createVariableStatement(undefined, createConstDeclarationList([ + createVariableDeclaration("_super", undefined, createGeti(createSuper())) + ])); + } + ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = skipParentheses(node); + switch (target.kind) { + case 69: + return cacheIdentifiers; + case 97: + case 8: + case 9: + return false; + case 170: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 171: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + var callee = skipOuterExpressions(expression, 7); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = createThis(); + target = callee; + } + else if (callee.kind === 95) { + thisArg = createThis(); + target = languageVersion < 2 ? createIdentifier("_super", callee) : callee; + } + else { + switch (callee.kind) { + case 172: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createPropertyAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.name, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 173: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createElementAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.argumentExpression, callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + thisArg = createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + return ts.reduceLeft(expressions, createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = getMutableClone(node.right); + return createPropertyAccess(left, right, node); + } + else { + return getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return createLiteral(memberName, undefined); + } + else if (ts.isComputedPropertyName(memberName)) { + return getMutableClone(memberName.expression); + } + else { + return getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 149: + case 150: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + case 253: + return createExpressionForPropertyAssignment(property, receiver); + case 254: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 147: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_1 = []; + if (getAccessor) { + var getterFunction = createFunctionExpression(undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); + setOriginalNode(getterFunction, getAccessor); + var getter = createPropertyAssignment("get", getterFunction); + properties_1.push(getter); + } + if (setAccessor) { + var setterFunction = createFunctionExpression(undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); + setOriginalNode(setterFunction, setAccessor); + var setter = createPropertyAssignment("set", setterFunction); + properties_1.push(setter); + } + properties_1.push(createPropertyAssignment("enumerable", createLiteral(true))); + properties_1.push(createPropertyAssignment("configurable", createLiteral(true))); + var expression = createCall(createPropertyAccess(createIdentifier("Object"), "defineProperty"), undefined, [ + receiver, + createExpressionForPropertyName(property.name), + createObjectLiteral(properties_1, undefined, multiLine) + ], firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), property.initializer, property), property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), getSynthesizedClone(property.name), property), property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); + } + function isUseStrictPrologue(node) { + return node.expression.text === "use strict"; + } + function addPrologueDirectives(target, source, ensureUseStrict, visitor) { + ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + foundUseStrict = true; + } + if (statement.emitFlags & 8388608) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + } + statementOffset++; + } + return statementOffset; + } + ts.addPrologueDirectives = addPrologueDirectives; + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = skipPartiallyEmittedExpressions(operand); + if (skipped.kind === 178) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var binaryOperatorPrecedence = ts.getOperatorPrecedence(187, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(187, binaryOperator); + var emittedOperand = skipPartiallyEmittedExpressions(operand); + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1: + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 + && operand.kind === 190) { + return false; + } + return true; + case 1: + return false; + case 0: + if (isLeftSideOfBinary) { + return binaryOperatorAssociativity === 1; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + if (binaryOperator === 35) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0; + } + } + } + function operatorHasAssociativeProperty(binaryOperator) { + return binaryOperator === 37 + || binaryOperator === 47 + || binaryOperator === 46 + || binaryOperator === 48; + } + function getLiteralKindOfBinaryPlusOperand(node) { + node = skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 187 && node.operatorToken.kind === 35) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0; + } + function parenthesizeForNew(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + switch (emittedExpression.kind) { + case 174: + return createParen(expression); + case 175: + return emittedExpression.arguments + ? expression + : createParen(expression); + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + function parenthesizeForAccess(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 175 || emittedExpression.arguments) + && emittedExpression.kind !== 8) { + return expression; + } + return createParen(expression, expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : createParen(operand, operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : createParen(operand, operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return createNodeArray(result, elements, elements.hasTrailingComma); + } + return elements; + } + function parenthesizeExpressionForList(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(187, 24); + return expressionPrecedence > commaPrecedence + ? expression + : createParen(expression, expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = skipPartiallyEmittedExpressions(callee).kind; + if (kind === 179 || kind === 180) { + var mutableCall = getMutableClone(emittedExpression); + mutableCall.expression = createParen(callee, callee); + return recreatePartiallyEmittedExpressions(expression, mutableCall); + } + } + else { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 171 || leftmostExpressionKind === 179) { + return createParen(expression, expression); + } + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { + if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { + var clone_1 = getMutableClone(originalOuterExpression); + clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); + return clone_1; + } + return newInnerExpression; + } + function getLeftmostExpression(node) { + while (true) { + switch (node.kind) { + case 186: + node = node.operand; + continue; + case 187: + node = node.left; + continue; + case 188: + node = node.condition; + continue; + case 174: + case 173: + case 172: + node = node.expression; + continue; + case 288: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + var emittedBody = skipPartiallyEmittedExpressions(body); + if (emittedBody.kind === 171) { + return createParen(body, body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7; } + var previousNode; + do { + previousNode = node; + if (kinds & 1) { + node = skipParentheses(node); + } + if (kinds & 2) { + node = skipAssertions(node); + } + if (kinds & 4) { + node = skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipParentheses(node) { + while (node.kind === 178) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipAssertions(node) { + while (ts.isAssertionExpression(node)) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function startOnNewLine(node) { + node.startsOnNewLine = true; + return node; + } + ts.startOnNewLine = startOnNewLine; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; + if (emitFlags) + node.emitFlags = emitFlags; + if (commentRange) + node.commentRange = commentRange; + if (sourceMapRange) + node.sourceMapRange = sourceMapRange; + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function setTextRange(node, location) { + if (location) { + node.pos = location.pos; + node.end = location.end; + } + return node; + } + ts.setTextRange = setTextRange; + function setNodeFlags(node, flags) { + node.flags = flags; + return node; + } + ts.setNodeFlags = setNodeFlags; + function setMultiLine(node, multiLine) { + node.multiLine = multiLine; + return node; + } + ts.setMultiLine = setMultiLine; + function setHasTrailingComma(nodes, hasTrailingComma) { + nodes.hasTrailingComma = hasTrailingComma; + return nodes; + } + ts.setHasTrailingComma = setHasTrailingComma; + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name_11 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + } + if (node.kind === 230 && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 236 && node.moduleSpecifier) { + return getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); + if (moduleName.kind === 9) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + function tryRenameExternalModule(moduleName, sourceFile) { + if (sourceFile.renamedDependencies && ts.hasProperty(sourceFile.renamedDependencies, moduleName.text)) { + return createLiteral(sourceFile.renamedDependencies[moduleName.text]); + } + return undefined; + } + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return createLiteral(file.moduleName); + } + if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + return createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } + else if (kind === 69) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (kind < 139) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -7389,6 +11291,8 @@ var ts; return visitNodes(cbNodes, node.types); case 164: return visitNode(cbNode, node.type); + case 166: + return visitNode(cbNode, node.literal); case 167: case 168: return visitNodes(cbNodes, node.elements); @@ -7628,7 +11532,7 @@ var ts; case 263: return visitNode(cbNode, node.type); case 265: - return visitNodes(cbNodes, node.members); + return visitNode(cbNode, node.literal); case 267: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); @@ -7667,14 +11571,19 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + case 288: + return visitNode(cbNode, node.expression); + case 282: + return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - var start = new Date().getTime(); + ts.performance.mark("beforeParse"); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.parseTime += new Date().getTime() - start; + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; } ts.createSourceFile = createSourceFile; @@ -7688,8 +11597,8 @@ var ts; ts.updateSourceFile = updateSourceFile; function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDocComment) { - Parser.fixupParentReferences(result.jsDocComment); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); } return result; } @@ -7701,13 +11610,15 @@ var ts; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 4194304 | 16777216; + var disallowInAndDecoratorContext = 32768 | 131072; var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -7728,15 +11639,17 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 1048576 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -7755,10 +11668,10 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; - token = nextToken(); + nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token === 1); + ts.Debug.assert(token() === 1); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -7771,20 +11684,18 @@ var ts; return sourceFile; } function addJSDocComment(node) { - if (contextFlags & 134217728) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDocComment) { - continue; - } - if (!node.jsDocComments) { - node.jsDocComments = []; - } - node.jsDocComments.push(jsDocComment); + var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; } + if (!node.jsDocComments) { + node.jsDocComments = []; + } + node.jsDocComments.push(jsDoc); } } return node; @@ -7833,16 +11744,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 4194304); + setContextFlag(val, 32768); } function setYieldContext(val) { - setContextFlag(val, 8388608); + setContextFlag(val, 65536); } function setDecoratorContext(val) { - setContextFlag(val, 16777216); + setContextFlag(val, 131072); } function setAwaitContext(val) { - setContextFlag(val, 33554432); + setContextFlag(val, 262144); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -7865,40 +11776,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(4194304, func); + return doOutsideOfContext(32768, func); } function disallowInAnd(func) { - return doInsideOfContext(4194304, func); + return doInsideOfContext(32768, func); } function doInYieldContext(func) { - return doInsideOfContext(8388608, func); + return doInsideOfContext(65536, func); } function doInDecoratorContext(func) { - return doInsideOfContext(16777216, func); + return doInsideOfContext(131072, func); } function doInAwaitContext(func) { - return doInsideOfContext(33554432, func); + return doInsideOfContext(262144, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(33554432, func); + return doOutsideOfContext(262144, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(8388608 | 33554432, func); + return doInsideOfContext(65536 | 262144, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(8388608); + return inContext(65536); } function inDisallowInContext() { - return inContext(4194304); + return inContext(32768); } function inDecoratorContext() { - return inContext(16777216); + return inContext(131072); } function inAwaitContext() { - return inContext(33554432); + return inContext(262144); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -7922,26 +11833,32 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } + function token() { + return currentToken; + } function nextToken() { - return token = scanner.scan(); + return currentToken = scanner.scan(); } function reScanGreaterToken() { - return token = scanner.reScanGreaterToken(); + return currentToken = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return token = scanner.reScanSlashToken(); + return currentToken = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return token = scanner.reScanTemplateToken(); + return currentToken = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return token = scanner.scanJsxIdentifier(); + return currentToken = scanner.scanJsxIdentifier(); } function scanJsxText() { - return token = scanner.scanJsxToken(); + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); } function speculationHelper(callback, isLookAhead) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -7950,7 +11867,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -7963,20 +11880,20 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token === 69) { + if (token() === 69) { return true; } - if (token === 114 && inYieldContext()) { + if (token() === 114 && inYieldContext()) { return false; } - if (token === 119 && inAwaitContext()) { + if (token() === 119 && inAwaitContext()) { return false; } - return token > 105; + return token() > 105; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token === kind) { + if (token() === kind) { if (shouldAdvance) { nextToken(); } @@ -7991,14 +11908,14 @@ var ts; return false; } function parseOptional(t) { - if (token === t) { + if (token() === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token === t) { + if (token() === t) { return parseTokenNode(); } return undefined; @@ -8008,19 +11925,19 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token); + var node = createNode(token()); nextToken(); return finishNode(node); } function canParseSemicolon() { - if (token === 23) { + if (token() === 23) { return true; } - return token === 16 || token === 1 || scanner.hasPrecedingLineBreak(); + return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token === 23) { + if (token() === 23) { nextToken(); } return true; @@ -8034,7 +11951,18 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new NodeConstructor(kind, pos, pos); + return kind >= 139 ? new NodeConstructor(kind, pos, pos) : + kind === 69 ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -8043,7 +11971,7 @@ var ts; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 67108864; + node.flags |= 524288; } return node; } @@ -8060,14 +11988,14 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); + return identifiers[text] || (identifiers[text] = text); } function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { var node = createNode(69); - if (token !== 69) { - node.originalKeywordKind = token; + if (token() !== 69) { + node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -8079,18 +12007,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token) || - token === 9 || - token === 8; + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token === 9 || token === 8) { + if (token() === 9 || token() === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token === 19) { + if (allowComputedPropertyNames && token() === 19) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -8102,7 +12030,7 @@ var ts; return parsePropertyNameWorker(false); } function isSimplePropertyName() { - return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { var node = createNode(140); @@ -8112,7 +12040,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8122,39 +12050,39 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token === 74) { + if (token() === 74) { return nextToken() === 81; } - if (token === 82) { + if (token() === 82) { nextToken(); - if (token === 77) { + if (token() === 77) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token !== 37 && token !== 116 && token !== 15 && canFollowModifier(); + return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); } - if (token === 77) { + if (token() === 77) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token === 113) { + if (token() === 113) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token === 19 - || token === 15 - || token === 37 - || token === 22 + return token() === 19 + || token() === 15 + || token() === 37 + || token() === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token === 73 || token === 87 || - (token === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 73 || token() === 87 || + (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -8165,21 +12093,21 @@ var ts; case 0: case 1: case 3: - return !(token === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); case 2: - return token === 71 || token === 77; + return token() === 71 || token() === 77; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); case 6: - return token === 19 || isLiteralPropertyName(); + return token() === 19 || isLiteralPropertyName(); case 12: - return token === 19 || token === 37 || isLiteralPropertyName(); + return token() === 19 || token() === 37 || isLiteralPropertyName(); case 9: - return token === 19 || isLiteralPropertyName(); + return token() === 19 || isLiteralPropertyName(); case 7: - if (token === 15) { + if (token() === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -8191,23 +12119,23 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token === 24 || token === 22 || isIdentifierOrPattern(); + return token() === 24 || token() === 22 || isIdentifierOrPattern(); case 17: return isIdentifier(); case 11: case 15: - return token === 24 || token === 22 || isStartOfExpression(); + return token() === 24 || token() === 22 || isStartOfExpression(); case 16: return isStartOfParameter(); case 18: case 19: - return token === 24 || isStartOfType(); + return token() === 24 || isStartOfType(); case 20: return isHeritageClause(); case 21: - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); case 13: - return ts.tokenIsIdentifierOrKeyword(token) || token === 15; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; case 14: return true; case 22: @@ -8220,7 +12148,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token === 15); + ts.Debug.assert(token() === 15); if (nextToken() === 16) { var next = nextToken(); return next === 24 || next === 15 || next === 83 || next === 106; @@ -8233,11 +12161,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token === 106 || - token === 83) { + if (token() === 106 || + token() === 83) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -8247,7 +12175,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token === 1) { + if (token() === 1) { return true; } switch (kind) { @@ -8259,49 +12187,49 @@ var ts; case 12: case 9: case 21: - return token === 16; + return token() === 16; case 3: - return token === 16 || token === 71 || token === 77; + return token() === 16 || token() === 71 || token() === 77; case 7: - return token === 15 || token === 83 || token === 106; + return token() === 15 || token() === 83 || token() === 106; case 8: return isVariableDeclaratorListTerminator(); case 17: - return token === 27 || token === 17 || token === 15 || token === 83 || token === 106; + return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; case 11: - return token === 18 || token === 23; + return token() === 18 || token() === 23; case 15: case 19: case 10: - return token === 20; + return token() === 20; case 16: - return token === 18 || token === 20; + return token() === 18 || token() === 20; case 18: - return token === 27 || token === 17; + return token() === 27 || token() === 17; case 20: - return token === 15 || token === 16; + return token() === 15 || token() === 16; case 13: - return token === 27 || token === 39; + return token() === 27 || token() === 39; case 14: - return token === 25 && lookAhead(nextTokenIsSlash); + return token() === 25 && lookAhead(nextTokenIsSlash); case 22: - return token === 18 || token === 54 || token === 16; + return token() === 18 || token() === 54 || token() === 16; case 23: - return token === 27 || token === 16; + return token() === 27 || token() === 16; case 25: - return token === 20 || token === 16; + return token() === 20 || token() === 16; case 24: - return token === 16; + return token() === 16; } } function isVariableDeclaratorListTerminator() { if (canParseSemicolon()) { return true; } - if (isInOrOfKeyword(token)) { + if (isInOrOfKeyword(token())) { return true; } - if (token === 34) { + if (token() === 34) { return true; } return false; @@ -8319,8 +12247,7 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); @@ -8359,7 +12286,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 197132288; + var nodeContextFlags = node.flags & 1540096; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -8541,8 +12468,7 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); var commaStart = -1; while (true) { if (isListElement(kind, false)) { @@ -8556,7 +12482,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -8576,11 +12502,7 @@ var ts; return result; } function createMissingList() { - var pos = getNodePos(); - var result = []; - result.pos = pos; - result.end = pos; - return result; + return createNodeArray(); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -8601,7 +12523,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); @@ -8613,8 +12535,7 @@ var ts; var template = createNode(189); template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); - var templateSpans = []; - templateSpans.pos = getNodePos(); + var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); } while (ts.lastOrUndefined(templateSpans).literal.kind === 13); @@ -8626,7 +12547,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16) { + if (token() === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -8636,14 +12557,11 @@ var ts; span.literal = literal; return finishNode(span); } - function parseStringLiteralTypeNode() { - return parseLiteralLikeNode(166, true); - } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token, internName); + return parseLiteralLikeNode(token(), internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token, false); + return parseLiteralLikeNode(token(), false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -8669,7 +12587,7 @@ var ts; var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); var node = createNode(155, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token === 25) { + if (!scanner.hasPrecedingLineBreak() && token() === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); @@ -8706,7 +12624,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25) { + if (token() === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -8717,26 +12635,20 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; - } - function setModifiers(node, modifiers) { - if (modifiers) { - node.flags |= modifiers.flags; - node.modifiers = modifiers; - } + return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; } function parseParameter() { var node = createNode(142); - if (token === 97) { + if (token() === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -8791,20 +12703,20 @@ var ts; } fillSignature(54, false, false, false, node); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token !== 19) { + if (token() !== 19) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token === 22 || token === 20) { + if (token() === 22 || token() === 20) { return true; } - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { nextToken(); if (isIdentifier()) { return true; @@ -8816,19 +12728,19 @@ var ts; else { nextToken(); } - if (token === 54 || token === 24) { + if (token() === 54 || token() === 24) { return true; } - if (token !== 53) { + if (token() !== 53) { return false; } nextToken(); - return token === 54 || token === 24 || token === 20; + return token() === 54 || token() === 24 || token() === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.parameters = parseBracketedList(16, parseParameter, 19, 20); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); @@ -8837,58 +12749,59 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { var method = createNode(146, fullStart); - setModifiers(method, modifiers); + method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; fillSignature(54, false, false, false, method); parseTypeMemberSemicolon(); - return finishNode(method); + return addJSDocComment(finishNode(method)); } else { var property = createNode(144, fullStart); - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56) { + if (token() === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } } function isTypeMemberStart() { var idToken; - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { return true; } - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); nextToken(); } - if (token === 19) { + if (token() === 19) { return true; } if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } if (idToken) { - return token === 17 || - token === 25 || - token === 53 || - token === 54 || + return token() === 17 || + token() === 25 || + token() === 53 || + token() === 54 || + token() === 24 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token === 17 || token === 25) { + if (token() === 17 || token() === 25) { return parseSignatureMember(151); } - if (token === 92 && lookAhead(isStartOfConstructSignature)) { + if (token() === 92 && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152); } var fullStart = getNodePos(); @@ -8900,7 +12813,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 || token === 25; + return token() === 17 || token() === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -8940,10 +12853,19 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token === 21 ? undefined : node; + return token() === 21 ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(166); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8; } function parseNonArrayType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -8954,13 +12876,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: - return parseStringLiteralTypeNode(); + case 8: + case 99: + case 84: + return parseLiteralTypeNode(); + case 36: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); case 103: case 93: return parseTokenNode(); case 97: { var thisKeyword = parseThisTypeNode(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -8980,7 +12907,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -8997,7 +12924,12 @@ var ts; case 25: case 92: case 9: + case 8: + case 99: + case 84: return true; + case 36: + return lookAhead(nextTokenIsNumericLiteral); case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); default: @@ -9006,7 +12938,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 || isStartOfParameter() || isStartOfType(); + return token() === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -9020,9 +12952,8 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { - var types = [type]; - types.pos = type.pos; + if (token() === operator) { + var types = createNodeArray([type], type.pos); while (parseOptional(operator)) { types.push(parseConstituentType()); } @@ -9040,20 +12971,20 @@ var ts; return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { - if (token === 25) { + if (token() === 25) { return true; } - return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { parseModifiers(); } - if (isIdentifier() || token === 97) { + if (isIdentifier() || token() === 97) { nextToken(); return true; } - if (token === 19 || token === 15) { + if (token() === 19 || token() === 15) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -9062,17 +12993,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token === 18 || token === 22) { + if (token() === 18 || token() === 22) { return true; } if (skipParameterStart()) { - if (token === 54 || token === 24 || - token === 53 || token === 56) { + if (token() === 54 || token() === 24 || + token() === 53 || token() === 56) { return true; } - if (token === 18) { + if (token() === 18) { nextToken(); - if (token === 34) { + if (token() === 34) { return true; } } @@ -9094,19 +13025,19 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseType() { - return doOutsideOfContext(41943040, parseTypeWorker); + return doOutsideOfContext(327680, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token === 92) { + if (token() === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -9115,7 +13046,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97: case 95: case 93: @@ -9143,7 +13074,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9165,10 +13096,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token !== 15 && - token !== 87 && - token !== 73 && - token !== 55 && + return token() !== 15 && + token() !== 87 && + token() !== 73 && + token() !== 55 && isStartOfExpression(); } function parseExpression() { @@ -9187,8 +13118,8 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15) || !isStartOfExpression()) { + if (token() !== 56) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { return undefined; } } @@ -9204,7 +13135,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token === 34) { + if (expr.kind === 69 && token() === 34) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -9213,7 +13144,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114) { + if (token() === 114) { if (inYieldContext()) { return true; } @@ -9229,7 +13160,7 @@ var ts; var node = createNode(190); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token === 37 || isStartOfExpression())) { + (token() === 37 || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -9239,11 +13170,11 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180, asyncModifier.pos); - setModifiers(node, asyncModifier); + node.modifiers = asyncModifier; } else { node = createNode(180, identifier.pos); @@ -9251,12 +13182,11 @@ var ts; var parameter = createNode(142, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = [parameter]; - node.parameters.pos = parameter.pos; + node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; node.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function tryParseParenthesizedArrowFunctionExpression() { var triState = isParenthesizedArrowFunctionExpression(); @@ -9269,34 +13199,34 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token; + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return finishNode(arrowFunction); + return addJSDocComment(finishNode(arrowFunction)); } function isParenthesizedArrowFunctionExpression() { - if (token === 17 || token === 25 || token === 118) { + if (token() === 17 || token() === 25 || token() === 118) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token === 34) { + if (token() === 34) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token === 118) { + if (token() === 118) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token !== 17 && token !== 25) { + if (token() !== 17 && token() !== 25) { return 0; } } - var first = token; + var first = token(); var second = nextToken(); if (first === 17) { if (second === 18) { @@ -9359,7 +13289,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token === 118) { + if (token() === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -9370,13 +13300,13 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token === 118) { + if (token() === 118) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token === 34) { + if (scanner.hasPrecedingLineBreak() || token() === 34) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { return 1; } } @@ -9384,24 +13314,24 @@ var ts; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(180); - setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 256); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = !!(ts.getModifierFlags(node) & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token !== 34 && token !== 15) { + if (!allowAmbiguity && token() !== 34 && token() !== 15) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token === 15) { + if (token() === 15) { return parseFunctionBlock(false, isAsync, false); } - if (token !== 23 && - token !== 87 && - token !== 73 && + if (token() !== 23 && + token() !== 87 && + token() !== 73 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -9434,16 +13364,16 @@ var ts; while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token === 38 ? + var consumeCurrentOperator = token() === 38 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token === 90 && inDisallowInContext()) { + if (token() === 90 && inDisallowInContext()) { break; } - if (token === 116) { + if (token() === 116) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -9459,13 +13389,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token === 90) { + if (inDisallowInContext() && token() === 90) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token) { + switch (token()) { case 52: return 1; case 51: @@ -9520,7 +13450,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -9544,7 +13474,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119) { + if (token() === 119) { if (inAwaitContext()) { return true; } @@ -9559,18 +13489,15 @@ var ts; return finishNode(node); } function parseUnaryExpressionOrHigher() { - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - if (isIncrementExpression()) { + if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token === 38 ? + return token() === 38 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token; + var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token === 38) { + if (token() === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -9582,7 +13509,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9596,12 +13523,16 @@ var ts; return parseVoidExpression(); case 25: return parseTypeAssertion(); + case 119: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } } - function isIncrementExpression() { - switch (token) { + function isUpdateExpression() { + switch (token()) { case 35: case 36: case 50: @@ -9609,6 +13540,7 @@ var ts; case 78: case 101: case 103: + case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -9619,29 +13551,29 @@ var ts; } } function parseIncrementExpression() { - if (token === 41 || token === 42) { + if (token() === 41 || token() === 42) { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { + if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186, expression.pos); node.operand = expression; - node.operator = token; + node.operator = token(); nextToken(); return finishNode(node); } return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token === 95 + var expression = token() === 95 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -9652,7 +13584,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token === 17 || token === 21 || token === 19) { + if (token() === 17 || token() === 21 || token() === 19) { return expression; } var node = createNode(172, expression.pos); @@ -9691,7 +13623,7 @@ var ts; ts.Debug.assert(opening.kind === 242); result = opening; } - if (inExpressionContext && token === 25) { + if (inExpressionContext && token() === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -9708,11 +13640,11 @@ var ts; } function parseJsxText() { var node = createNode(244, scanner.getStartPos()); - token = scanner.scanJsxToken(); + currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token) { + switch (token()) { case 244: return parseJsxText(); case 15: @@ -9720,19 +13652,18 @@ var ts; case 25: return parseJsxElementOrSelfClosingElement(false); } - ts.Debug.fail("Unknown JSX child kind " + token); + ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = []; - result.pos = scanner.getStartPos(); + var result = createNodeArray(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - token = scanner.reScanJsxToken(); - if (token === 26) { + currentToken = scanner.reScanJsxToken(); + if (token() === 26) { break; } - else if (token === 1) { + else if (token() === 1) { parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } @@ -9748,7 +13679,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token === 27) { + if (token() === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -9769,7 +13700,7 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token === 97 ? + var expression = token() === 97 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21)) { var propertyAccess = createNode(172, expression.pos); @@ -9782,7 +13713,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token !== 16) { + if (token() !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -9795,14 +13726,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token === 15) { + if (token() === 15) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246); node.name = parseIdentifierName(); - if (parseOptional(56)) { - switch (token) { + if (token() === 56) { + switch (scanJsxAttributeValue()) { case 9: node.initializer = parseLiteralNode(); break; @@ -9852,7 +13783,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token === 49 && !scanner.hasPrecedingLineBreak()) { + if (token() === 49 && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196, expression.pos); nonNullExpression.expression = expression; @@ -9862,7 +13793,7 @@ var ts; if (!inDecoratorContext() && parseOptional(19)) { var indexedAccess = createNode(173, expression.pos); indexedAccess.expression = expression; - if (token !== 20) { + if (token() !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; @@ -9873,10 +13804,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token === 11 || token === 12) { + if (token() === 11 || token() === 12) { var tagExpression = createNode(176, expression.pos); tagExpression.tag = expression; - tagExpression.template = token === 11 + tagExpression.template = token() === 11 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -9888,7 +13819,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token === 25) { + if (token() === 25) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; @@ -9900,7 +13831,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token === 17) { + else if (token() === 17) { var callExpr = createNode(174, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -9929,7 +13860,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17: case 21: case 18: @@ -9956,7 +13887,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8: case 9: case 11: @@ -10009,8 +13940,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token === 22 ? parseSpreadElement() : - token === 24 ? createNode(193) : + return token() === 22 ? parseSpreadElement() : + token() === 24 ? createNode(193) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -10028,7 +13959,7 @@ var ts; } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123)) { - return addJSDocComment(parseAccessorDeclaration(149, fullStart, decorators, modifiers)); + return parseAccessorDeclaration(149, fullStart, decorators, modifiers); } else if (parseContextualModifier(131)) { return parseAccessorDeclaration(150, fullStart, decorators, modifiers); @@ -10047,10 +13978,10 @@ var ts; var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token === 17 || token === 25) { + if (asteriskToken || token() === 17 || token() === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254, fullStart); shorthandDeclaration.name = propertyName; @@ -10088,11 +14019,11 @@ var ts; setDecoratorContext(false); } var node = createNode(179); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); parseExpected(87); node.asteriskToken = parseOptionalToken(37); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256); + var isAsync = !!(ts.getModifierFlags(node) & 256); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -10113,7 +14044,7 @@ var ts; parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token === 17) { + if (node.typeArguments || token() === 17) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -10121,6 +14052,9 @@ var ts; function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var node = createNode(199); if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.statements = parseList(1, parseStatement); parseExpected(16); } @@ -10186,8 +14120,8 @@ var ts; parseExpected(86); parseExpected(17); var initializer = undefined; - if (token !== 23) { - if (token === 102 || token === 108 || token === 74) { + if (token() !== 23) { + if (token() === 102 || token() === 108 || token() === 74) { initializer = parseVariableDeclarationList(true); } else { @@ -10213,11 +14147,11 @@ var ts; var forStatement = createNode(206, pos); forStatement.initializer = initializer; parseExpected(23); - if (token !== 23 && token !== 18) { + if (token() !== 23 && token() !== 18) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23); - if (token !== 18) { + if (token() !== 18) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18); @@ -10269,7 +14203,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -10295,8 +14229,8 @@ var ts; var node = createNode(216); parseExpected(100); node.tryBlock = parseBlock(false); - node.catchClause = token === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token === 85) { + node.catchClause = token() === 72 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 85) { parseExpected(85); node.finallyBlock = parseBlock(false); } @@ -10336,19 +14270,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token === 87 && !scanner.hasPrecedingLineBreak(); + return token() === 87 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token) || token === 8) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -10376,16 +14310,16 @@ var ts; continue; case 137: nextToken(); - return token === 15 || token === 69 || token === 82; + return token() === 15 || token() === 69 || token() === 82; case 89: nextToken(); - return token === 9 || token === 37 || - token === 15 || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 || token() === 37 || + token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); case 82: nextToken(); - if (token === 56 || token === 37 || - token === 15 || token === 77 || - token === 116) { + if (token() === 56 || token() === 37 || + token() === 15 || token() === 77 || + token() === 116) { return true; } continue; @@ -10401,7 +14335,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55: case 23: case 15: @@ -10449,13 +14383,13 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token === 15 || token === 19; + return isIdentifier() || token() === 15 || token() === 19; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token) { + switch (token()) { case 23: return parseEmptyStatement(); case 15: @@ -10527,7 +14461,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -10550,7 +14484,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token) { + switch (token()) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -10564,24 +14498,24 @@ var ts; var node = createMissingNode(239, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; return finishNode(node); } } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token !== 15 && canParseSemicolon()) { + if (token() !== 15 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token === 24) { + if (token() === 24) { return createNode(193); } var node = createNode(169); @@ -10594,7 +14528,7 @@ var ts; var node = createNode(169); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token !== 54) { + if (tokenIsIdentifier && token() !== 54) { node.name = propertyName; } else { @@ -10620,13 +14554,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token === 15 || token === 19 || isIdentifier(); + return token() === 15 || token() === 19 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token === 19) { + if (token() === 19) { return parseArrayBindingPattern(); } - if (token === 15) { + if (token() === 15) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -10635,27 +14569,27 @@ var ts; var node = createNode(218); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token)) { + if (!isInOrOfKeyword(token())) { node.initializer = parseInitializer(false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219); - switch (token) { + switch (token()) { case 102: break; case 108: - node.flags |= 1024; + node.flags |= 1; break; case 74: - node.flags |= 2048; + node.flags |= 2; break; default: ts.Debug.fail(); } nextToken(); - if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -10672,7 +14606,7 @@ var ts; function parseVariableStatement(fullStart, decorators, modifiers) { var node = createNode(200, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); return addJSDocComment(finishNode(node)); @@ -10680,12 +14614,12 @@ var ts; function parseFunctionDeclaration(fullStart, decorators, modifiers) { var node = createNode(220, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(87); node.asteriskToken = parseOptionalToken(37); - node.name = node.flags & 512 ? parseOptionalIdentifier() : parseIdentifier(); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256); + var isAsync = ts.hasModifier(node, 256); fillSignature(54, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); @@ -10693,7 +14627,7 @@ var ts; function parseConstructorDeclaration(pos, decorators, modifiers) { var node = createNode(148, pos); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(121); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); @@ -10702,12 +14636,12 @@ var ts; function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { var method = createNode(147, fullStart); method.decorators = decorators; - setModifiers(method, modifiers); + method.modifiers = modifiers; method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 256); + var isAsync = ts.hasModifier(method, 256); fillSignature(54, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); @@ -10715,21 +14649,21 @@ var ts; function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { var property = createNode(145, fullStart); property.decorators = decorators; - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = modifiers && modifiers.flags & 32 + property.initializer = ts.hasModifier(property, 32) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(8388608 | 4194304, parseNonParameterInitializer); + : doOutsideOfContext(65536 | 32768, parseNonParameterInitializer); parseSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { var asteriskToken = parseOptionalToken(37); var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token === 17 || token === 25) { + if (asteriskToken || token() === 17 || token() === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -10742,11 +14676,11 @@ var ts; function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.name = parsePropertyName(); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -10762,31 +14696,31 @@ var ts; } function isClassMemberStart() { var idToken; - if (token === 55) { + if (token() === 55) { return true; } - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); if (isClassMemberModifier(idToken)) { return true; } nextToken(); } - if (token === 37) { + if (token() === 37) { return true; } if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } - if (token === 19) { + if (token() === 19) { return true; } if (idToken !== undefined) { if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { return true; } - switch (token) { + switch (token()) { case 17: case 25: case 54: @@ -10806,13 +14740,15 @@ var ts; if (!parseOptional(55)) { break; } - if (!decorators) { - decorators = []; - decorators.pos = decoratorStart; - } var decorator = createNode(143, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - decorators.push(finishNode(decorator)); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } } if (decorators) { decorators.end = getNodeEnd(); @@ -10820,12 +14756,11 @@ var ts; return decorators; } function parseModifiers(permitInvalidConstAsModifier) { - var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; - if (token === 74 && permitInvalidConstAsModifier) { + var modifierKind = token(); + if (token() === 74 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -10835,37 +14770,33 @@ var ts; break; } } + var modifier = finishNode(createNode(modifierKind, modifierStart)); if (!modifiers) { - modifiers = []; - modifiers.pos = modifierStart; + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); } - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); } if (modifiers) { - modifiers.flags = flags; modifiers.end = scanner.getStartPos(); } return modifiers; } function parseModifiersForArrowFunction() { - var flags = 0; var modifiers; - if (token === 118) { + if (token() === 118) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; + var modifierKind = token(); nextToken(); - modifiers = []; - modifiers.pos = modifierStart; - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); - modifiers.flags = flags; + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); modifiers.end = scanner.getStartPos(); } return modifiers; } function parseClassElement() { - if (token === 23) { + if (token() === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -10877,22 +14808,22 @@ var ts; if (accessor) { return accessor; } - if (token === 121) { + if (token() === 121) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); } - if (ts.tokenIsIdentifierOrKeyword(token) || - token === 9 || - token === 8 || - token === 37 || - token === 19) { + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8 || + token() === 37 || + token() === 19) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); + var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10905,7 +14836,7 @@ var ts; function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(73); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -10917,7 +14848,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseNameOfClassDeclarationOrExpression() { return isIdentifier() && !isImplementsClause() @@ -10925,7 +14856,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -10934,9 +14865,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token === 83 || token === 106) { + if (token() === 83 || token() === 106) { var node = createNode(251); - node.token = token; + node.token = token(); nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); @@ -10946,13 +14877,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token === 25) { + if (token() === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } function isHeritageClause() { - return token === 83 || token === 106; + return token() === 83 || token() === 106; } function parseClassMembers() { return parseList(5, parseClassElement); @@ -10960,18 +14891,18 @@ var ts; function parseInterfaceDeclaration(fullStart, decorators, modifiers) { var node = createNode(222, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(107); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(false); node.members = parseObjectTypeMembers(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { var node = createNode(223, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(134); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -10984,12 +14915,12 @@ var ts; var node = createNode(255, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { var node = createNode(224, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(81); node.name = parseIdentifier(); if (parseExpected(15)) { @@ -10999,7 +14930,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseModuleBlock() { var node = createNode(226, scanner.getStartPos()); @@ -11014,28 +14945,28 @@ var ts; } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { var node = createNode(225, fullStart); - var namespaceFlag = flags & 4096; + var namespaceFlag = flags & 16; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 1 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) : parseModuleBlock(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { var node = createNode(225, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); - if (token === 137) { + node.modifiers = modifiers; + if (token() === 137) { node.name = parseIdentifier(); - node.flags |= 131072; + node.flags |= 512; } else { node.name = parseLiteralNode(true); } - if (token === 15) { + if (token() === 15) { node.body = parseModuleBlock(); } else { @@ -11044,23 +14975,23 @@ var ts; return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = modifiers ? modifiers.flags : 0; - if (token === 137) { + var flags = 0; + if (token() === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { - flags |= 4096; + flags |= 16; } else { parseExpected(125); - if (token === 9) { + if (token() === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 129 && + return token() === 129 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -11085,23 +15016,23 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 && token !== 136) { + if (token() !== 24 && token() !== 136) { var importEqualsDeclaration = createNode(229, fullStart); importEqualsDeclaration.decorators = decorators; - setModifiers(importEqualsDeclaration, modifiers); + importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; parseExpected(56); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); - return finishNode(importEqualsDeclaration); + return addJSDocComment(finishNode(importEqualsDeclaration)); } } var importDeclaration = createNode(230, fullStart); importDeclaration.decorators = decorators; - setModifiers(importDeclaration, modifiers); + importDeclaration.modifiers = modifiers; if (identifier || - token === 37 || - token === 15) { + token() === 37 || + token() === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -11116,7 +15047,7 @@ var ts; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); } return finishNode(importClause); } @@ -11134,7 +15065,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9) { + if (token() === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -11163,14 +15094,14 @@ var ts; } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token === 116) { + if (token() === 116) { node.propertyName = identifierName; parseExpected(116); - checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -11186,14 +15117,14 @@ var ts; function parseExportDeclaration(fullStart, decorators, modifiers) { var node = createNode(236, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(37)) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } else { node.exportClause = parseNamedImportsOrExports(237); - if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -11204,7 +15135,7 @@ var ts; function parseExportAssignment(fullStart, decorators, modifiers) { var node = createNode(235, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(56)) { node.isExportEquals = true; } @@ -11280,7 +15211,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 + return ts.hasModifier(node, 1) || node.kind === 229 && node.moduleReference.kind === 240 || node.kind === 230 || node.kind === 235 @@ -11292,7 +15223,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37: case 53: case 17: @@ -11305,13 +15236,14 @@ var ts; case 97: return true; } - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2, undefined, 1); + sourceFile = createSourceFile("file.js", 2, 1); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -11329,12 +15261,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token === 47) { + if (token() === 47) { var unionType = createNode(261, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token === 56) { + if (token() === 56) { var optionalType = createNode(268, type.pos); nextToken(); optionalType.type = type; @@ -11345,20 +15277,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token === 19) { + if (token() === 19) { var arrayType = createNode(260, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } - else if (token === 53) { + else if (token() === 53) { var nullableType = createNode(263, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token === 49) { + else if (token() === 49) { var nonNullableType = createNode(264, type.pos); nonNullableType.type = type; nextToken(); @@ -11371,7 +15303,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37: return parseJSDocAllType(); case 53: @@ -11398,7 +15330,15 @@ var ts; case 120: case 133: case 103: + case 93: + case 135: + case 127: return parseTokenNode(); + case 9: + case 8: + case 99: + case 84: + return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } @@ -11429,7 +15369,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -11446,12 +15386,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267); result.name = parseSimplePropertyName(); - if (token === 25) { + if (token() === 25) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21)) { - if (token === 25) { + if (token() === 25) { result.typeArguments = parseTypeArguments(); break; } @@ -11485,19 +15425,7 @@ var ts; } function parseJSDocRecordType() { var result = createNode(265); - nextToken(); - result.members = parseDelimitedList(24, parseJSDocRecordMember); - checkForTrailingComma(result.members); - parseExpected(16); - return finishNode(result); - } - function parseJSDocRecordMember() { - var result = createNode(266); - result.name = parseSimplePropertyName(); - if (token === 54) { - nextToken(); - result.type = parseJSDocType(); - } + result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { @@ -11529,9 +15457,7 @@ var ts; } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); - var types = []; - types.pos = firstType.pos; - types.push(firstType); + var types = createNodeArray([firstType], firstType.pos); while (parseOptional(47)) { types.push(parseJSDocType()); } @@ -11543,15 +15469,20 @@ var ts; nextToken(); return finishNode(result); } + function parseJSDocLiteralType() { + var result = createNode(282); + result.literal = parseLiteralTypeNode(); + return finishNode(result); + } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token === 24 || - token === 16 || - token === 18 || - token === 27 || - token === 56 || - token === 47) { + if (token() === 24 || + token() === 16 || + token() === 18 || + token() === 27 || + token() === 56 || + token() === 47) { var result = createNode(259, pos); return finishNode(result); } @@ -11564,21 +15495,21 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { initializeState("file.js", content, 2, undefined, 1); sourceFile = { languageVariant: 0, text: content }; - var jsDocComment = parseJSDocCommentWorker(start, length); + var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); - return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -11593,125 +15524,254 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var comments = []; var result; - if (content.charCodeAt(start) === 47 && - content.charCodeAt(start + 1) === 42 && - content.charCodeAt(start + 2) === 42 && - content.charCodeAt(start + 3) !== 42) { - scanner.scanRange(start + 3, length - 5, function () { - var canParseTag = true; - var seenAsterisk = true; + if (!isJsDocStart(content, start)) { + return result; + } + scanner.scanRange(start + 3, length - 5, function () { + var advanceToken = true; + var state = 1; + var margin = undefined; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5) { nextJSDocToken(); - while (token !== 1) { - switch (token) { - case 55: - if (canParseTag) { - parseTag(); - } - seenAsterisk = false; - break; - case 4: - canParseTag = true; - seenAsterisk = false; - break; - case 37: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 69: - canParseTag = false; - break; - case 1: - break; - } + } + if (token() === 4) { + state = 0; + nextJSDocToken(); + } + while (token() !== 1) { + switch (token()) { + case 55: + if (state === 0 || state === 1) { + removeTrailingNewlines(comments); + parseTag(indent); + state = 0; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 37: + var asterisk = scanner.getTokenText(); + if (state === 1) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 69: + pushComment(scanner.getTokenText()); + state = 2; + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break; + default: + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { nextJSDocToken(); } - result = createJSDocComment(); - }); - } - return result; - function createJSDocComment() { - if (!tags) { - return undefined; + else { + advanceToken = true; + } } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42; + } + function createJSDocComment() { var result = createNode(273, start); result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 || token === 4) { + while (token() === 5 || token() === 4) { nextJSDocToken(); } } - function parseTag() { - ts.Debug.assert(token === 55); + function parseTag(indent) { + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return; } - var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); - addTag(tag); - } - function handleTag(atToken, tagName) { + var tag; if (tagName) { switch (tagName.text) { case "param": - return handleParamTag(atToken, tagName); + tag = parseParamTag(atToken, tagName); + break; case "return": case "returns": - return handleReturnTag(atToken, tagName); + tag = parseReturnTag(atToken, tagName); + break; case "template": - return handleTemplateTag(atToken, tagName); + tag = parseTemplateTag(atToken, tagName); + break; case "type": - return handleTypeTag(atToken, tagName); + tag = parseTypeTag(atToken, tagName); + break; case "typedef": - return handleTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; } } - return undefined; + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); } - function handleUnknownTag(atToken, tagName) { + function parseTagComments(indent) { + var comments = []; + var state = 1; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 55 && token() !== 1) { + switch (token()) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 55: + break; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 37: + if (state === 0) { + state = 1; + indent += scanner.getTokenText().length; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (token() === 55) { + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { var result = createNode(274, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } - function addTag(tag) { - if (tag) { - if (!tags) { - tags = []; - tags.pos = tag.pos; - } - tags.push(tag); - tags.end = tag.end; + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); } + else { + tags.push(tag); + } + tags.end = tag.end; } function tryParseTypeExpression() { - if (token !== 15) { - return undefined; - } - var typeExpression = parseJSDocTypeExpression(); - return typeExpression; + return tryParse(function () { + skipWhitespace(); + if (token() !== 15) { + return undefined; + } + return parseJSDocTypeExpression(); + }); } - function handleParamTag(atToken, tagName) { + function parseParamTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name; var isBracketed; if (parseOptionalToken(19)) { name = parseJSDocIdentifierName(); + skipWhitespace(); isBracketed = true; if (parseOptionalToken(56)) { parseExpression(); } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -11734,10 +15794,11 @@ var ts; result.preParameterName = preName; result.typeExpression = typeExpression; result.postParameterName = postName; + result.parameterName = postName || preName; result.isBracketed = isBracketed; return finishNode(result); } - function handleReturnTag(atToken, tagName) { + function parseReturnTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 276; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -11747,7 +15808,7 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handleTypeTag(atToken, tagName) { + function parseTypeTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 277; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -11757,10 +15818,11 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handlePropertyTag(atToken, tagName) { + function parsePropertyTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name = parseJSDocIdentifierName(); + skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; @@ -11772,7 +15834,7 @@ var ts; result.typeExpression = typeExpression; return finishNode(result); } - function handleTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var typedefTag = createNode(279, atToken.pos); @@ -11780,12 +15842,13 @@ var ts; typedefTag.tagName = tagName; typedefTag.name = parseJSDocIdentifierName(); typedefTag.typeExpression = typeExpression; + skipWhitespace(); if (typeExpression) { if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_9 = jsDocTypeReference.name; - if (name_9.text === "Object") { + var name_13 = jsDocTypeReference.name; + if (name_13.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11804,12 +15867,15 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token !== 1 && !parentTagTerminated) { + while (token() !== 1 && !parentTagTerminated) { nextJSDocToken(); - switch (token) { + switch (token()) { case 55: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); + if (!parentTagTerminated) { + resumePos = scanner.getStartPos(); + } } seenAsterisk = false; break; @@ -11835,11 +15901,12 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token === 55); + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return false; } @@ -11848,37 +15915,38 @@ var ts; if (parentTag.jsDocTypeTag) { return false; } - parentTag.jsDocTypeTag = handleTypeTag(atToken, tagName); + parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); return true; case "prop": case "property": if (!parentTag.jsDocPropertyTags) { parentTag.jsDocPropertyTags = []; } - var propertyTag = handlePropertyTag(atToken, tagName); + var propertyTag = parsePropertyTag(atToken, tagName); parentTag.jsDocPropertyTags.push(propertyTag); return true; } return false; } - function handleTemplateTag(atToken, tagName) { + function parseTemplateTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 278; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var typeParameters = []; - typeParameters.pos = scanner.getStartPos(); + var typeParameters = createNodeArray(); while (true) { - var name_10 = parseJSDocIdentifierName(); - if (!name_10) { + var name_14 = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name_14) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_10.pos); - typeParameter.name = name_10; + var typeParameter = createNode(141, name_14.pos); + typeParameter.name = name_14; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24) { + if (token() === 24) { nextJSDocToken(); + skipWhitespace(); } else { break; @@ -11893,10 +15961,10 @@ var ts; return result; } function nextJSDocToken() { - return token = scanner.scanJSDocToken(); + return currentToken = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -12202,7 +16270,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -12210,7 +16277,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 230 || node.kind === 229) && !(node.flags & 1)) { + else if ((node.kind === 230 || node.kind === 229) && !(ts.hasModifier(node, 1))) { return 0; } else if (node.kind === 226) { @@ -12240,9 +16307,10 @@ var ts; ts.getModuleInstanceState = getModuleInstanceState; var binder = createBinder(); function bindSourceFile(file, options) { - var start = new Date().getTime(); + ts.performance.mark("beforeBind"); binder(file, options); - ts.bindTime += new Date().getTime() - start; + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -12270,13 +16338,16 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 }; var reportedUnreachableFlow = { flags: 1 }; + var subtreeTransformFlags = 0; + var skipTransformFlagAggregation; function bindSourceFile(f, opts) { file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; + skipTransformFlagAggregation = ts.isDeclarationFile(file); Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -12300,6 +16371,7 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0; + subtreeTransformFlags = 0; } return bindSourceFile; function createSymbol(flags, name) { @@ -12314,10 +16386,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = {}; + symbol.exports = ts.createMap(); } if (symbolFlags & 6240 && !symbol.members) { - symbol.members = {}; + symbol.members = ts.createMap(); } if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; @@ -12371,14 +16443,14 @@ var ts; break; case 220: case 221: - return node.flags & 512 ? "default" : undefined; + return ts.hasModifier(node, 512) ? "default" : undefined; case 269: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; case 142: ts.Debug.assert(node.parent.kind === 269); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); - return "p" + index; + return "arg" + index; case 279: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; @@ -12398,44 +16470,47 @@ var ts; } function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512; + var isDefaultExport = ts.hasModifier(node, 512); var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name !== undefined) { - symbol = ts.hasProperty(symbolTable, name) - ? symbolTable[name] - : (symbolTable[name] = createSymbol(0, name)); + if (name === undefined) { + symbol = createSymbol(0, "__missing"); + } + else { + symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0, name)); if (name && (includes & 788448)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (node.name) { - node.name.parent = node; + if (symbol.isReplaceableByMethod) { + symbol = symbolTable[name] = createSymbol(0, name); } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + else { + if (node.name) { + node.name.parent = node; } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (ts.hasModifier(declaration, 512)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); + } } } - else { - symbol = createSymbol(0, "__missing"); - } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 8388608) { if (node.kind === 238 || (node.kind === 229 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -12445,10 +16520,10 @@ var ts; } } else { - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793056 ? 2097152 : 0) | - (symbolFlags & 1536 ? 4194304 : 0); + (symbolFlags & 793064 ? 2097152 : 0) | + (symbolFlags & 1920 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -12465,7 +16540,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -12496,11 +16571,11 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); - node.flags &= ~4030464; + node.flags &= ~32128; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { - node.flags |= 32768; + node.flags |= 128; if (hasExplicitReturn) - node.flags |= 65536; + node.flags |= 256; } if (node.kind === 256) { node.flags |= emitFlags; @@ -12521,7 +16596,7 @@ var ts; else if (containerFlags & 64) { seenThisKeyword = false; bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 16384 : node.flags & ~16384; + node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; } else { bindChildren(node); @@ -12530,11 +16605,24 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindChildrenWorker(node) { if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - bind(jsDocComment); - } + ts.forEach(node.jsDocComments, bind); } if (checkUnreachable(node)) { ts.forEachChild(node, bind); @@ -12583,6 +16671,9 @@ var ts; case 185: bindPrefixUnaryExpressionFlow(node); break; + case 186: + bindPostfixUnaryExpressionFlow(node); + break; case 187: bindBinaryExpressionFlow(node); break; @@ -12640,15 +16731,9 @@ var ts; } return false; } - function isNarrowingNullCheckOperands(expr1, expr2) { - return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); - } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } - function isNarrowingDiscriminant(expr) { - return expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -12657,9 +16742,8 @@ var ts; case 31: case 32: case 33: - return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || - isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 91: return isNarrowableOperand(expr.left); case 24: @@ -12681,10 +16765,6 @@ var ts; } return isNarrowableReference(expr); } - function isNarrowingSwitchStatement(switchStatement) { - var expr = switchStatement.expression; - return expr.kind === 172 && isNarrowableReference(expr.expression); - } function createBranchLabel() { return { flags: 4, @@ -12728,7 +16808,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -13069,6 +17149,15 @@ var ts; } else { ts.forEachChild(node, bind); + if (node.operator === 57 || node.operator === 42) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + ts.forEachChild(node, bind); + if (node.operator === 41 || node.operator === 42) { + bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { @@ -13110,7 +17199,7 @@ var ts; currentFlow = finishFlowLabel(postExpressionLabel); } function bindInitializedVariableFlow(node) { - var name = node.name; + var name = !ts.isOmittedExpression(node) ? node.name : undefined; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var child = _a[_i]; @@ -13234,7 +17323,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 32 + return ts.hasModifier(node, 32) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -13257,16 +17346,16 @@ var ts; } function setExportContextFlag(node) { if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 8192; + node.flags |= 32; } else { - node.flags &= ~8192; + node.flags &= ~32; } } function bindModuleDeclaration(node) { setExportContextFlag(node); if (ts.isAmbientModule(node)) { - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (ts.isExternalModuleAugmentation(node)) { @@ -13316,12 +17405,12 @@ var ts; addDeclarationToSymbol(symbol, node, 131072); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; + typeLiteralSymbol.members = ts.createMap(); + typeLiteralSymbol.members[symbol.name] = symbol; } function bindObjectLiteralExpression(node) { if (inStrictMode) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69) { @@ -13337,8 +17426,8 @@ var ts; continue; } if (currentKind === 1 && existingKind === 1) { - var span = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -13360,7 +17449,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -13401,8 +17490,8 @@ var ts; } function checkStrictModeDeleteExpression(node) { if (inStrictMode && node.expression.kind === 69) { - var span = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -13413,8 +17502,8 @@ var ts; if (name && name.kind === 69) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { - var span = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } } } @@ -13499,6 +17588,9 @@ var ts; } parent = saveParent; } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } inStrictMode = saveInStrictMode; } function updateStrictModeStatementList(statements) { @@ -13573,7 +17665,7 @@ var ts; case 154: return checkTypePredicate(node); case 141: - return declareSymbolAndAddToSymbolTable(node, 262144, 530912); + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); case 142: return bindParameter(node); case 218: @@ -13589,9 +17681,9 @@ var ts; case 254: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 107455); + return bindPropertyOrMethodOrAccessor(node, 8, 900095); case 247: - emitFlags |= 1073741824; + emitFlags |= 16384; return; case 151: case 152: @@ -13631,10 +17723,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222: - return bindBlockScopedDeclaration(node, 64, 792960); + return bindBlockScopedDeclaration(node, 64, 792968); case 279: case 223: - return bindBlockScopedDeclaration(node, 524288, 793056); + return bindBlockScopedDeclaration(node, 524288, 793064); case 224: return bindEnumDeclaration(node); case 225: @@ -13683,15 +17775,14 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 235 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } - else if (boundExpression.kind === 69 && node.kind === 235) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); - } else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); + var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) + ? 8388608 + : 4; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); } } function bindNamespaceExportDeclaration(node) { @@ -13713,7 +17804,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || {}; + file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); } function bindExportDeclaration(node) { @@ -13744,18 +17835,20 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); } function bindThisPropertyAssignment(node) { - var assignee; - if (container.kind === 220 || container.kind === 220) { - assignee = container; + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (container.kind === 220 || container.kind === 179) { + container.symbol.members = container.symbol.members || ts.createMap(); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } else if (container.kind === 148) { - assignee = container.parent; + var saveContainer = container; + container = container.parent; + var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); + if (symbol) { + symbol.isReplaceableByMethod = true; + } + container = saveContainer; } - else { - return; - } - assignee.symbol.members = assignee.symbol.members || {}; - declareSymbol(assignee.symbol.members, assignee.symbol, node, 4, 0 & ~4); } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; @@ -13769,7 +17862,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -13781,10 +17874,10 @@ var ts; function bindClassLikeDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 262144; + emitFlags |= 1024; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288; + emitFlags |= 2048; } } if (node.kind === 221) { @@ -13799,7 +17892,7 @@ var ts; } var symbol = node.symbol; var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (symbol.exports[prototypeSymbol.name]) { if (node.name) { node.name.parent = node; } @@ -13833,7 +17926,7 @@ var ts; if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node) && ts.nodeIsDecorated(node)) { - emitFlags |= (524288 | 1048576); + emitFlags |= (2048 | 4096); } if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); @@ -13852,7 +17945,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } } checkStrictModeFunctionName(node); @@ -13867,7 +17960,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } } if (currentFlow) { @@ -13880,10 +17973,10 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152; + emitFlags |= 8192; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288; + emitFlags |= 2048; } } return ts.hasDynamicName(node) @@ -13902,7 +17995,7 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatement(node) && node.kind !== 201) || + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 201) || node.kind === 221 || (node.kind === 225 && shouldReportErrorOnModuleDeclaration(node)) || (node.kind === 224 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); @@ -13911,7 +18004,7 @@ var ts; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && (node.kind !== 200 || - ts.getCombinedNodeFlags(node.declarationList) & 3072 || + ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); @@ -13921,9 +18014,517 @@ var ts; return true; } } + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 174: + return computeCallExpression(node, subtreeFlags); + case 225: + return computeModuleDeclaration(node, subtreeFlags); + case 178: + return computeParenthesizedExpression(node, subtreeFlags); + case 187: + return computeBinaryExpression(node, subtreeFlags); + case 202: + return computeExpressionStatement(node, subtreeFlags); + case 142: + return computeParameter(node, subtreeFlags); + case 180: + return computeArrowFunction(node, subtreeFlags); + case 179: + return computeFunctionExpression(node, subtreeFlags); + case 220: + return computeFunctionDeclaration(node, subtreeFlags); + case 218: + return computeVariableDeclaration(node, subtreeFlags); + case 219: + return computeVariableDeclarationList(node, subtreeFlags); + case 200: + return computeVariableStatement(node, subtreeFlags); + case 214: + return computeLabeledStatement(node, subtreeFlags); + case 221: + return computeClassDeclaration(node, subtreeFlags); + case 192: + return computeClassExpression(node, subtreeFlags); + case 251: + return computeHeritageClause(node, subtreeFlags); + case 194: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 148: + return computeConstructor(node, subtreeFlags); + case 145: + return computePropertyDeclaration(node, subtreeFlags); + case 147: + return computeMethod(node, subtreeFlags); + case 149: + case 150: + return computeAccessor(node, subtreeFlags); + case 229: + return computeImportEquals(node, subtreeFlags); + case 172: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (subtreeFlags & 262144 + || isSuperOrSuperProperty(expression, expressionKind)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537133909; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 95: + return true; + case 172: + case 173: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 95; + } + return false; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 56 + && (leftKind === 171 + || leftKind === 170)) { + transformFlags |= 192 | 256; + } + else if (operatorTokenKind === 38 + || operatorTokenKind === 60) { + transformFlags |= 48; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + if (node.questionToken) { + transformFlags |= 3; + } + if (subtreeFlags & 2048 + || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + transformFlags |= 3; + } + if (modifierFlags & 92) { + transformFlags |= 3 | 131072; + } + if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { + transformFlags |= 192 | 65536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~538968917; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + if (expressionKind === 195 + || expressionKind === 177) { + transformFlags |= 3; + } + if (expressionTransformFlags & 256) { + transformFlags |= 256; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 192; + if ((subtreeFlags & 137216) + || (modifierFlags & 1)) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537590613; + } + function computeClassExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (subtreeFlags & 137216) { + transformFlags |= 3; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537590613; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 83: + transformFlags |= 192; + break; + case 106: + transformFlags |= 3; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.typeArguments) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var body = node.body; + if (body === undefined) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computeMethod(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var typeParameters = node.typeParameters; + var asteriskToken = node.asteriskToken; + if (!body + || typeParameters + || (modifierFlags & (256 | 128)) + || (subtreeFlags & 2048)) { + transformFlags |= 3; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body + || (modifierFlags & (256 | 128)) + || (subtreeFlags & 2048)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550593365; + } + function computePropertyDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags | 3; + if (node.initializer) { + transformFlags |= 4096; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var asteriskToken = node.asteriskToken; + if (!body || (modifierFlags & 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 8388608; + if (modifierFlags & 1) { + transformFlags |= 3 | 192; + } + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550726485; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var asteriskToken = node.asteriskToken; + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 81920) { + transformFlags |= 192; + } + if (asteriskToken && node.emitFlags & 2097152) { + transformFlags |= 1536; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550726485; + } + function computeArrowFunction(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 256) { + transformFlags |= 3; + } + if (subtreeFlags & 8192) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~550710101; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (expressionKind === 95) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var nameKind = node.name.kind; + if (nameKind === 167 || nameKind === 168) { + transformFlags |= 192 | 2097152; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags; + if (modifierFlags & 1) { + transformFlags |= 192 | 3; + } + if (declarationListTransformFlags & 2097152) { + transformFlags |= 192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (subtreeFlags & 1048576 + && ts.isIterationStatement(node, true)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.expression.transformFlags & 256) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536871765; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~546335573; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (node.flags & 3) { + transformFlags |= 192 | 1048576; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~538968917; + } + function computeOther(node, kind, subtreeFlags) { + var transformFlags = subtreeFlags; + var excludeFlags = 536871765; + switch (kind) { + case 112: + case 110: + case 111: + case 115: + case 122: + case 118: + case 74: + case 184: + case 224: + case 255: + case 177: + case 195: + case 196: + case 128: + transformFlags |= 3; + break; + case 241: + case 242: + case 243: + case 244: + case 245: + case 246: + case 247: + case 248: + transformFlags |= 12; + break; + case 82: + transformFlags |= 192 | 3; + break; + case 77: + case 11: + case 12: + case 13: + case 14: + case 189: + case 176: + case 254: + case 208: + transformFlags |= 192; + break; + case 190: + transformFlags |= 192 | 4194304; + break; + case 117: + case 130: + case 127: + case 132: + case 120: + case 133: + case 103: + case 141: + case 144: + case 146: + case 151: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 161: + case 162: + case 163: + case 164: + case 222: + case 223: + case 165: + case 166: + transformFlags = 3; + excludeFlags = -3; + break; + case 140: + transformFlags |= 524288; + if (subtreeFlags & 8192) { + transformFlags |= 32768; + } + break; + case 191: + transformFlags |= 262144; + break; + case 95: + transformFlags |= 192; + break; + case 97: + transformFlags |= 8192; + break; + case 167: + case 168: + transformFlags |= 192 | 2097152; + break; + case 143: + transformFlags |= 3 | 2048; + break; + case 171: + excludeFlags = 537430869; + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + if (subtreeFlags & 32768) { + transformFlags |= 8192; + } + break; + case 170: + case 175: + excludeFlags = 537133909; + if (subtreeFlags & 262144) { + transformFlags |= 192; + } + break; + case 204: + case 205: + case 206: + case 207: + if (subtreeFlags & 1048576) { + transformFlags |= 192; + } + break; + case 256: + if (subtreeFlags & 16384) { + transformFlags |= 192; + } + break; + case 211: + case 209: + case 210: + transformFlags |= 8388608; + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~excludeFlags; + } })(ts || (ts = {})); var ts; (function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -13936,7 +18537,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -13953,7 +18553,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = {}; + var emptySymbols = ts.createMap(); var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -14005,37 +18605,49 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, + getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var stringLiteralTypes = ts.createMap(); + var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var unknownType = createIntrinsicType(1, "unknown"); + var undefinedType = createIntrinsicType(2048, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); + var nullType = createIntrinsicType(4096, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); - var booleanType = createIntrinsicType(8, "boolean"); - var esSymbolType = createIntrinsicType(16777216, "symbol"); - var voidType = createIntrinsicType(16, "void"); - var undefinedType = createIntrinsicType(32, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 | 2097152, "undefined"); - var nullType = createIntrinsicType(64, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 | 2097152, "null"); - var unknownType = createIntrinsicType(1, "unknown"); - var neverType = createIntrinsicType(134217728, "never"); + var trueType = createIntrinsicType(128, "true"); + var falseType = createIntrinsicType(128, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512, "symbol"); + var voidType = createIntrinsicType(1024, "void"); + var neverType = createIntrinsicType(8192, "never"); + var silentNeverType = createIntrinsicType(8192, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = {}; + emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; + anyFunctionType.flags |= 134217728; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, undefined, 0, false, false); var enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = {}; + var globals = ts.createMap(); var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; + var tryGetGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; @@ -14068,10 +18680,8 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var tupleTypes = {}; - var unionTypes = {}; - var intersectionTypes = {}; - var stringLiteralTypes = {}; + var emptyStringType = getLiteralTypeForText(32, ""); + var zeroType = getLiteralTypeForText(64, "0"); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -14087,7 +18697,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1, "number": 2, "boolean": 4, @@ -14095,8 +18705,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128, "number": 256, "boolean": 512, @@ -14104,16 +18714,16 @@ var ts; "undefined": 131072, "object": 2048, "function": 4096 - }; - var typeofTypesByName = { + }); + var typeofTypesByName = ts.createMap({ "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }; + }); var jsxElementType; - var jsxTypes = {}; + var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -14123,15 +18733,14 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = {}; - var assignableRelation = {}; - var comparableRelation = {}; - var identityRelation = {}; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); var _displayBuilder; - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -14157,13 +18766,13 @@ var ts; if (flags & 4) result |= 0; if (flags & 8) - result |= 107455; + result |= 900095; if (flags & 16) result |= 106927; if (flags & 32) result |= 899519; if (flags & 64) - result |= 792960; + result |= 792968; if (flags & 256) result |= 899327; if (flags & 128) @@ -14177,9 +18786,9 @@ var ts; if (flags & 65536) result |= 74687; if (flags & 262144) - result |= 530912; + result |= 530920; if (flags & 524288) - result |= 793056; + result |= 793064; if (flags & 8388608) result |= 8388608; return result; @@ -14200,9 +18809,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = cloneSymbolTable(symbol.members); + result.members = ts.cloneMap(symbol.members); if (symbol.exports) - result.exports = cloneSymbolTable(symbol.exports); + result.exports = ts.cloneMap(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -14222,12 +18831,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = {}; + target.members = ts.createMap(); mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = {}; + target.exports = ts.createMap(); mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -14243,28 +18852,17 @@ var ts; }); } } - function cloneSymbolTable(symbolTable) { - var result = {}; - for (var id in symbolTable) { - if (ts.hasProperty(symbolTable, id)) { - result[id] = symbolTable[id]; - } - } - return result; - } function mergeSymbolTable(target, source) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (!ts.hasProperty(target, id)) { - target[id] = source[id]; - } - else { - var symbol = target[id]; - if (!(symbol.flags & 33554432)) { - target[id] = symbol = cloneSymbol(symbol); - } - mergeSymbol(symbol, source[id]); + var targetSymbol = target[id]; + if (!targetSymbol) { + target[id] = source[id]; + } + else { + if (!(targetSymbol.flags & 33554432)) { + target[id] = targetSymbol = cloneSymbol(targetSymbol); } + mergeSymbol(targetSymbol, source[id]); } } } @@ -14286,7 +18884,7 @@ var ts; return; } mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1536) { + if (mainModule.flags & 1920) { mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } @@ -14297,13 +18895,11 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (ts.hasProperty(target, id)) { - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; - } + if (target[id]) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; } } function addDeclarationDiagnostic(id, message) { @@ -14318,23 +18914,25 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning && ts.hasProperty(symbols, name)) { + if (meaning) { var symbol = symbols[name]; - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { + if (symbol) { + ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { return symbol; } + if (symbol.flags & 8388608) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } } } } @@ -14396,7 +18994,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 145 && - (current.parent.flags & 32) === 0 && + (ts.getModifierFlags(current.parent) & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -14418,7 +19016,7 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793056 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 142 || @@ -14455,7 +19053,7 @@ var ts; } result = undefined; } - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -14472,7 +19070,7 @@ var ts; break; case 145: case 144: - if (ts.isClassLike(location.parent) && !(location.flags & 32)) { + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -14484,8 +19082,8 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { - if (lastLocation && lastLocation.flags & 32) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -14502,7 +19100,7 @@ var ts; case 140: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -14553,8 +19151,10 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14572,7 +19172,7 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule) { + if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -14582,7 +19182,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -14598,7 +19198,7 @@ var ts; error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); return true; } - if (location === container && !(location.flags & 32)) { + if (location === container && !(ts.getModifierFlags(location) & 32)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); @@ -14611,25 +19211,32 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var parentClassExpression = errorLocation; - while (parentClassExpression) { - var kind = parentClassExpression.kind; - if (kind === 69 || kind === 172) { - parentClassExpression = parentClassExpression.parent; - continue; - } - if (kind === 194) { - break; - } - return false; - } - if (!parentClassExpression) { - return false; - } - var expression = parentClassExpression.expression; - if (resolveEntityName(expression, 64, true)) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64, true)); + if (isError) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - return true; + } + return isError; + } + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 69: + case 172: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 194: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (107455 & ~1024)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + if (symbol && !(symbol.flags & 1024)) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } } return false; } @@ -14637,7 +19244,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -14675,7 +19282,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -14694,7 +19301,7 @@ var ts; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793056 | 1536)) { + if (valueSymbol.flags & (793064 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -14710,9 +19317,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536) { - var exports = getExportsOfSymbol(symbol); - if (ts.hasProperty(exports, name)) { - return resolveSymbol(exports[name]); + var exportedSymbol = getExportsOfSymbol(symbol)[name]; + if (exportedSymbol) { + return resolveSymbol(exportedSymbol); } } } @@ -14728,25 +19335,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_11 = specifier.propertyName || specifier.name; - if (name_11.text) { - if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + var name_15 = specifier.propertyName || specifier.name; + if (name_15.text) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); + error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); } return symbol; } @@ -14761,10 +19371,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536); + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 | 793056 | 1536); + return resolveEntityName(node.expression, 107455 | 793064 | 1920); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -14785,7 +19395,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793056 | 1536)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); @@ -14793,6 +19403,7 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -14822,6 +19433,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -14838,24 +19450,24 @@ var ts; entityName = entityName.parent; } if (entityName.kind === 69 || entityName.parent.kind === 139) { - return resolveEntityName(entityName, 1536, false, dontResolveAlias); + return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { ts.Debug.assert(entityName.parent.kind === 229); - return resolveEntityName(entityName, 107455 | 793056 | 1536, false, dontResolveAlias); + return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); } - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias) { + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } var symbol; if (name.kind === 69) { - var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } @@ -14863,7 +19475,7 @@ var ts; else if (name.kind === 139 || name.kind === 172) { var left = name.kind === 139 ? name.left : name.expression; var right = name.kind === 139 ? name.right : name.name; - var namespace = resolveEntityName(left, 1536, ignoreErrors); + var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -14873,7 +19485,7 @@ var ts; symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); } return undefined; } @@ -14892,7 +19504,10 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; - var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } @@ -14903,14 +19518,14 @@ var ts; return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return getMergedSymbol(sourceFile.symbol); } if (moduleNotFoundError) { - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return undefined; } @@ -14921,7 +19536,14 @@ var ts; } } if (moduleNotFoundError) { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } return undefined; } @@ -14951,7 +19573,7 @@ var ts; } function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !ts.hasProperty(target, id)) { + if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -14959,7 +19581,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -14977,11 +19599,11 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = cloneSymbolTable(symbol.exports); + var symbols = ts.cloneMap(symbol.exports); var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = {}; - var lookupTable = {}; + var nestedSymbols = ts.createMap(); + var lookupTable = ts.createMap(); for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -14990,7 +19612,7 @@ var ts; } for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -15041,8 +19663,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount; typeCount++; + result.id = typeCount; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -15050,6 +19672,12 @@ var ts; type.intrinsicName = intrinsicName; return type; } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8; + type.intrinsicName = "boolean"; + return type; + } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -15064,14 +19692,12 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (ts.hasProperty(members, id)) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); } } } @@ -15089,7 +19715,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -15114,7 +19740,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1536; + return rightMeaning === 107455 ? 107455 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -15131,10 +19757,10 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(ts.lookUp(symbols, symbol.name))) { + if (isAccessible(symbols[symbol.name])) { return [symbol]; } - return ts.forEachValue(symbols, function (symbolFromSymbolTable) { + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { @@ -15161,10 +19787,10 @@ var ts; function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - if (!ts.hasProperty(symbolTable, symbol.name)) { + var symbolFromSymbolTable = symbolTable[symbol.name]; + if (!symbolFromSymbolTable) { return false; } - var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { return true; } @@ -15195,19 +19821,19 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined }; } return hasAccessibleDeclarations; @@ -15243,7 +19869,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -15253,16 +19879,18 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1) && + !(ts.getModifierFlags(anyImportSyntax) & 1) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -15278,14 +19906,14 @@ var ts; } else if (entityName.kind === 139 || entityName.kind === 172 || entityName.parent.kind === 229) { - meaning = 1536; + meaning = 1920; } else { - meaning = 793056; + meaning = 793064; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -15332,6 +19960,31 @@ var ts; ts.releaseStringWriter(writer); return result; } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144)) { + if (t.flags & (128 | 256)) { + var baseType = t.flags & 128 ? booleanType : t.baseType; + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } + } + result.push(t); + } + } + if (flags & 4096) + result.push(nullType); + if (flags & 2048) + result.push(undefinedType); + return result || types; + } function visibilityToString(flags) { if (flags === 8) { return "private"; @@ -15358,6 +20011,9 @@ var ts; node.parent.kind === 226 && ts.isExternalModuleAugmentation(node.parent.parent); } + function literalTypeToString(type) { + return type.flags & 32 ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -15417,71 +20073,77 @@ var ts; parentSymbol = symbol; } writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning) { - if (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_7) { + walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else { - if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { - return; - } - if (symbol.flags & 2048 || symbol.flags & 4096) { - return; - } - appendParentTypeArgumentsAndSymbolName(symbol); + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } + else if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } } var isTypeParameter = symbol.flags & 262144; var typeFormatFlag = 128 & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning); - return; + walkSymbol(symbol, meaning, true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); } - return appendParentTypeArgumentsAndSymbolName(symbol); } function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - if (type.flags & 150995071) { + var nextFlags = flags & ~512; + if (type.flags & 16015) { writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 33554432) { + else if (type.flags & 268435456) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 4096) { - writeTypeReference(type, flags); - } - else if (type.flags & (1024 | 2048 | 128 | 512)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056, 0, flags); - } - else if (type.flags & 8192) { - writeTupleType(type); - } - else if (type.flags & 49152) { - writeUnionOrIntersectionType(type, flags); - } - else if (type.flags & 65536) { - writeAnonymousType(type, flags); + else if (type.flags & 131072) { + writeTypeReference(type, nextFlags); } else if (type.flags & 256) { - writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); + buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); + writePunctuation(writer, 21); + appendSymbolNameOnly(type.symbol, writer); + } + else if (type.flags & (32768 | 65536 | 16 | 16384)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); + } + else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); + } + else if (type.flags & 1572864) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (type.flags & 2097152) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96) { + writer.writeStringLiteral(literalTypeToString(type)); } else { writePunctuation(writer, 15); @@ -15505,7 +20167,7 @@ var ts; } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056, 0, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); } if (pos < end) { writePunctuation(writer, 25); @@ -15527,6 +20189,11 @@ var ts; writePunctuation(writer, 19); writePunctuation(writer, 20); } + else if (type.target.flags & 262144) { + writePunctuation(writer, 19); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); + writePunctuation(writer, 20); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -15534,12 +20201,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_7 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_7); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_7, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -15548,16 +20215,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } - function writeTupleType(type) { - writePunctuation(writer, 19); - writeTypeList(type.elementTypes, 24); - writePunctuation(writer, 20); - } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { writePunctuation(writer, 17); } - writeTypeList(type.types, type.flags & 16384 ? 47 : 46); + if (type.flags & 524288) { + writeTypeList(formatUnionTypes(type.types), 47); + } + else { + writeTypeList(type.types, 46); + } if (flags & 64) { writePunctuation(writer, 18); } @@ -15574,7 +20241,7 @@ var ts; else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); } else { writeKeyword(writer, 117); @@ -15594,7 +20261,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32; })); + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -15780,7 +20447,7 @@ var ts; } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingElement.kind === 193) { + if (ts.isOmittedExpression(bindingElement)) { return; } ts.Debug.assert(bindingElement.kind === 169); @@ -15928,19 +20595,19 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_8 = getDeclarationContainer(node); - if (!(ts.getCombinedNodeFlags(node) & 1) && - !(node.kind !== 229 && parent_8.kind !== 256 && ts.isInAmbientContext(parent_8))) { - return isGlobalSourceFile(parent_8); + var parent_9 = getDeclarationContainer(node); + if (!(ts.getCombinedModifierFlags(node) & 1) && + !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { + return isGlobalSourceFile(parent_9); } - return isDeclarationVisible(parent_8); + return isDeclarationVisible(parent_9); case 145: case 144: case 149: case 150: case 147: case 146: - if (node.flags & (8 | 16)) { + if (ts.getModifierFlags(node) & (8 | 16)) { return false; } case 148: @@ -15965,6 +20632,7 @@ var ts; return false; case 141: case 256: + case 228: return true; case 235: return false; @@ -15976,13 +20644,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793056 | 1536 | 8388608); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); } var result = []; if (exportSymbol) { @@ -15999,7 +20667,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -16040,7 +20708,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 1024)); + ts.Debug.assert(!!(target.flags & 32768)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -16082,7 +20750,7 @@ var ts; return type && (type.flags & 1) !== 0; } function isTypeNever(type) { - return type && (type.flags & 134217728) !== 0; + return type && (type.flags & 8192) !== 0; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); @@ -16113,25 +20781,25 @@ var ts; } if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { - return checkExpressionCached(declaration.initializer); + return checkDeclarationInitializer(declaration); } return parentType; } var type; if (pattern.kind === 167) { - var name_12 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_12)) { + var name_16 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_16)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_12); + var text = getTextOfPropertyName(name_16); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); + error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); return unknownType; } } @@ -16144,7 +20812,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -16156,10 +20824,12 @@ var ts; type = createArrayType(elementType); } } - if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { type = getTypeWithFacts(type, 131072); } - return type; + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -16189,10 +20859,10 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? addTypeKind(type, 32) : type; + return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -16224,40 +20894,44 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - var type = declaration.symbol.name === "this" - ? getContextuallyTypedThisType(func) - : getContextuallyTypedParameterType(declaration); + var type = void 0; + if (declaration.symbol.name === "this") { + var thisParameter = getContextualThisParameter(func); + type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + } + else { + type = getContextuallyTypedParameterType(declaration); + } if (type) { return addOptionality(type, declaration.questionToken && includeOptionality); } } if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), declaration.questionToken && includeOptionality); + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, declaration.questionToken && includeOptionality); } if (declaration.kind === 254) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false); + return getTypeFromBindingPattern(declaration.name, false, true); } return undefined; } - function getTypeFromBindingElement(element, includePatternInType) { + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - var type = checkExpressionCached(element.initializer); - reportErrorsFromWidening(element, type); - return getWidenedType(type); + return checkDeclarationInitializer(element); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType); + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } - function getTypeFromObjectBindingPattern(pattern, includePatternInType) { - var members = {}; + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createMap(); var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -16268,7 +20942,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -16277,27 +20951,28 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 67108864; + result.flags |= 536870912; } return result; } - function getTypeFromArrayBindingPattern(pattern, includePatternInType) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; - if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); if (includePatternInType) { - var result = createNewTupleType(elementTypes); + result = cloneTypeReference(result); result.pattern = pattern; - return result; } - return createTupleType(elementTypes); + return result; } - function getTypeFromBindingPattern(pattern, includePatternInType) { + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { return pattern.kind === 167 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType) - : getTypeFromArrayBindingPattern(pattern, includePatternInType); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration, true); @@ -16336,19 +21011,27 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } + if (declaration.flags & 1048576 && declaration.kind === 280 && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = undefined; - if (declaration.kind === 187) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - else if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - type = checkExpressionCached(declaration.parent.right); + var type = void 0; + if (declaration.kind === 187 || + declaration.kind === 172 && declaration.parent.kind === 187) { + if (declaration.flags & 1048576) { + var typeTag = ts.getJSDocTypeTag(declaration.parent); + if (typeTag && typeTag.typeExpression) { + return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + } } + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + checkExpressionCached(decl.right) : + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -16391,7 +21074,7 @@ var ts; if (!links.type) { var getter = ts.getDeclarationOfKind(symbol, 149); var setter = ts.getDeclarationOfKind(symbol, 150); - if (getter && getter.flags & 134217728) { + if (getter && getter.flags & 1048576) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -16416,7 +21099,13 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } type = anyType; } @@ -16436,13 +21125,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(65536, symbol); + var type = createObjectType(2097152, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + includeFalsyTypes(type, 2048) : type; } } return links.type; @@ -16450,7 +21139,7 @@ var ts; function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.type = getDeclaredTypeOfEnumMember(symbol); } return links.type; } @@ -16493,7 +21182,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 4096 ? type.target : type; + return type.flags & 131072 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -16553,7 +21242,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 80896 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -16565,7 +21254,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -16580,7 +21269,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -16596,25 +21285,28 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { - var isClass = type.symbol.flags & 32; - var isInterface = type.symbol.flags & 64; if (!type.resolvedBaseTypes) { - if (!isClass && !isInterface) { + if (type.flags & 262144) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 | 64)) { + if (type.symbol.flags & 32) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64) { + resolveBaseTypesOfInterface(type); + } + } + else { ts.Debug.fail("type must be class or interface"); } - if (isClass) { - resolveBaseTypesOfClass(type); - } - if (isInterface) { - resolveBaseTypesOfInterface(type); - } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 80896)) { + if (!(baseConstructorType.flags & 2588672)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -16635,7 +21327,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (1024 | 2048))) { + if (!(getTargetType(baseType).flags & (32768 | 65536))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -16668,7 +21360,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (1024 | 2048)) { + if (getTargetType(baseType).flags & (32768 | 65536)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -16693,15 +21385,15 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 222) { - if (declaration.flags & 16384) { + if (declaration.flags & 64) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isSupportedExpressionWithTypeArguments(node)) { - var baseSymbol = resolveEntityName(node.expression, 793056, true); + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -16715,20 +21407,20 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 1024 : 2048; + var kind = symbol.flags & 32 ? 32768 : 65536; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1024 || !isIndependentInterface(symbol)) { - type.flags |= 4096; + if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { + type.flags |= 131072; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = {}; + type.instantiations = ts.createMap(); type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(512 | 33554432); + type.thisType = createType(16384 | 268435456); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -16741,8 +21433,9 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var type = void 0; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var declaration = ts.getDeclarationOfKind(symbol, 279); + var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -16753,12 +21446,12 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type); + type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); } if (popTypeResolution()) { - links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (links.typeParameters) { - links.instantiations = {}; + links.typeParameters = typeParameters; + if (typeParameters) { + links.instantiations = ts.createMap(); links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -16770,19 +21463,84 @@ var ts; } return links.declaredType; } + function isLiteralEnumMember(symbol, member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + return expr.kind === 8 || + expr.kind === 185 && expr.operator === 36 && + expr.operand.kind === 8 || + expr.kind === 69 && !!symbol.exports[expr.text]; + } + function enumHasLiteralMembers(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (!isLiteralEnumMember(symbol, member)) { + return false; + } + } + } + } + return true; + } + function createEnumLiteralType(symbol, baseType, text) { + var type = createType(256); + type.symbol = symbol; + type.baseType = baseType; + type.text = text; + return type; + } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(128); - type.symbol = symbol; - links.declaredType = type; + var enumType = links.declaredType = createType(16); + enumType.symbol = symbol; + if (enumHasLiteralMembers(symbol)) { + var memberTypeList = []; + var memberTypes = ts.createMap(); + for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224) { + computeEnumMemberValues(declaration); + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberSymbol = getSymbolOfNode(member); + var value = getEnumMemberValue(member); + if (!memberTypes[value]) { + var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); + memberTypeList.push(memberType); + } + } + } + } + enumType.memberTypes = memberTypes; + if (memberTypeList.length > 1) { + enumType.flags |= 524288; + enumType.types = memberTypeList; + unionTypes[getTypeListId(memberTypeList)] = enumType; + } + } + } + return links.declaredType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.declaredType = enumType.flags & 524288 ? + enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : + enumType; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(512); + var type = createType(16384); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141).constraint) { type.constraint = noConstraintType; @@ -16806,11 +21564,14 @@ var ts; if (symbol.flags & 524288) { return getDeclaredTypeOfTypeAlias(symbol); } + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); + } if (symbol.flags & 384) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); + if (symbol.flags & 8) { + return getDeclaredTypeOfEnumMember(symbol); } if (symbol.flags & 8388608) { return getDeclaredTypeOfAlias(symbol); @@ -16881,7 +21642,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -16889,7 +21650,7 @@ var ts; return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -16899,7 +21660,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!ts.hasProperty(symbols, s.name)) { + if (!symbols[s.name]) { symbols[s.name] = s; } } @@ -16916,19 +21677,27 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 4096) { + if (type.flags & 131072) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper = identityMapper; - var members = source.symbol.members; - var callSignatures = source.declaredCallSignatures; - var constructSignatures = source.declaredConstructSignatures; - var stringIndexInfo = source.declaredStringIndexInfo; - var numberIndexInfo = source.declaredNumberIndexInfo; - if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -16938,7 +21707,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (members === source.symbol.members) { + if (source.symbol && members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -16964,7 +21733,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -16974,11 +21743,11 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasStringLiterals = hasStringLiterals; + sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -16987,7 +21756,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -17002,22 +21771,6 @@ var ts; } return result; } - function createTupleTypeMemberSymbols(memberTypes) { - var members = {}; - for (var i = 0; i < memberTypes.length; i++) { - var symbol = createSymbol(4 | 67108864, "" + i); - symbol.type = memberTypes[i]; - members[i] = symbol; - } - return members; - } - function resolveTupleTypeMembers(type) { - var arrayElementType = getUnionType(type.elementTypes, true); - var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); - var members = createTupleTypeMemberSymbols(type.elementTypes); - addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); - } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -17063,7 +21816,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; @@ -17088,7 +21841,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -17148,7 +21901,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -17162,41 +21915,36 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 4096) { + if (type.flags & 131072) { resolveTypeReferenceMembers(type); } - else if (type.flags & (1024 | 2048)) { + else if (type.flags & (32768 | 65536)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 65536) { + else if (type.flags & 2097152) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 8192) { - resolveTupleTypeMembers(type); - } - else if (type.flags & 16384) { + else if (type.flags & 524288) { resolveUnionTypeMembers(type); } - else if (type.flags & 32768) { + else if (type.flags & 1048576) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } } } @@ -17207,7 +21955,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 16384) { + if (type.flags & 524288) { break; } } @@ -17215,12 +21963,12 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 512) { + while (constraintType && constraintType.flags & 16384) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -17228,19 +21976,19 @@ var ts; return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 512) { + if (type.flags & 16384) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 258) { + if (type.flags & 34) { type = globalStringType; } - else if (type.flags & 132) { + else if (type.flags & 340) { type = globalNumberType; } - else if (type.flags & 8) { + else if (type.flags & 136) { type = globalBooleanType; } - else if (type.flags & 16777216) { + else if (type.flags & 512) { type = getGlobalESSymbolType(); } return type; @@ -17248,14 +21996,14 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; + var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 | 16))) { + if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16))) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -17267,7 +22015,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384) { + else if (containingType.flags & 524288) { return undefined; } } @@ -17280,11 +22028,20 @@ var ts; } var propTypes = []; var declarations = []; + var commonType = undefined; + var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + hasCommonType = false; + } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 | @@ -17292,47 +22049,46 @@ var ts; 268435456 | commonFlags, name); result.containingType = containingType; + result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = {}); - if (ts.hasProperty(properties, name)) { - return properties[name]; - } - var property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; + var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); + var property = properties[name]; + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; + } } return property; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol = getPropertyOfObjectType(globalFunctionType, name); - if (symbol) { - return symbol; + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 49152) { + if (type.flags & 1572864) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 130048) { + if (type.flags & 4161536) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -17342,7 +22098,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 130048) { + if (type.flags & 4161536) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -17367,13 +22123,13 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, true); } } return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -17401,7 +22157,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 134217728) { + if (node.flags & 1048576) { if (node.type && node.type.kind === 268) { return true; } @@ -17450,7 +22206,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasStringLiterals = false; + var hasLiteralTypes = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -17470,7 +22226,7 @@ var ts; parameters.push(paramSymbol); } if (param.type && param.type.kind === 166) { - hasStringLiterals = true; + hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -17496,6 +22252,9 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } + if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { + thisParameter = getContextualThisParameter(declaration); + } var classType = declaration.kind === 148 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -17506,7 +22265,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } @@ -17520,7 +22279,7 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 134217728) { + if (declaration.flags & 1048576) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -17591,7 +22350,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); } else { type = getReturnTypeFromBody(signature.declaration); @@ -17615,7 +22374,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 4096 && type.target === globalArrayType) { + if (type.flags & 131072 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -17635,7 +22394,7 @@ var ts; function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(65536 | 262144); + var type = createObjectType(2097152); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -17670,7 +22429,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); } return undefined; } @@ -17679,7 +22438,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { + while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -17711,24 +22470,27 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); } function getTypeListId(types) { + var result = ""; if (types) { - switch (types.length) { - case 1: - return "" + types[0].id; - case 2: - return types[0].id + "," + types[1].id; - default: - var result = ""; - for (var i = 0; i < types.length; i++) { - if (i > 0) { - result += ","; - } - result += types[i].id; - } - return result; + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; } } - return ""; + return result; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; @@ -17738,20 +22500,29 @@ var ts; result |= type.flags; } } - return result & 14680064; + return result & 234881024; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 4096 | propagatedFlags; + var flags = 131072 | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } + function cloneTypeReference(source) { + var type = createObjectType(source.flags, source.symbol); + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return type.target.typeParameters ? type.target.typeParameters.length : 0; + } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; @@ -17760,7 +22531,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); return unknownType; } - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -17777,7 +22548,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); var id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } @@ -17801,8 +22572,9 @@ var ts; case 267: return node.name; case 194: - if (ts.isSupportedExpressionWithTypeArguments(node)) { - return node.expression; + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; } } return undefined; @@ -17811,7 +22583,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -17837,14 +22609,14 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); - links.resolvedSymbol = symbol; - links.resolvedType = type; } else { - var typeNameOrExpression = node.kind === 155 ? node.typeName : - ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : - undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 + ? node.typeName + : ts.isEntityNameExpression(node.expression) + ? node.expression + : undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : @@ -17879,7 +22651,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 80896)) { + if (!(type.flags & 2588672)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -17893,7 +22665,7 @@ var ts; return getGlobalSymbol(name, 107455, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793056, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793064, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -17903,8 +22675,8 @@ var ts; return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); + var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } function createTypedPropertyDescriptorType(propertyType) { @@ -17932,47 +22704,115 @@ var ts; } return links.resolvedType; } - function createTupleType(elementTypes) { - var id = getTypeListId(elementTypes); - return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); - } - function createNewTupleType(elementTypes) { - var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, 0); - var type = createObjectType(8192 | propagatedFlags); - type.elementTypes = elementTypes; + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384); + typeParameters.push(typeParameter); + var property = createSymbol(4 | 67108864, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(262144 | 131072); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 | 268435456); + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; return type; } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); } return links.resolvedType; } - function addTypeToSet(typeSet, type, typeSetKind) { - if (type.flags & typeSetKind) { - addTypesToSet(typeSet, type.types, typeSetKind); + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } } - else if (type.flags & (1 | 32 | 64)) { - if (type.flags & 1) - typeSet.containsAny = true; - if (type.flags & 32) + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 524288) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144) { + if (flags & 2048) typeSet.containsUndefined = true; - if (type.flags & 64) + if (flags & 4096) typeSet.containsNull = true; - if (!(type.flags & 2097152)) + if (!(flags & 33554432)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(flags & 8192)) { + if (flags & 2) + typeSet.containsString = true; + if (flags & 4) + typeSet.containsNumber = true; + if (flags & 96) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } } } - function addTypesToSet(typeSet, types, typeSetKind) { + function addTypesToUnion(typeSet, types) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToSet(typeSet, type, typeSetKind); + addTypeToUnion(typeSet, type); } } + function containsIdenticalType(types, type) { + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -17986,11 +22826,24 @@ var ts; while (i > 0) { i--; if (isSubtypeOfAny(types[i], types)) { - types.splice(i, 1); + ts.orderedRemoveItemAt(types, i); } } } - function getUnionType(types, noSubtypeReduction) { + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 && types.containsString || + t.flags & 64 && types.containsNumber || + t.flags & 96 && t.flags & 16777216 && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -17998,96 +22851,132 @@ var ts; return types[0]; } var typeSet = []; - addTypesToSet(typeSet, types, 16384); + addTypesToUnion(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } - if (!noSubtypeReduction) { + if (subtypeReduction) { removeSubtypes(typeSet); } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - else if (typeSet.length === 1) { - return typeSet[0]; + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; } - var id = getTypeListId(typeSet); + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); - type = unionTypes[id] = createObjectType(16384 | propagatedFlags); - type.types = typeSet; + var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); + type = unionTypes[id] = createObjectType(524288 | propagatedFlags); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node) { + function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), true); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), false, aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getIntersectionType(types) { + function addTypeToIntersection(typeSet, type) { + if (type.flags & 1048576) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + addTypeToIntersection(typeSet, type); + } + } + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToSet(typeSet, types, 32768); + addTypesToIntersection(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); - type = intersectionTypes[id] = createObjectType(32768 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); + type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node) { + function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createObjectType(65536, node.symbol); + var type = createObjectType(2097152, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + links.resolvedType = type; } return links.resolvedType; } - function getStringLiteralTypeForText(text) { - if (ts.hasProperty(stringLiteralTypes, text)) { - return stringLiteralTypes[text]; - } - var type = stringLiteralTypes[text] = createType(256); + function createLiteralType(flags, text) { + var type = createType(flags); type.text = text; return type; } - function getTypeFromStringLiteralTypeNode(node) { + function getFreshTypeOfLiteralType(type) { + if (type.flags & 96 && !(type.flags & 16777216)) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags | 16777216, type.text); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 && type.flags & 16777216 ? type.regularType : type; + } + function getLiteralTypeForText(flags, text) { + var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; + return map[text] || (map[text] = createLiteralType(flags, text)); + } + function getTypeFromLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); } return links.resolvedType; } @@ -18102,7 +22991,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); + var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -18111,8 +23000,8 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 222)) { - if (!(container.flags & 32) && - (container.kind !== 148 || ts.isNodeDescendentOf(node, container.body))) { + if (!(ts.getModifierFlags(container) & 32) && + (container.kind !== 148 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -18126,7 +23015,10 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNodeNoAlias(type) { + return getTypeFromTypeNode(type, undefined, undefined); + } + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117: case 258: @@ -18148,11 +23040,19 @@ var ts; return nullType; case 127: return neverType; + case 283: + return nullType; + case 284: + return undefinedType; + case 285: + return neverType; case 165: case 97: return getTypeFromThisTypeNode(node); case 166: - return getTypeFromStringLiteralTypeNode(node); + return getTypeFromLiteralTypeNode(node); + case 282: + return getTypeFromLiteralTypeNode(node.literal); case 155: case 267: return getTypeFromTypeReference(node); @@ -18169,9 +23069,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162: case 261: - return getTypeFromUnionTypeNode(node); + return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); case 163: - return getTypeFromIntersectionTypeNode(node); + return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); case 164: case 263: case 264: @@ -18179,13 +23079,14 @@ var ts; case 272: case 268: return getTypeFromTypeNode(node.type); + case 265: + return getTypeFromTypeNode(node.literal); case 156: case 157: case 159: case 281: case 269: - case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -18231,6 +23132,7 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; + mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -18239,7 +23141,7 @@ var ts; function getInferenceMapper(context) { if (!context.mapper) { var mapper = function (t) { - var typeParameters = context.typeParameters; + var typeParameters = context.signature.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (t === typeParameters[i]) { context.inferences[i].isFixed = true; @@ -18248,7 +23150,7 @@ var ts; } return t; }; - mapper.mappedTypes = context.typeParameters; + mapper.mappedTypes = context.signature.typeParameters; mapper.context = context; context.mapper = mapper; } @@ -18263,7 +23165,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(512); + var result = createType(16384); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -18298,7 +23200,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -18329,9 +23231,11 @@ var ts; else { mapper.instantiations = []; } - var result = createObjectType(65536 | 131072, type.symbol); + var result = createObjectType(2097152 | 4194304, type.symbol); result.target = type; result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -18383,26 +23287,23 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 512) { + if (type.flags & 16384) { return mapper(type); } - if (type.flags & 65536) { + if (type.flags & 2097152) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 131072 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 4096) { + if (type.flags & 131072) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 8192) { - return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); + if (type.flags & 524288 && !(type.flags & 8190)) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); } - if (type.flags & 16384) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), true); - } - if (type.flags & 32768) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); + if (type.flags & 1048576) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); } } return type; @@ -18445,10 +23346,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(65536, type.symbol); + var result = createObjectType(2097152, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -18459,22 +23360,25 @@ var ts; return type; } function isTypeIdenticalTo(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined); + return isTypeRelatedTo(source, target, identityRelation); } function compareTypesIdentical(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; + return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; } function compareTypesAssignable(source, target) { - return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; + return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; } function isTypeSubtypeOf(source, target) { - return checkTypeSubtypeOf(source, target, undefined); + return isTypeRelatedTo(source, target, subtypeRelation); } function isTypeAssignableTo(source, target) { - return checkTypeAssignableTo(source, target, undefined); + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeInstanceOf(source, target) { + return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); } function isTypeComparableTo(source, target) { - return checkTypeComparableTo(source, target, undefined); + return isTypeRelatedTo(source, target, comparableRelation); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -18587,8 +23491,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) - || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { return isSignatureAssignableTo(erasedSource, erasedTarget, true); } return false; @@ -18614,6 +23518,94 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + var id = source.id + "," + target.id; + if (enumRelation[id] !== undefined) { + return enumRelation[id]; + } + if (source.symbol.name !== target.symbol.name || + !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || + (source.flags & 524288) !== (target.flags & 524288)) { + return enumRelation[id] = false; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + } + return enumRelation[id] = false; + } + } + } + return enumRelation[id] = true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + if (target.flags & 8192) + return false; + if (target.flags & 1 || source.flags & 8192) + return true; + if (source.flags & 34 && target.flags & 2) + return true; + if (source.flags & 340 && target.flags & 4) + return true; + if (source.flags & 136 && target.flags & 8) + return true; + if (source.flags & 256 && target.flags & 16 && source.baseType === target) + return true; + if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) + return true; + if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) + return true; + if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1) + return true; + if ((source.flags & 4 | source.flags & 64) && target.flags & 272) + return true; + if (source.flags & 256 && + target.flags & 256 && + source.text === target.text && + isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + return true; + } + if (source.flags & 256 && + target.flags & 16 && + isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { + return true; + } + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 && source.flags & 16777216) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 16777216) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 2588672 && target.flags & 2588672) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation[id]; + if (related !== undefined) { + return related === 1; + } + } + if (source.flags & 4177920 || target.flags & 4177920) { + return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + } + return false; + } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; @@ -18652,85 +23644,73 @@ var ts; } reportError(message, sourceType, targetType); } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType() === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; + if (source.flags & 96 && source.flags & 16777216) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 16777216) { + target = target.regularType; + } if (source === target) return -1; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (!(target.flags & 134217728)) { - if (target.flags & 1 || source.flags & 134217728) - return -1; - if (source.flags & 32) { - if (!strictNullChecks || target.flags & (32 | 16)) - return -1; - } - if (source.flags & 64) { - if (!strictNullChecks || target.flags & 64) - return -1; - } - if (source.flags & 128 && target === numberType) - return -1; - if (source.flags & 128 && target.flags & 128) { - if (result = enumRelatedTo(source, target, reportErrors)) { - return result; - } - } - if (source.flags & 256 && target === stringType) - return -1; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return -1; - if (source === numberType && target.flags & 128) - return -1; - } - if (source.flags & 8 && target.flags & 8) { - return -1; - } - } - if (source.flags & 1048576) { + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1; + if (source.flags & 8388608 && source.flags & 16777216) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 49152) { + if (target.flags & 1572864) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 16384) { + if (source.flags & 524288) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors); + result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } else { - result = eachTypeRelatedToType(source, target, reportErrors); + result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } if (result) { return result; } } - else if (target.flags & 32768) { + else if (target.flags & 1048576) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; } } else { - if (source.flags & 32768) { + if (source.flags & 1048576) { if (result = someTypeRelatedToType(source, target, false)) { return result; } } - if (target.flags & 16384) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726))) { + if (target.flags & 524288) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { return result; } } } - if (source.flags & 512) { + if (source.flags & 16384) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1) { constraint = emptyObjectType; @@ -18743,14 +23723,14 @@ var ts; } } else { - if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); + if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -18758,22 +23738,28 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 2588672 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } reportRelationError(headMessage, source, target); } return 0; } function isIdenticalTo(source, target) { var result; - if (source.flags & 80896 && target.flags & 80896) { - if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + if (source.flags & 2588672 && target.flags & 2588672) { + if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 16384 && target.flags & 16384 || - source.flags & 32768 && target.flags & 32768) { + if (source.flags & 524288 && target.flags & 524288 || + source.flags & 1048576 && target.flags & 1048576) { if (result = eachTypeRelatedToSomeType(source, target, false)) { if (result &= eachTypeRelatedToSomeType(target, source, false)) { return result; @@ -18783,7 +23769,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -18792,7 +23778,7 @@ var ts; return true; } } - else if (type.flags & 49152) { + else if (type.flags & 1572864) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -18810,7 +23796,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { + if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -18840,14 +23826,10 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - var len = targetTypes.length; - while (len >= 2 && targetTypes[len - 1].flags & 96) { - var related = isRelatedTo(source, targetTypes[len - 1], false); - if (related) { - return related; - } - len--; + if (target.flags & 524288 && containsType(targetTypes, source)) { + return -1; } + var len = targetTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -18871,14 +23853,10 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - var len = sourceTypes.length; - while (len >= 2 && sourceTypes[len - 1].flags & 96) { - var related = isRelatedTo(sourceTypes[len - 1], target, false); - if (related) { - return related; - } - len--; + if (source.flags & 524288 && containsType(sourceTypes, target)) { + return -1; } + var len = sourceTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -18950,7 +23928,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -18982,7 +23960,7 @@ var ts; if (result) { var maybeCache = maybeStack[depth]; var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyMap(maybeCache, destinationCache); + ts.copyProperties(maybeCache, destinationCache); } else { relation[id] = reportErrors ? 3 : 2; @@ -18995,9 +23973,9 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); - for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { - var targetProp = properties_1[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -19009,8 +23987,8 @@ var ts; } } else if (!(targetProp.flags & 134217728)) { - var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -19061,7 +24039,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 80896 && target.flags & 80896)) { + if (!(source.flags & 2588672 && target.flags & 2588672)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -19174,7 +24152,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 8190))) { return -1; } var sourceInfo = getIndexInfoOfType(source, kind) || @@ -19211,33 +24189,12 @@ var ts; } return 0; } - function enumRelatedTo(source, target, reportErrors) { - if (source.symbol.name !== target.symbol.name || - source.symbol.flags & 128 || - target.symbol.flags & 128) { - return 0; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); - } - return 0; - } - } - } - return -1; - } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = sourceSignature.declaration.flags & (8 | 16); - var targetAccessibility = targetSignature.declaration.flags & (8 | 16); + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; if (targetAccessibility === 8) { return true; } @@ -19254,11 +24211,11 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 65536) { + if (type.flags & 2097152) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && declaration.flags & 128) { + if (declaration && ts.getModifierFlags(declaration) & 128) { return true; } } @@ -19266,12 +24223,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (4096 | 131072) && depth >= 5) { + if (type.flags & (131072 | 4194304) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (4096 | 131072) && t.symbol === symbol) { + if (t.flags & (131072 | 4194304) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -19287,8 +24244,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 | 16); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 | 16); + var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24; if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -19313,8 +24270,10 @@ var ts; source.hasRestParameter === target.hasRestParameter) { return true; } - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || - source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -19364,31 +24323,40 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } - function getCombinedFlagsOfTypes(types) { - var flags = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - flags |= t.flags; + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } } - return flags; + return true; + } + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } function getCommonSupertype(types) { if (!strictNullChecks) { - return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); if (!primaryTypes.length) { - return getUnionType(types); + return getUnionType(types, true); } - var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96); + var supertype = getSupertypeOrUnion(primaryTypes); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -19418,44 +24386,80 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 4096 && type.target === globalArrayType; + return type.flags & 131072 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 96) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralUnionType(type) { - return type.flags & 256 ? true : - type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : - false; + function isUnitType(type) { + return (type.flags & (480 | 2048 | 4096)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 ? true : + type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 32 ? stringType : + type.flags & 64 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 256 ? type.baseType : + type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 32 && type.flags & 16777216 ? stringType : + type.flags & 64 && type.flags & 16777216 ? numberType : + type.flags & 128 ? booleanType : + type.flags & 256 ? type.baseType : + type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type; } function isTupleType(type) { - return !!(type.flags & 8192); + return !!(type.flags & 131072 && type.target.flags & 262144); } - function getCombinedTypeFlags(type) { - return type.flags & 16384 ? getCombinedFlagsOfTypes(type.types) : type.flags; + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; } - function addTypeKind(type, kind) { - if ((getCombinedTypeFlags(type) & kind) === kind) { + function getFalsyFlags(type) { + return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : + type.flags & 32 ? type.text === "" ? 32 : 0 : + type.flags & 64 ? type.text === "0" ? 64 : 0 : + type.flags & 128 ? type === falseType ? 128 : 0 : + type.flags & 7406; + } + function includeFalsyTypes(type, flags) { + if ((getFalsyFlags(type) & flags) === flags) { return type; } var types = [type]; - if (kind & 2) - types.push(stringType); - if (kind & 4) - types.push(numberType); - if (kind & 8) - types.push(booleanType); - if (kind & 16) + if (flags & 34) + types.push(emptyStringType); + if (flags & 340) + types.push(zeroType); + if (flags & 136) + types.push(falseType); + if (flags & 1024) types.push(voidType); - if (kind & 32) + if (flags & 2048) types.push(undefinedType); - if (kind & 64) + if (flags & 4096) types.push(nullType); - return getUnionType(types); + return getUnionType(types, true); + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 7392 ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : + type; } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; @@ -19477,7 +24481,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = {}; + var members = ts.createMap(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -19488,7 +24492,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576)) { + if (!(type.flags & 8388608 && type.flags & 16777216)) { return type; } var regularType = type.regularType; @@ -19498,7 +24502,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; + regularNew.flags = resolved.flags & ~16777216; type.regularType = regularNew; return regularNew; } @@ -19512,31 +24516,28 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 96 ? type : getWidenedType(type); + return type.flags & 6144 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 96) { + if (type.flags & 100663296) { + if (type.flags & 6144) { return anyType; } - if (type.flags & 524288) { + if (type.flags & 8388608) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 16384) { - return getUnionType(ts.map(type.types, getWidenedConstituentType), true); + if (type.flags & 524288) { + return getUnionType(ts.map(type.types, getWidenedConstituentType)); } - if (isArrayType(type)) { - return createArrayType(getWidenedType(type.typeArguments[0])); - } - if (isTupleType(type)) { - return createTupleType(ts.map(type.elementTypes, getWidenedType)); + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 16384) { + if (type.flags & 524288) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -19544,22 +24545,19 @@ var ts; } } } - if (isArrayType(type)) { - return reportWideningErrorsInType(type.typeArguments[0]); - } - if (isTupleType(type)) { - for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 524288) { + if (type.flags & 8388608) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { + if (t.flags & 33554432) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -19604,7 +24602,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -19630,29 +24628,46 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = ts.map(typeParameters, createTypeInferencesObject); + function createInferenceContext(signature, inferUnionTypes) { + var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); return { - typeParameters: typeParameters, + signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length) }; } function createTypeInferencesObject() { return { primary: undefined, secondary: undefined, + topLevel: true, isFixed: false }; } - function inferTypes(context, source, target) { + function couldContainTypeParameters(type) { + return !!(type.flags & 16384 || + type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || + type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || + type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); + } + function couldUnionOrIntersectionContainTypeParameters(type) { + if (type.couldContainTypeParameters === undefined) { + type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + } + return type.couldContainTypeParameters; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 1572864 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypes(context, originalSource, originalTarget) { + var typeParameters = context.signature.typeParameters; var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; - inferFromTypes(source, target); + var visited = ts.createMap(); + inferFromTypes(originalSource, originalTarget); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { if (source === sourceStack[i] && target === targetStack[i]) { @@ -19662,26 +24677,41 @@ var ts; return false; } function inferFromTypes(source, target) { - if (source.flags & 16384 && target.flags & 16384 || - source.flags & 32768 && target.flags & 32768) { + if (!couldContainTypeParameters(target)) { + return; + } + if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || + source.flags & 1048576 && target.flags & 1048576) { + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } var matchingTypes = void 0; - for (var _i = 0, _a = target.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (typeIdenticalToSomeType(t, source.types)) { + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } + else if (t.flags & (64 | 32)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } } if (matchingTypes) { source = removeTypesFromUnionOrIntersection(source, matchingTypes); target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 512) { - if (source.flags & 8388608) { + if (target.flags & 16384) { + if (source.flags & 134217728) { return; } - var typeParameters = context.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { var inferences = context.inferences[i]; @@ -19692,12 +24722,15 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } + if (!isTypeParameterAtTopLevel(originalTarget, target)) { + inferences.topLevel = false; + } } return; } } } - else if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { + else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -19705,20 +24738,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { - var sourceTypes = source.elementTypes; - var targetTypes = target.elementTypes; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 49152) { + else if (target.flags & 1572864) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; - for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { - var t = targetTypes_2[_b]; - if (t.flags & 512 && ts.contains(context.typeParameters, t)) { + for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { + var t = targetTypes_2[_d]; + if (t.flags & 16384 && ts.contains(typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -19732,18 +24758,16 @@ var ts; inferiority--; } } - else if (source.flags & 49152) { + else if (source.flags & 1572864) { var sourceTypes = source.types; - for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { - var sourceType = sourceTypes_3[_c]; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || - target.flags & 8192 || - target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (source.flags & 2588672) { if (isInProcess(source, target)) { return; } @@ -19751,7 +24775,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -19772,8 +24796,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -19790,8 +24814,11 @@ var ts; inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } + function inferFromParameterTypes(source, target) { + return inferFromTypes(source, target); + } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromParameterTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -19820,8 +24847,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -19836,19 +24863,28 @@ var ts; reducedTypes.push(t); } } - return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); + return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190); + } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; var inferenceSucceeded; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var signature = context.signature; + var widenLiteralTypes = context.inferences[index].topLevel && + !hasPrimitiveConstraint(signature.typeParameters[index]) && + (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); + var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -19858,7 +24894,7 @@ var ts; } context.inferredTypes[index] = inferredType; if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -19914,10 +24950,6 @@ var ts; } return undefined; } - function isNullOrUndefinedLiteral(node) { - return node.kind === 93 || - node.kind === 69 && getResolvedSymbol(node) === undefinedSymbol; - } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69: @@ -19929,16 +24961,17 @@ var ts; return undefined; } function isMatchingReference(source, target) { - if (source.kind === target.kind) { - switch (source.kind) { - case 69: - return getResolvedSymbol(source) === getResolvedSymbol(target); - case 97: - return true; - case 172: - return source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } + switch (source.kind) { + case 69: + return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 218 || target.kind === 169) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 97: + return target.kind === 97; + case 172: + return target.kind === 172 && + source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); } return false; } @@ -19951,6 +24984,40 @@ var ts; } return false; } + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 172 && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 69) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 172) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.text); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 524288) { + var prop = getPropertyOfType(type, name); + if (!prop) { + var filteredType = getTypeWithFacts(type, 4194304); + if (filteredType !== type && filteredType.flags & 524288) { + prop = getPropertyOfType(filteredType, name); + } + } + if (prop && prop.flags & 268435456) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !prop.hasCommonType && + isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -19977,7 +25044,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 16384)) { + if (!(source.flags & 524288)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -19989,70 +25056,82 @@ var ts; return false; } function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType && declaredType.flags & 16384) { - var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedTypes.length) { - return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); + if (declaredType !== assignedType) { + if (assignedType.flags & 8192) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192)) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); + } function getTypeFacts(type) { var flags = type.flags; - if (flags & 258) { + if (flags & 2) { return strictNullChecks ? 4079361 : 4194049; } - if (flags & 132) { + if (flags & 32) { + return strictNullChecks ? + type.text === "" ? 3030785 : 1982209 : + type.text === "" ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } + if (flags & (64 | 256)) { + var isZero = type.text === "0"; + return strictNullChecks ? + isZero ? 3030658 : 1982082 : + isZero ? 3145346 : 4193922; + } if (flags & 8) { return strictNullChecks ? 4078980 : 4193668; } - if (flags & 80896) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? - strictNullChecks ? 1970144 : 4181984 : - strictNullChecks ? 1972176 : 4184016; + if (flags & 136) { + return strictNullChecks ? + type === falseType ? 3030404 : 1981828 : + type === falseType ? 3145092 : 4193668; } - if (flags & (16 | 32)) { + if (flags & 2588672) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 : 8376288 : + strictNullChecks ? 6166480 : 8378320; + } + if (flags & (1024 | 2048)) { return 2457472; } - if (flags & 64) { + if (flags & 4096) { return 2340752; } - if (flags & 16777216) { + if (flags & 512) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 512) { + if (flags & 16384) { var constraint = getConstraintOfTypeParameter(type); - return constraint ? getTypeFacts(constraint) : 4194303; + return getTypeFacts(constraint || emptyObjectType); } - if (flags & 32768) { - return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0); + if (flags & 1572864) { + return getTypeFactsOfTypes(type.types); } - return 4194303; + return 8388607; } function getTypeWithFacts(type, include) { - if (!(type.flags & 16384)) { - return getTypeFacts(type) & include ? type : neverType; - } - var firstType; - var types; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (getTypeFacts(t) & include) { - if (!firstType) { - firstType = t; - } - else { - if (!types) { - types = [firstType]; - } - types.push(t); - } - } - } - return firstType ? types ? getUnionType(types, true) : firstType : neverType; + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -20146,53 +25225,88 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getReferenceFromExpression(node) { + function getInitialOrAssignedType(node) { + return node.kind === 218 || node.kind === 169 ? + getInitialType(node) : + getAssignedType(node); + } + function getReferenceCandidate(node) { switch (node.kind) { case 178: - return getReferenceFromExpression(node.expression); + return getReferenceCandidate(node.expression); case 187: switch (node.operatorToken.kind) { case 56: - return getReferenceFromExpression(node.left); + return getReferenceCandidate(node.left); case 24: - return getReferenceFromExpression(node.right); + return getReferenceCandidate(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249) { - var expr = clause.expression; - return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; } - return undefined; + return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 524288) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 && target.flags & 16 && source.baseType === target) { + return true; + } + return containsType(target.types, source); } function filterType(type, f) { - return type.flags & 16384 ? - getUnionType(ts.filter(type.types, f)) : - f(type) ? type : neverType; + if (type.flags & 524288) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32); + var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; - var result = getTypeAtFlowNode(reference.flowNode); + var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288) === neverType) { + if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288).flags & 8192) { return declaredType; } return result; @@ -20230,7 +25344,7 @@ var ts; } else if (flow.flags & 2) { var container = flow.container; - if (container && includeOuterFunctions) { + if (container && container !== flowContainer && reference.kind !== 172) { flow = container.flowNode; continue; } @@ -20249,16 +25363,10 @@ var ts; } function getTypeAtFlowAssignment(flow) { var node = flow.node; - if ((node.kind === 218 || node.kind === 169) && - reference.kind === 69 && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { - return declaredType.flags & 16384 ? - getAssignmentReducedType(declaredType, getInitialType(node)) : - declaredType; - } if (isMatchingReference(reference, node)) { - return declaredType.flags & 16384 ? - getAssignmentReducedType(declaredType, getAssignedType(node)) : + var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; + return declaredType.flags & 524288 && !isIncrementOrDecrement ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -20267,37 +25375,55 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - if (type !== neverType) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (!(type.flags & 8192)) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { - type = narrowType(declaredType, flow.expression, assumeTrue); + if (type.flags & 8192 && isIncomplete(flowType)) { + type = silentNeverType; } } - return type; + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtSwitchClause(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) { return type; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } } - return getUnionType(antecedentTypes); + return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); if (!key) { key = getFlowCacheKey(reference); } @@ -20306,32 +25432,66 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return getUnionType(flowLoopTypes[i]); + return createFlowType(getUnionType(flowLoopTypes[i]), true); } } var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); if (cache[key]) { return cache[key]; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } if (type === declaredType) { break; } } - return cache[key] = getUnionType(antecedentTypes); + var result = getUnionType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, true); + } + return cache[key] = result; + } + function isMatchingReferenceDiscriminant(expr) { + return expr.kind === 172 && + declaredType.flags & 524288 && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(declaredType, expr.name.text); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152) : type; + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + } + if (isMatchingReferenceDiscriminant(expr)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -20341,26 +25501,29 @@ var ts; case 31: case 32: case 33: - var left = expr.left; - var operator = expr.operatorToken.kind; - var right = expr.right; - if (isNullOrUndefinedLiteral(right)) { - return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 182 && right_1.kind === 9) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (isNullOrUndefinedLiteral(left)) { - return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + if (right_1.kind === 182 && left_1.kind === 9) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (left.kind === 182 && right.kind === 9) { - return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } - if (right.kind === 182 && left.kind === 9) { - return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } - if (left.kind === 172) { - return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + if (isMatchingReferenceDiscriminant(left_1)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (right.kind === 172) { - return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); + if (isMatchingReferenceDiscriminant(right_1)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; } break; case 91: @@ -20370,23 +25533,41 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1) { + return type; + } if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { + var valueType = checkExpression(value); + if (valueType.flags & 6144) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 30 || operator === 31; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + value.kind === 93 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); + } + if (type.flags & 2589191) { return type; } - var doubleEquals = operator === 30 || operator === 31; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - literal.kind === 93 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 ? type : narrowedType; + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceFromExpression(typeOfExpr.expression); + var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (containsMatchingReference(reference, target)) { return declaredType; @@ -20396,76 +25577,40 @@ var ts; if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, literal.text); + if (assumeTrue && !(type.flags & 524288)) { + var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, literal.text) || 64 : - ts.getProperty(typeofNEFacts, literal.text) || 8192; + typeofEQFacts[literal.text] || 64 : + typeofNEFacts[literal.text] || 8192; return getTypeWithFacts(type, facts); } - function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { - if (!isMatchingReference(reference, propAccess.expression)) { - return type; - } - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } - var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); - if (!isStringLiteralUnionType(discriminantType)) { - return type; - } - if (operator === 31 || operator === 33) { - assumeTrue = !assumeTrue; - } - if (assumeTrue) { - return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); - } - if (discriminantType.flags & 256) { - return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); - } - return type; - } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - if (!isMatchingReference(reference, switchStatement.expression.expression)) { - return type; - } - var propName = switchStatement.expression.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); - var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; - var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; - var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); - return caseType ? getUnionType([caseType, defaultType]) : defaultType; + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left); + var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (containsMatchingReference(reference, left)) { return declaredType; } return type; } - if (isTypeAny(type)) { - return type; - } var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; @@ -20478,12 +25623,15 @@ var ts; targetType = prototypePropertyType; } } + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 2048) { + if (rightType.flags & 65536) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 65536) { + else if (rightType.flags & 2097152) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -20497,23 +25645,22 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return type.flags & 16384 ? - getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : - type; + return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); } - if (type.flags & 16384) { - var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); - if (assignableConstituents.length) { - return getUnionType(assignableConstituents); + if (type.flags & 524288) { + var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (!(assignableType.flags & 8192)) { + return assignableType; } } - var targetType = type.flags & 512 ? getApparentType(type) : type; - return isTypeAssignableTo(candidate, targetType) ? candidate : + var targetType = type.flags & 16384 ? getApparentType(type) : type; + return isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : - getIntersectionType([type, candidate]); + isTypeAssignableTo(candidate, targetType) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (type.flags & 1 || !hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -20521,6 +25668,9 @@ var ts; if (!predicate) { return type; } + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -20591,31 +25741,62 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 256 || node.kind === 145) { + if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 226 || + node.kind === 256 || + node.kind === 145) { return node; } } } - function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { - var declarationContainer = getControlFlowContainer(declaration); - var container = getControlFlowContainer(reference); - while (container !== declarationContainer && - (container.kind === 179 || container.kind === 180) && - (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { - container = getControlFlowContainer(container); + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304)) { + links.flags |= 4194304; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + while (true) { + node = node.parent; + if (!node) { + return false; + } + if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304) { + return true; + } + } + } + function markParameterAssignments(node) { + if (node.kind === 69) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); } - return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 180) { - if (languageVersion < 2) { + if (languageVersion < 2) { + if (container.kind === 180) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } + else if (ts.hasModifier(container, 256)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } } - if (node.flags & 33554432) { + if (node.flags & 262144) { getNodeLinks(container).flags |= 8192; } } @@ -20623,34 +25804,56 @@ var ts; markAliasSymbolAsReferenced(symbol); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (languageVersion === 2 - && localOrExportSymbol.flags & 32 - && localOrExportSymbol.valueDeclaration.kind === 221 - && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { - getNodeLinks(container).flags |= 524288; - getNodeLinks(node).flags |= 1048576; - break; + if (localOrExportSymbol.flags & 32) { + var declaration_1 = localOrExportSymbol.valueDeclaration; + if (languageVersion === 2 + && declaration_1.kind === 221 + && ts.nodeIsDecorated(declaration_1)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration_1 && container.name !== node) { + getNodeLinks(declaration_1).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration_1.kind === 192) { + var container = ts.getThisContainer(node, false); + while (container !== undefined) { + if (container.parent === declaration_1) { + if (container.kind === 145 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration_1).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + } + break; + } + container = ts.getThisContainer(container, false); } - container = ts.getContainingClass(container); } } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node)) { + var declaration = localOrExportSymbol.valueDeclaration; + if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { return type; } - var declaration = localOrExportSymbol.valueDeclaration; - var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || !declaration || - ts.getRootDeclaration(declaration).kind === 142 || ts.isInAmbientContext(declaration) || - !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); - if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32) && getCombinedTypeFlags(flowType) & 32) { + var isParameter = ts.getRootDeclaration(declaration).kind === 142; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + while (flowContainer !== declarationContainer && + (flowContainer.kind === 179 || flowContainer.kind === 180) && + (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || + isOuterVariable || ts.isInAmbientContext(declaration); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); + if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -20788,7 +25991,7 @@ var ts; break; case 145: case 144: - if (container.flags & 32) { + if (ts.getModifierFlags(container) & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -20813,10 +26016,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -20824,8 +26023,8 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - var type = container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, true, true); + var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type, true, undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -20886,15 +26085,15 @@ var ts; } return unknownType; } - if ((container.flags & 32) || isCallExpression) { + if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } else { nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 147 && container.flags & 256) { - if (ts.isSuperPropertyOrElementAccess(node.parent) && ts.isAssignmentTarget(node.parent)) { + if (container.kind === 147 && ts.getModifierFlags(container) & 256) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } else { @@ -20938,7 +26137,7 @@ var ts; } else { if (ts.isClassLike(container.parent) || container.parent.kind === 171) { - if (container.flags & 32) { + if (ts.getModifierFlags(container) & 32) { return container.kind === 147 || container.kind === 146 || container.kind === 149 || @@ -20958,11 +26157,11 @@ var ts; return false; } } - function getContextuallyTypedThisType(func) { + function getContextualThisParameter(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return getThisTypeOfSignature(contextualSignature); + return contextualSignature.thisParameter; } } return undefined; @@ -20977,14 +26176,14 @@ var ts; if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getTypeOfExpression(iife.arguments[i])); + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } return createArrayType(getUnionType(restTypes)); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; links.resolvedSignature = anySignature; - var type = checkExpression(iife.arguments[indexOfParameter]); + var type = getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])); links.resolvedSignature = cached; return type; } @@ -21019,15 +26218,15 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true); + return getTypeFromBindingPattern(declaration.name, true, false); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_13 = declaration.propertyName || declaration.name; + var name_17 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_13)) { - var text = getTextOfPropertyName(name_13); + !ts.isBindingPattern(name_17)) { + var text = getTextOfPropertyName(name_17); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -21102,6 +26301,9 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 && operator <= 68) { + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + return undefined; + } if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); } @@ -21121,14 +26323,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 16384)) { + if (!(type.flags & 524288)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -21146,7 +26348,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 130048 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -21154,7 +26356,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -21242,6 +26444,7 @@ var ts; case 187: return getContextualTypeForBinaryOperand(node); case 253: + case 254: return getContextualTypeForObjectLiteralElement(parent); case 170: return getContextualTypeForElementExpression(node); @@ -21288,13 +26491,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 16384)) { + if (!(type.flags & 524288)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -21343,14 +26546,14 @@ var ts; } } else { - var type = checkExpression(e, contextualMapper); + var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 191; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -21362,7 +26565,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.elementTypes[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { if (patternElement.kind !== 193) { @@ -21377,17 +26580,22 @@ var ts; } } } - return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, true) : + strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } function isNumericLiteralName(name) { return (+name).toString() === name; } @@ -21395,7 +26603,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 16777216)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -21411,13 +26619,13 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = {}; + var propertiesTable = ts.createMap(); var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -21441,7 +26649,7 @@ var ts; } else { ts.Debug.assert(memberDecl.kind === 254); - type = checkExpression(memberDecl.name, contextualMapper); + type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); @@ -21455,7 +26663,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -21493,7 +26701,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!ts.hasProperty(propertiesTable, prop.name)) { + if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -21505,8 +26713,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -21560,9 +26768,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var indexerType = getIndexTypeOfType(elementAttributesType, 0); - if (indexerType) { - correspondingPropType = indexerType; + var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); + if (attributeType) { + correspondingPropType = attributeType; } else { if (!correspondingPropType) { @@ -21635,7 +26843,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 16384)); + ts.Debug.assert(!(valueType.flags & 524288)); if (isTypeAny(valueType)) { return anyType; } @@ -21647,11 +26855,11 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature)); + return getUnionType(signatures.map(getReturnTypeOfSignature), true); } function getJsxElementPropertiesName() { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064); var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -21674,16 +26882,16 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 16384) { + if (elemType.flags & 524288) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - })); + }), true); } if (elemType.flags & 2) { return anyType; } - else if (elemType.flags & 256) { + else if (elemType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elemType.text; @@ -21736,7 +26944,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 16384) { + else if (attributesType.flags & 524288) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -21819,7 +27027,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = {}; + var nameTable = ts.createMap(); var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { if (node.attributes[i].kind === 246) { @@ -21837,7 +27045,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912) && - nameTable[targetProperties[i].name] === undefined) { + !nameTable[targetProperties[i].name]) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -21854,11 +27062,14 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 145; } - function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + function getDeclarationModifierFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function checkClassPropertyAccess(node, left, type, prop) { - var flags = getDeclarationFlagsFromSymbol(prop); + var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 172 || node.kind === 218 ? node.name : @@ -21873,7 +27084,7 @@ var ts; return false; } } - if (!(flags & (8 | 16))) { + if (!(flags & 24)) { return true; } if (flags & 8) { @@ -21898,10 +27109,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 33554432) { + if (type.flags & 268435456) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (1024 | 2048) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -21910,9 +27121,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getCombinedTypeFlags(type) & 96; + var kind = getFalsyFlags(type) & 6144; if (kind) { - error(node, kind & 32 ? kind & 64 ? + error(node, kind & 2048 ? kind & 4096 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -21929,23 +27140,23 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); - if (isTypeAny(type)) { + if (isTypeAny(type) || type === silentNeverType) { return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 512 && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); + reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); } return unknownType; } if (noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && (prop.valueDeclaration.flags & 8)) { + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { if (prop.flags & 16777216) { getSymbolLinks(prop).target.isReferenced = true; } @@ -21960,10 +27171,24 @@ var ts; var propType = getTypeOfSymbol(prop); if (node.kind !== 172 || ts.isAssignmentTarget(node) || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 16384)) { + !(prop.flags & 8192 && propType.flags & 524288)) { return propType; } - return getFlowTypeOfReference(node, propType, true, false); + return getFlowTypeOfReference(node, propType, true, undefined); + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 524288 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -22031,8 +27256,8 @@ var ts; } var objectType = getApparentType(checkNonNullExpression(node.expression)); var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; - if (objectType === unknownType) { - return unknownType; + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; } var isConstEnum = isConstEnumObjectType(objectType); if (isConstEnum && @@ -22041,21 +27266,22 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_14 !== undefined) { - var prop = getPropertyOfType(objectType, name_14); + var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_18 !== undefined) { + var prop = getPropertyOfType(objectType, name_18); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol)); return unknownType; } } } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + var allowedNullableFlags = strictNullChecks ? 0 : 6144; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -22100,7 +27326,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 16777216) === 0) { + if ((expressionType.flags & 512) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -22149,22 +27375,22 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_9 = signature.declaration && signature.declaration.parent; + var parent_10 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_9 === lastParent) { + if (lastParent && parent_10 === lastParent) { index++; } else { - lastParent = parent_9; + lastParent = parent_10; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_9; + lastParent = parent_10; } lastSymbol = symbol; - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -22238,7 +27464,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 80896) { + if (type.flags & 2588672) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -22248,7 +27474,7 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature.typeParameters, true); + var context = createInferenceContext(signature, true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { inferTypes(context, instantiateType(source, contextualMapper), target); }); @@ -22338,9 +27564,7 @@ var ts; var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { - argType = arg.kind === 9 && !reportErrors - ? getStringLiteralTypeForText(arg.text) - : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { @@ -22444,10 +27668,10 @@ var ts; case 69: case 8: case 9: - return getStringLiteralTypeForText(element.name.text); + return getLiteralTypeForText(32, element.name.text); case 140: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 16777216)) { + if (isTypeOfKind(nameType, 512)) { return nameType; } else { @@ -22573,7 +27797,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -22594,7 +27818,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); } return candidate; } @@ -22619,14 +27843,14 @@ var ts; var candidate = void 0; var typeArgumentsAreValid = void 0; var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate.typeParameters, false) + ? createInferenceContext(originalCandidate, false) : undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -22681,15 +27905,16 @@ var ts; return resolveUntypedCall(node); } var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } var apparentType = getApparentType(funcType); if (apparentType === unknownType) { return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isTypeAny(funcType) || - (isTypeAny(apparentType) && funcType.flags & 512) || - (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -22700,12 +27925,27 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); } return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + if (funcType.flags & 524288) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -22714,12 +27954,15 @@ var ts; } } var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } expressionType = getApparentType(expressionType); if (expressionType === unknownType) { return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 128) { + if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -22755,17 +27998,29 @@ var ts; return true; } var declaration = signature.declaration; - var flags = declaration.flags; - if (!(flags & (8 | 16))) { + var modifiers = ts.getModifierFlags(declaration); + if (!(modifiers & 24)) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - if (flags & 8) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } + if (modifiers & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (flags & 16) { + if (modifiers & 16) { error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -22779,11 +28034,12 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -22810,13 +28066,14 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); return resolveErrorCall(node); @@ -22839,21 +28096,21 @@ var ts; function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); var cached = links.resolvedSignature; - if (cached && cached !== anySignature && !candidatesOutArray) { + if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = anySignature; + links.resolvedSignature = resolvingSignature; var result = resolveSignature(node, candidatesOutArray); links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); } return links.inferredClassType; } @@ -22891,7 +28148,7 @@ var ts; return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { @@ -22910,7 +28167,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32); + return includeFalsyTypes(type, 2048); } } return type; @@ -22922,6 +28179,12 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (context.thisParameter) { + if (!signature.thisParameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); + } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -22937,7 +28200,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193) { + if (!ts.isOmittedExpression(element)) { if (element.name.kind === 69) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -23019,17 +28282,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); - if (!type) { - if (funcIsGenerator) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); - return createIterableIteratorType(unknownType); - } - else { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); - } - } + type = getUnionType(types, true); if (funcIsGenerator) { type = createIterableIteratorType(type); } @@ -23037,6 +28290,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } + if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } var widenedType = getWidenedType(type); return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } @@ -23057,27 +28313,21 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - var expr = node.expression; - if (!node.possiblyExhaustive || expr.kind !== 172) { + if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(expr.expression); - if (!(type.flags & 16384)) { - return false; - } - var propName = expr.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { + var type = checkExpression(node.expression); + if (!isLiteralType(type)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(propType, switchTypes); + return eachTypeContainedIn(type, switchTypes); } function functionHasImplicitReturn(func) { - if (!(func.flags & 32768)) { + if (!(func.flags & 128)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); @@ -23098,7 +28348,7 @@ var ts; if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type === neverType) { + if (type.flags & 8192) { hasReturnOfTypeNever = true; } else if (!ts.contains(aggregatedTypes, type)) { @@ -23124,14 +28374,14 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { return; } if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } - var hasExplicitReturn = func.flags & 65536; - if (returnType === neverType) { + var hasExplicitReturn = func.flags & 256; + if (returnType && returnType.flags & 8192) { error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -23226,7 +28476,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { error(operand, diagnostic); return false; } @@ -23234,8 +28484,8 @@ var ts; } function isReadonlySymbol(symbol) { return symbol.isReadonly || - symbol.flags & 4 && (getDeclarationFlagsFromSymbol(symbol) & 64) !== 0 || - symbol.flags & 3 && (getDeclarationFlagsFromSymbol(symbol) & 2048) !== 0 || + symbol.flags & 4 && (getDeclarationModifierFlagsFromSymbol(symbol) & 64) !== 0 || + symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 || symbol.flags & 98304 && !(symbol.flags & 65536) || (symbol.flags & 8) !== 0; } @@ -23308,7 +28558,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 33554432)) { + if (!(node.flags & 262144)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -23320,16 +28570,25 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 36 && node.operand.kind === 8) { + return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); + } switch (node.operator) { case 35: case 36: case 50: - if (maybeTypeOfKind(operandType, 16777216)) { + if (maybeTypeOfKind(operandType, 512)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49: - return booleanType; + var facts = getTypeFacts(operandType) & (1048576 | 2097152); + return facts === 1048576 ? falseType : + facts === 2097152 ? trueType : + booleanType; case 41: case 42: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -23342,6 +28601,9 @@ var ts; } function checkPostfixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); @@ -23352,10 +28614,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 49152) { + if (type.flags & 1572864) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -23367,20 +28629,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 16384) { + if (type.flags & 524288) { var types = type.types; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 32768) { + if (type.flags & 1048576) { var types = type.types; - for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { - var t = types_12[_a]; + for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { + var t = types_16[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -23389,13 +28651,16 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (80896 | 65536) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (isTypeOfKind(leftType, 16777726)) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (isTypeOfKind(leftType, 8190)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -23404,32 +28669,35 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var p = properties_3[_i]; + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var p = properties_4[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); } return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_15 = property.name; - if (name_15.kind === 140) { - checkComputedPropertyName(name_15); + var name_19 = property.name; + if (name_19.kind === 140) { + checkComputedPropertyName(name_19); } - if (isComputedNonLiteralName(name_15)) { + if (isComputedNonLiteralName(name_19)) { return undefined; } - var text = getTextOfPropertyName(name_15); + var text = getTextOfPropertyName(name_19); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -23444,7 +28712,7 @@ var ts; } } else { - error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); + error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); } } else { @@ -23474,8 +28742,9 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { + checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -23505,7 +28774,7 @@ var ts; var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -23534,8 +28803,65 @@ var ts; } return sourceType; } + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 69: + case 9: + case 10: + case 176: + case 189: + case 11: + case 8: + case 99: + case 84: + case 93: + case 135: + case 179: + case 192: + case 180: + case 170: + case 171: + case 182: + case 196: + case 242: + case 241: + return true; + case 188: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 187: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 185: + case 186: + switch (node.operator) { + case 49: + case 35: + case 36: + case 50: + return true; + } + return false; + case 183: + case 177: + case 195: + default: + return false; + } + } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 96) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], true); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -23570,15 +28896,18 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 96) + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (leftType.flags & 6144) leftType = rightType; - if (rightType.flags & 96) + if (rightType.flags & 6144) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; - if ((leftType.flags & 8) && - (rightType.flags & 8) && + if ((leftType.flags & 136) && + (rightType.flags & 136) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -23592,18 +28921,21 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 96) + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (leftType.flags & 6144) leftType = rightType; - if (rightType.flags & 96) + if (rightType.flags & 6144) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { + if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { resultType = numberType; } else { - if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { + if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -23635,6 +28967,12 @@ var ts; case 31: case 32: case 33: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -23644,18 +28982,25 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; + return getTypeFacts(leftType) & 1048576 ? + includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + leftType; case 52: - return getUnionType([getNonNullableType(leftType), rightType]); + return getTypeFacts(leftType) & 2097152 ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; case 56: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); case 24: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : - maybeTypeOfKind(rightType, 16777216) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : + maybeTypeOfKind(rightType, 512) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -23707,7 +29052,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 8388608) || isYieldExpressionInClass(node)) { + if (!(node.flags & 65536) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -23740,14 +29085,22 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getUnionType([type1, type2]); + return getBestChoiceType(type1, type2); } - function checkStringLiteralExpression(node) { - var contextualType = getContextualType(node); - if (contextualType && isStringLiteralUnionType(contextualType)) { - return getStringLiteralTypeForText(node.text); + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); + case 8: + return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); + case 99: + return trueType; + case 84: + return falseType; } - return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -23772,11 +29125,38 @@ var ts; } return links.resolvedType; } + function isTypeAssertion(node) { + node = skipParenthesizedNodes(node); + return node.kind === 177 || node.kind === 195; + } + function checkDeclarationInitializer(declaration) { + var type = checkExpressionCached(declaration.initializer); + return ts.getCombinedNodeFlags(declaration) & 2 || + ts.getCombinedModifierFlags(declaration) & 64 || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 16384) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (apparentType.flags & (2 | 4 | 8 | 16)) { + return true; + } + contextualType = apparentType; + } + return maybeTypeOfKind(contextualType, 480); + } + return false; + } + function checkExpressionForMutableLocation(node, contextualMapper) { + var type = checkExpression(node, contextualMapper); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } function checkPropertyAssignment(node, contextualMapper) { if (node.name.kind === 140) { checkComputedPropertyName(node.name); } - return checkExpression(node.initializer, contextualMapper); + return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); @@ -23820,10 +29200,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -23834,15 +29210,13 @@ var ts; return checkSuperExpression(node); case 93: return nullWideningType; + case 9: + case 8: case 99: case 84: - return booleanType; - case 8: - return checkNumericLiteral(node); + return checkLiteralExpression(node); case 189: return checkTemplateExpression(node); - case 9: - return checkStringLiteralExpression(node); case 11: return stringType; case 10: @@ -23919,7 +29293,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 92) { + if (ts.getModifierFlags(node) & 92) { func = ts.getContainingFunction(node); if (!(func.kind === 148 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -23987,9 +29361,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (ts.isBindingPattern(name_16) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { + var name_20 = _a[_i].name; + if (ts.isBindingPattern(name_20) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -24009,23 +29383,27 @@ var ts; case 156: case 147: case 146: - var parent_10 = node.parent; - if (node === parent_10.type) { - return parent_10; + var parent_11 = node.parent; + if (node === parent_11.type) { + return parent_11; } } } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_17 = _a[_i].name; - if (name_17.kind === 69 && - name_17.text === predicateVariableName) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name_21 = element.name; + if (name_21.kind === 69 && + name_21.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_17.kind === 168 || - name_17.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { + else if (name_21.kind === 168 || + name_21.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { return true; } } @@ -24073,22 +29451,21 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (!node.body) { + if (noUnusedIdentifiers && !node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var getter = 1, setter = 2, property = getter | setter; - var instanceNames = {}; - var staticNames = {}; + var instanceNames = ts.createMap(); + var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, property); + addName(instanceNames, param.name, param.name.text, 3); } } } @@ -24099,21 +29476,21 @@ var ts; if (memberName) { switch (member.kind) { case 149: - addName(names, member.name, memberName, getter); + addName(names, member.name, memberName, 1); break; case 150: - addName(names, member.name, memberName, setter); + addName(names, member.name, memberName, 2); break; case 145: - addName(names, member.name, memberName, property); + addName(names, member.name, memberName, 3); break; } } } } function addName(names, location, name, meaning) { - if (ts.hasProperty(names, name)) { - var prev = names[name]; + var prev = names[name]; + if (prev) { if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -24127,7 +29504,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = {}; + var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144) { @@ -24141,7 +29518,7 @@ var ts; default: continue; } - if (ts.hasProperty(names, memberName)) { + if (names[memberName]) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -24195,7 +29572,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); - if (node.flags & 128 && node.body) { + if (ts.getModifierFlags(node) & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -24240,7 +29617,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 145 && - !(n.flags & 32) && + !(ts.getModifierFlags(n) & 32) && !!n.initializer; } var containingClassDecl = node.parent; @@ -24252,7 +29629,7 @@ var ts; error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & 92; }); + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -24282,13 +29659,8 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); if (node.kind === 149) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { - if (node.flags & 65536) { - if (compilerOptions.noImplicitReturns) { - error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -24300,17 +29672,20 @@ var ts; var otherKind = node.kind === 149 ? 150 : 149; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 28) !== (otherAccessor.flags & 28))) { + if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (((node.flags & 128) !== (otherAccessor.flags & 128))) { + if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - getTypeOfAccessors(getSymbolOfNode(node)); + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 149) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -24342,7 +29717,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -24363,6 +29738,9 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } + if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } } } function checkTypeQuery(node) { @@ -24391,10 +29769,10 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 8) && ts.isInAmbientContext(node); + return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedNodeFlags(n); + var flags = ts.getCombinedModifierFlags(n); if (n.parent.kind !== 222 && n.parent.kind !== 221 && n.parent.kind !== 192 && @@ -24475,9 +29853,9 @@ var ts; var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { var reportError = (node.kind === 147 || node.kind === 146) && - (node.flags & 32) !== (subsequentNode.flags & 32); + (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); if (reportError) { - var diagnostic = node.flags & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -24493,7 +29871,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (node.flags & 128) { + if (ts.getModifierFlags(node) & 128) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -24553,7 +29931,7 @@ var ts; }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -24632,10 +30010,10 @@ var ts; case 224: return 2097152 | 1048576; case 229: - var result_1 = 0; + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); - return result_1; + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; default: return 1048576; } @@ -24658,7 +30036,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 4096) { + if (promise.flags & 131072) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -24684,7 +30062,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -24695,13 +30073,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 16384) { + if (type.flags & 524288) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types); + return getUnionType(types, true); } else { var promisedType = getPromisedType(type); @@ -24723,7 +30101,7 @@ var ts; } } } - function checkCorrectPromiseType(returnType, location) { + function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { if (returnType === unknownType) { return unknownType; } @@ -24732,13 +30110,13 @@ var ts; || globalPromiseType === getTargetType(returnType)) { return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } - error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(location, diagnostic, typeName); return unknownType; } function checkAsyncFunctionReturnType(node) { if (languageVersion >= 2) { var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type); + return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { @@ -24753,12 +30131,11 @@ var ts; var typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - return unknownType; + return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); } checkReturnTypeAnnotationAsExpression(node); var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } var promiseName = ts.getEntityNameFromTypeNode(node.type); @@ -24806,7 +30183,7 @@ var ts; function checkTypeNodeAsExpression(node) { if (node && node.kind === 155) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793056 : 1536; + var meaning = root.parent.kind === 155 ? 793064 : 1920; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -24961,22 +30338,21 @@ var ts; } function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function(key) { - if (ts.hasProperty(node.locals, key)) { - var local_1 = node.locals[key]; - if (!local_1.isReferenced) { - if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142) { - var parameter = local_1.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); - } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); + var _loop_1 = function (key) { + var local = node.locals[key]; + if (!local.isReferenced) { + if (local.valueDeclaration && local.valueDeclaration.kind === 142) { + var parameter = local.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + } } }; for (var key in node.locals) { @@ -24984,6 +30360,9 @@ var ts; } } } + function parameterIsThisKeyword(parameter) { + return parameter.name && parameter.name.originalKeywordKind === 97; + } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -24993,15 +30372,15 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 147 || member.kind === 145) { - if (!member.symbol.isReferenced && member.flags & 8) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } else if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && parameter.flags & 8) { - error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -25012,9 +30391,14 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!typeParameter.symbol.isReferenced) { + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -25024,14 +30408,12 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - if (ts.hasProperty(node.locals, key)) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); - } + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } } @@ -25137,12 +30519,12 @@ var ts; return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152) { + if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 3072) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } if (node.kind === 218 && !node.initializer) { @@ -25154,7 +30536,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219); var container = varDeclList.parent.kind === 200 && varDeclList.parent.parent ? varDeclList.parent.parent @@ -25165,8 +30547,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_18 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); + var name_22 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); } } } @@ -25206,7 +30588,7 @@ var ts; return; } if (current.parent.kind === 145 && - !(current.parent.flags & 32) && + !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)) { return; } @@ -25234,12 +30616,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_11 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_11); - var name_19 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); - if (parent_11.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); + var parent_12 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_12); + var name_23 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); + if (parent_12.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -25302,7 +30684,7 @@ var ts; 128 | 64 | 32; - return (left.flags & interestingFlags) === (right.flags & interestingFlags); + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -25413,7 +30795,7 @@ var ts; if (varExpr.kind === 170 || varExpr.kind === 171) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -25421,7 +30803,7 @@ var ts; } } var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -25474,7 +30856,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 4096) && type.target === getGlobalIterableType()) { + if ((type.flags & 131072) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -25489,7 +30871,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), true), errorNode); } } return typeAsIterable.iterableElementType; @@ -25500,7 +30882,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 4096) && type.target === getGlobalIteratorType()) { + if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -25515,7 +30897,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), true); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -25535,7 +30917,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 4096) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -25544,10 +30926,10 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 16384) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); + if (arrayOrStringType.flags & 524288) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); } - else if (arrayOrStringType.flags & 258) { + else if (arrayOrStringType.flags & 34) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -25557,7 +30939,7 @@ var ts; error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); reportedError = true; } - if (arrayType === neverType) { + if (arrayType.flags & 8192) { return stringType; } } @@ -25572,10 +30954,10 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 258) { + if (arrayElementType.flags & 34) { return stringType; } - return getUnionType([arrayElementType, stringType]); + return getUnionType([arrayElementType, stringType], true); } return arrayElementType; } @@ -25587,7 +30969,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -25600,7 +30982,7 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType === neverType) { + if (strictNullChecks || node.expression || returnType.flags & 8192) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (func.asteriskToken) { return; @@ -25635,7 +31017,7 @@ var ts; } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 33554432) { + if (node.flags & 262144) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -25718,7 +31100,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals && ts.hasProperty(locals, identifierName)) { + if (locals) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -25743,11 +31125,11 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(member.flags & 32) && ts.hasDynamicName(member)) { + if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -25758,7 +31140,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 2048)) { + if (!errorNode && (type.flags & 65536)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -25780,7 +31162,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 2048) { + else if (containingType.flags & 65536) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -25845,7 +31227,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 512)) { + if (!node.name && !(ts.getModifierFlags(node) & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -25888,6 +31270,11 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { + error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); + } + } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { @@ -25901,15 +31288,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { + if (!ts.isEntityNameExpression(typeRefNode.expression)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 4096) ? t.target : t; - if (declaredType.flags & (1024 | 2048)) { + var declaredType = (t.flags & 131072) ? t.target : t; + if (declaredType.flags & (32768 | 65536)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -25928,7 +31315,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && declaration.flags & 8) { + if (declaration && ts.getModifierFlags(declaration) & 8) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); @@ -25951,12 +31338,12 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { if (derivedClassDecl.kind === 192) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -25966,7 +31353,7 @@ var ts; } } else { - var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); if ((baseDeclarationFlags & 8) || (derivedDeclarationFlags & 8)) { continue; } @@ -26033,19 +31420,19 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = {}; + var seen = ts.createMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; - if (!ts.hasProperty(seen, prop.name)) { + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var prop = properties_5[_a]; + var existing = seen[prop.name]; + if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; } else { - var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -26083,7 +31470,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -26091,7 +31478,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - checkUnusedTypeParameters(node); + registerForUnusedIdentifiersCheck(node); } } function checkTypeAliasDeclaration(node) { @@ -26114,7 +31501,7 @@ var ts; } else { var text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text)) { + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -26406,9 +31793,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -26434,9 +31818,9 @@ var ts; break; case 169: case 218: - var name_20 = node.name; - if (ts.isBindingPattern(name_20)) { - for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { + var name_24 = node.name; + if (ts.isBindingPattern(name_24)) { + for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26462,19 +31846,20 @@ var ts; } } function getFirstIdentifier(node) { - while (true) { - if (node.kind === 139) { - node = node.left; - } - else if (node.kind === 172) { - node = node.expression; - } - else { - break; - } + switch (node.kind) { + case 69: + return node; + case 139: + do { + node = node.left; + } while (node.kind !== 69); + return node; + case 172: + do { + node = node.expression; + } while (node.kind !== 69); + return node; } - ts.Debug.assert(node.kind === 69); - return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -26502,8 +31887,8 @@ var ts; var target = resolveAlias(symbol); if (target !== unknownSymbol) { var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793056 ? 793056 : 0) | - (symbol.flags & 1536 ? 1536 : 0); + (symbol.flags & 793064 ? 793064 : 0) | + (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -26522,7 +31907,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -26549,7 +31934,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1) { + if (ts.getModifierFlags(node) & 1) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -26557,11 +31942,11 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 107455) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1536).flags & 1536)) { + if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793056) { + if (target.flags & 793064) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -26577,7 +31962,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -26605,7 +31990,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); } @@ -26623,7 +32008,7 @@ var ts; error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69) { @@ -26667,7 +32052,7 @@ var ts; continue; } var _a = exports[id], declarations = _a.declarations, flags = _a.flags; - if (flags & (1536 | 64 | 384)) { + if (flags & (1920 | 64 | 384)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -26837,9 +32222,10 @@ var ts; } } function checkSourceFile(node) { - var start = new Date().getTime(); + ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); - ts.checkTime += new Date().getTime() - start; + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); } function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -26910,7 +32296,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -26941,7 +32327,7 @@ var ts; case 221: case 222: if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056); + copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; case 179: @@ -26954,7 +32340,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = location.flags; + memberFlags = ts.getModifierFlags(location); location = location.parent; } copySymbols(globals, meaning); @@ -26962,7 +32348,7 @@ var ts; function copySymbol(symbol, meaning) { if (symbol.flags & meaning) { var id = symbol.name; - if (!ts.hasProperty(symbols, id)) { + if (!symbols[id]) { symbols[id] = symbol; } } @@ -27050,15 +32436,13 @@ var ts; default: } } - if (entityName.parent.kind === 235) { - return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); + if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); } - if (entityName.kind !== 172) { - if (isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); - } + if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 229); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -27066,18 +32450,18 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 194) { - meaning = 793056; + meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; } } else { - meaning = 1536; + meaning = 1920; } meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if (ts.isExpression(entityName)) { + else if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; } @@ -27103,7 +32487,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793056 : 1536; + var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 246) { @@ -27155,7 +32539,7 @@ var ts; } } case 95: - var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case 165: return getTypeFromTypeNode(node).symbol; @@ -27195,16 +32579,16 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { return unknownType; } - if (ts.isTypeNode(node)) { + if (ts.isPartOfTypeNode(node)) { return getTypeFromTypeNode(node); } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { return getTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -27263,11 +32647,11 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return checkExpression(expr); + return getRegularTypeOfLiteralType(checkExpression(expr)); } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 32 + return ts.getModifierFlags(node) & 32 ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -27276,7 +32660,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!ts.hasProperty(propsByName, p.name)) { + if (!propsByName[p.name]) { propsByName[p.name] = p; } }); @@ -27286,9 +32670,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_21 = symbol.name; + var name_25 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_21); + var symbol = getPropertyOfType(t, name_25); if (symbol) { symbols_3.push(symbol); } @@ -27308,11 +32692,17 @@ var ts; return [symbol]; } function isArgumentsLocalBinding(node) { - return getReferencedValueSymbol(node) === argumentsSymbol; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + return getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol) { + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -27321,7 +32711,7 @@ var ts; if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455) - : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -27329,34 +32719,48 @@ var ts; return s && !!(s.flags & 107455); } } - function getReferencedExportContainer(node) { - var symbol = getReferencedValueSymbol(node); - if (symbol) { - if (symbol.flags & 1048576) { - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (exportSymbol.flags & 944) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { - if (parentSymbol.valueDeclaration === ts.getSourceFileOfNode(node)) { - return parentSymbol.valueDeclaration; + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944) { + return undefined; } + symbol = exportSymbol; } - for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 225 || n.kind === 224) && getSymbolOfNode(n) === parentSymbol) { - return n; + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { + var symbolFile = parentSymbol.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + for (var n = node.parent; n; n = n.parent) { + if (ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) { + return n; + } } } } } } function getReferencedImportDeclaration(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && symbol.flags & 8388608 ? getDeclarationOfAliasSymbol(symbol) : undefined; + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && symbol.flags & 8388608) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418) { @@ -27384,30 +32788,53 @@ var ts; return false; } function getReferencedDeclarationWithCollidingName(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; } function isDeclarationWithCollidingName(node) { - return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; } function isValueAliasDeclaration(node) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + return true; + } switch (node.kind) { case 229: case 231: case 232: case 234: case 238: - return isAliasResolvedToValue(getSymbolOfNode(node)); + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); case 235: - return node.expression && node.expression.kind === 69 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; + return node.expression + && node.expression.kind === 69 + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -27425,9 +32852,13 @@ var ts; return isConstEnumSymbol(s) || s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + return true; + } if (ts.isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (getSymbolLinks(symbol).referenced) { + if (symbol && getSymbolLinks(symbol).referenced) { return true; } } @@ -27446,7 +32877,8 @@ var ts; return false; } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + node = ts.getParseTreeNode(node); + return node ? getNodeLinks(node).flags : undefined; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -27465,15 +32897,19 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 80896 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; } - function getTypeReferenceSerializationKind(typeName) { - var valueSymbol = resolveEntityName(typeName, 107455, true); + function getTypeReferenceSerializationKind(typeName, location) { + var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); + var globalPromiseSymbol = tryGetGlobalPromiseConstructorSymbol(); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } var constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793056, true); + var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -27484,22 +32920,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16)) { - return ts.TypeReferenceSerializationKind.VoidType; + else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 8)) { + else if (isTypeOfKind(type, 136)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 132)) { + else if (isTypeOfKind(type, 340)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 258)) { + else if (isTypeOfKind(type, 34)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTypeOfKind(type, 8192)) { + else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 16777216)) { + else if (isTypeOfKind(type, 512)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -27515,7 +32951,7 @@ var ts; function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 | 131072)) - ? getTypeOfSymbol(symbol) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -27534,16 +32970,44 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return ts.hasProperty(globals, name); + return !!globals[name]; } - function getReferencedValueSymbol(reference) { - return getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + var parent_13 = reference.parent; + if (ts.isDeclaration(parent_13) && reference === parent_13.name) { + location = getDeclarationContainer(parent_13); + } + } + return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); } function getReferencedValueDeclaration(reference) { - ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getReferencedValueSymbol(reference); - return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 && type.flags & 16777216); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -27551,9 +33015,6 @@ var ts; if (resolvedTypeReferenceDirectives) { fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { - if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { - continue; - } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; @@ -27589,7 +33050,9 @@ var ts; isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { @@ -27597,7 +33060,7 @@ var ts; } var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) ? 107455 | 1048576 - : 793056 | 1536; + : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -27627,9 +33090,9 @@ var ts; } var current = symbol; while (true) { - var parent_12 = getParentOfSymbol(current); - if (parent_12) { - current = parent_12; + var parent_14 = getParentOfSymbol(current); + if (parent_14) { + current = parent_14; } else { break; @@ -27657,11 +33120,15 @@ var ts; return ts.getDeclarationOfKind(moduleSymbol, 256); } function initializeTypeChecker() { - ts.forEach(host.getSourceFiles(), function (file) { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); - }); + } var augmentations; - ts.forEach(host.getSourceFiles(), function (file) { + var requestedExternalEmitHelpers = 0; + var firstFileRequestingExternalHelpers; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -27672,14 +33139,28 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - mergeSymbolTable(globals, file.symbol.globalExports); + var source = file.symbol.globalExports; + for (var id in source) { + if (!(id in globals)) { + globals[id] = source[id]; + } + } } - }); + if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { + var fileRequestedExternalEmitHelpers = file.flags & 31744; + if (fileRequestedExternalEmitHelpers) { + requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; + if (firstFileRequestingExternalHelpers === undefined) { + firstFileRequestingExternalHelpers = file; + } + } + } + } if (augmentations) { - for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { - var list = augmentations_1[_i]; - for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { - var augmentation = list_2[_a]; + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; mergeModuleAugmentation(augmentation); } } @@ -27703,10 +33184,11 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056, undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064, undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); + tryGetGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalSymbol("Promise", 107455, undefined) && getGlobalPromiseConstructorSymbol(); }); getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); getGlobalThenableType = ts.memoize(createThenableType); getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); }); @@ -27723,9 +33205,42 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { + var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); + if (helpersModule) { + var exports = helpersModule.exports; + if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { + verifyHelperSymbol(exports, "__extends", 107455); + } + if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { + verifyHelperSymbol(exports, "__assign", 107455); + } + if (requestedExternalEmitHelpers & 2048) { + verifyHelperSymbol(exports, "__decorate", 107455); + if (compilerOptions.emitDecoratorMetadata) { + verifyHelperSymbol(exports, "__metadata", 107455); + } + } + if (requestedExternalEmitHelpers & 4096) { + verifyHelperSymbol(exports, "__param", 107455); + } + if (requestedExternalEmitHelpers & 8192) { + verifyHelperSymbol(exports, "__awaiter", 107455); + if (languageVersion < 2) { + verifyHelperSymbol(exports, "__generator", 107455); + } + } + } + } + } + function verifyHelperSymbol(symbols, name, meaning) { + var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); + if (!symbol) { + error(undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -27737,7 +33252,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(65536); + var thenableType = createObjectType(2097152); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -27765,49 +33280,9 @@ var ts; return false; } function checkGrammarModifiers(node) { - switch (node.kind) { - case 149: - case 150: - case 148: - case 145: - case 144: - case 147: - case 146: - case 153: - case 225: - case 230: - case 229: - case 236: - case 235: - case 179: - case 180: - case 142: - break; - case 220: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && - node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 221: - case 222: - case 200: - case 223: - if (node.modifiers && node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 224: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && - node.parent.kind !== 226 && node.parent.kind !== 256) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - default: - return false; - } - if (!node.modifiers) { - return; + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -27945,7 +33420,7 @@ var ts; node.kind !== 150) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 && node.parent.flags & 128)) { + if (!(node.parent.kind === 221 && ts.getModifierFlags(node.parent) & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -28000,10 +33475,57 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function checkGrammarAsyncModifier(node, asyncModifier) { - if (languageVersion < 2) { - return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 149: + case 150: + case 148: + case 145: + case 144: + case 147: + case 146: + case 153: + case 225: + case 230: + case 229: + case 236: + case 235: + case 179: + case 180: + case 142: + return false; + default: + if (node.parent.kind === 226 || node.parent.kind === 256) { + return false; + } + switch (node.kind) { + case 220: + return nodeHasAnyModifiersExcept(node, 118); + case 221: + return nodeHasAnyModifiersExcept(node, 115); + case 222: + case 200: + case 223: + return true; + case 224: + return nodeHasAnyModifiersExcept(node, 74); + default: + ts.Debug.fail(); + return false; + } } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { case 147: case 220: @@ -28093,7 +33615,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1023) { + if (ts.getModifierFlags(parameter) !== 0) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -28130,8 +33652,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { - var arg = args_1[_i]; + for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { + var arg = args_2[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -28232,30 +33754,34 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; - var _loop_2 = function(prop) { - var name_22 = prop.name; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var name_26 = prop.name; if (prop.kind === 193 || - name_22.kind === 140) { - checkGrammarComputedPropertyName(name_22); + name_26.kind === 140) { + checkGrammarComputedPropertyName(name_26); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { - return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } - ts.forEach(prop.modifiers, function (mod) { - if (mod.kind !== 118 || prop.kind !== 147) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 118 || prop.kind !== 147) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } } - }); + } var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_22.kind === 8) { - checkGrammarNumericLiteral(name_22); + if (name_26.kind === 8) { + checkGrammarNumericLiteral(name_26); } currentKind = Property; } @@ -28271,51 +33797,46 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); if (effectiveName === undefined) { - return "continue"; + continue; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); + grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } - }; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var state_3 = _loop_2(prop); - if (typeof state_3 === "object") return state_3.value; } } function checkGrammarJsxElement(node) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247) { continue; } var jsxAttr = attr; - var name_23 = jsxAttr.name; - if (!ts.hasProperty(seen, name_23.text)) { - seen[name_23.text] = true; + var name_27 = jsxAttr.name; + if (!seen[name_27.text]) { + seen[name_27.text] = true; } else { - return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28365,7 +33886,7 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(accessor.flags & 128)) { + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { @@ -28502,10 +34023,26 @@ var ts; } } } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 || expr.kind === 8 || + expr.kind === 185 && expr.operator === 36 && + expr.operand.kind === 8; + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 207 && node.parent.parent.kind !== 208) { if (ts.isInAmbientContext(node)) { if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { var equalsTokenLength = "=".length; return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } @@ -28532,7 +34069,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 193) { + if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -28578,8 +34115,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); return true; } } @@ -28639,8 +34176,8 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || - (node.flags & 2) || - (node.flags & (1 | 512))) { + node.kind === 228 || + ts.getModifierFlags(node) & (2 | 1 | 512)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -28685,278 +34222,7977 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); return true; } } - var _a; + function getAmbientModules() { + var result = []; + for (var sym in globals) { + if (ambientModuleSymbolRegex.test(sym)) { + result.push(globals[sym]); + } + } + return result; + } } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; (function (ts) { - var nullSourceMapWriter; - var defaultLastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitStart: function (range) { }, - emitEnd: function (range, stopOverridingSpan) { }, - emitPos: function (pos) { }, - changeEmitSourcePos: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; }, - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { } - }; - } - return nullSourceMapWriter; + ; + var nodeEdgeTraversalMap = ts.createMap((_a = {}, + _a[139] = [ + { name: "left", test: ts.isEntityName }, + { name: "right", test: ts.isIdentifier } + ], + _a[143] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[177] = [ + { name: "type", test: ts.isTypeNode }, + { name: "expression", test: ts.isUnaryExpression } + ], + _a[195] = [ + { name: "expression", test: ts.isExpression }, + { name: "type", test: ts.isTypeNode } + ], + _a[196] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[224] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[225] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[226] = [ + { name: "statements", test: ts.isStatement } + ], + _a[229] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "moduleReference", test: ts.isModuleReference } + ], + _a[240] = [ + { name: "expression", test: ts.isExpression, optional: true } + ], + _a[255] = [ + { name: "name", test: ts.isPropertyName }, + { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } + ], + _a)); + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; } - ts.getNullSourceMapWriter = getNullSourceMapWriter; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - var currentSourceFile; - var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; - var sourceMapSourceIndex; - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan; - var lastEncodedNameIndex; - var sourceMapData; - return { - getSourceMapData: function () { return sourceMapData; }, - setSourceFile: setSourceFile, - emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - changeEmitSourcePos: changeEmitSourcePos, - getText: getText, - getSourceMappingURL: getSourceMappingURL, - initialize: initialize, - reset: reset - }; - function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { - if (sourceMapData) { - reset(); - } - currentSourceFile = undefined; - sourceMapSourceIndex = -1; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; - lastEncodedNameIndex = 0; - sourceMapData = { - sourceMapFilePath: sourceMapFilePath, - jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, - sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (!isBundledEmit) { - ts.Debug.assert(sourceFiles.length === 1); - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); - } + function reduceEachChild(node, f, initial) { + if (node === undefined) { + return initial; } - function reset() { - currentSourceFile = undefined; - sourceMapDir = undefined; - sourceMapSourceIndex = undefined; - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = undefined; - lastEncodedNameIndex = undefined; - sourceMapData = undefined; + var kind = node.kind; + if ((kind > 0 && kind <= 138)) { + return initial; } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; + if ((kind >= 154 && kind <= 166)) { + return initial; + } + var result = initial; + switch (node.kind) { + case 198: + case 201: + case 193: + case 217: + case 287: + break; + case 140: + result = reduceNode(node.expression, f, result); + break; + case 142: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 143: + result = reduceNode(node.expression, f, result); + break; + case 145: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 147: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 148: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 149: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 150: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 167: + case 168: + result = ts.reduceLeft(node.elements, f, result); + break; + case 169: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 170: + result = ts.reduceLeft(node.elements, f, result); + break; + case 171: + result = ts.reduceLeft(node.properties, f, result); + break; + case 172: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.name, f, result); + break; + case 173: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.argumentExpression, f, result); + break; + case 174: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 175: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 176: + result = reduceNode(node.tag, f, result); + result = reduceNode(node.template, f, result); + break; + case 179: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 180: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 178: + case 181: + case 182: + case 183: + case 184: + case 190: + case 191: + case 196: + result = reduceNode(node.expression, f, result); + break; + case 185: + case 186: + result = reduceNode(node.operand, f, result); + break; + case 187: + result = reduceNode(node.left, f, result); + result = reduceNode(node.right, f, result); + break; + case 188: + result = reduceNode(node.condition, f, result); + result = reduceNode(node.whenTrue, f, result); + result = reduceNode(node.whenFalse, f, result); + break; + case 189: + result = reduceNode(node.head, f, result); + result = ts.reduceLeft(node.templateSpans, f, result); + break; + case 192: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 194: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + break; + case 197: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.literal, f, result); + break; + case 199: + result = ts.reduceLeft(node.statements, f, result); + break; + case 200: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.declarationList, f, result); + break; + case 202: + result = reduceNode(node.expression, f, result); + break; + case 203: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.thenStatement, f, result); + result = reduceNode(node.elseStatement, f, result); + break; + case 204: + result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, f, result); + break; + case 205: + case 212: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 206: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.condition, f, result); + result = reduceNode(node.incrementor, f, result); + result = reduceNode(node.statement, f, result); + break; + case 207: + case 208: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 211: + case 215: + result = reduceNode(node.expression, f, result); + break; + case 213: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.caseBlock, f, result); + break; + case 214: + result = reduceNode(node.label, f, result); + result = reduceNode(node.statement, f, result); + break; + case 216: + result = reduceNode(node.tryBlock, f, result); + result = reduceNode(node.catchClause, f, result); + result = reduceNode(node.finallyBlock, f, result); + break; + case 218: + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 219: + result = ts.reduceLeft(node.declarations, f, result); + break; + case 220: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 221: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 227: + result = ts.reduceLeft(node.clauses, f, result); + break; + case 230: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.importClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 231: + result = reduceNode(node.name, f, result); + result = reduceNode(node.namedBindings, f, result); + break; + case 232: + result = reduceNode(node.name, f, result); + break; + case 233: + case 237: + result = ts.reduceLeft(node.elements, f, result); + break; + case 234: + case 238: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + break; + case 235: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.expression, f, result); + break; + case 236: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.exportClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 241: + result = reduceNode(node.openingElement, f, result); + result = ts.reduceLeft(node.children, f, result); + result = reduceNode(node.closingElement, f, result); + break; + case 242: + case 243: + result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.attributes, f, result); + break; + case 245: + result = reduceNode(node.tagName, f, result); + break; + case 246: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 247: + result = reduceNode(node.expression, f, result); + break; + case 248: + result = reduceNode(node.expression, f, result); + break; + case 249: + result = reduceNode(node.expression, f, result); + case 250: + result = ts.reduceLeft(node.statements, f, result); + break; + case 251: + result = ts.reduceLeft(node.types, f, result); + break; + case 252: + result = reduceNode(node.variableDeclaration, f, result); + result = reduceNode(node.block, f, result); + break; + case 253: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 254: + result = reduceNode(node.name, f, result); + result = reduceNode(node.objectAssignmentInitializer, f, result); + break; + case 256: + result = ts.reduceLeft(node.statements, f, result); + break; + case 288: + result = reduceNode(node.expression, f, result); + break; + default: + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_1 = edgeTraversalPath; _i < edgeTraversalPath_1.length; _i++) { + var edge = edgeTraversalPath_1[_i]; + var value = node[edge.name]; + if (value !== undefined) { + result = ts.isArray(value) + ? ts.reduceLeft(value, f, result) + : f(result, value); + } } } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } - } - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - } - function emitPos(pos) { - if (pos === -1) { - return; - } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - sourceIndex: sourceMapSourceIndex - }; - stopOverridingSpan = false; - } - else if (!stopOverridingSpan) { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - updateLastEncodedAndRecordedSpans(); - } - function getStartPos(range) { - var rangeHasDecorators = !!range.decorators; - return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; - } - function emitStart(range) { - emitPos(getStartPos(range)); - } - function emitEnd(range, stopOverridingEnd) { - emitPos(range.end); - stopOverridingSpan = stopOverridingEnd; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; - } - function setSourceFile(sourceFile) { - currentSourceFile = sourceFile; - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); - if (sourceMapSourceIndex === -1) { - sourceMapSourceIndex = sourceMapData.sourceMapSources.length; - sourceMapData.sourceMapSources.push(source); - sourceMapData.inputSourceFileNames.push(sourceFile.fileName); - if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(sourceFile.text); - } - } - } - function getText() { - encodeLastRecordedSourceMapSpan(); - return ts.stringify({ - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent - }); - } - function getSourceMappingURL() { - if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(getText()); - return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; - } - else { - return sourceMapData.jsSourceMappingURL; - } + break; } + return result; } - ts.createSourceMapWriter = createSourceMapWriter; - var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - function base64FormatEncode(inValue) { - if (inValue < 64) { - return base64Chars.charAt(inValue); + ts.reduceEachChild = reduceEachChild; + function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { + if (node === undefined) { + return undefined; } - throw TypeError(inValue + ": not a 64 based value"); - } - function base64VLQFormatEncode(inValue) { - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + if (!optional) { + Debug.failNotOptional(); + } + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); } else { - inValue = inValue << 1; + visitedNode = visited; } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; + if (parenthesize !== undefined) { + visitedNode = parenthesize(visitedNode, parentNode); + } + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + return visitedNode; } + ts.visitNode = visitNode; + function visitNodes(nodes, visitor, test, start, count, parenthesize, parentNode) { + if (nodes === undefined) { + return undefined; + } + var updated; + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + updated = ts.createNodeArray([], undefined, nodes.hasTrailingComma && start + count === length); + } + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + updated = ts.createNodeArray(nodes.slice(0, i), nodes, nodes.hasTrailingComma); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + visitedNode = parenthesize + ? parenthesize(visitedNode, parentNode) + : visitedNode; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + var visitedNode = parenthesize + ? parenthesize(visited, parentNode) + : visited; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + function visitEachChild(node, visitor, context) { + if (node === undefined) { + return undefined; + } + var kind = node.kind; + if ((kind > 0 && kind <= 138)) { + return node; + } + if ((kind >= 154 && kind <= 166)) { + return node; + } + switch (node.kind) { + case 198: + case 201: + case 193: + case 217: + return node; + case 140: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + case 142: + return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 145: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 147: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 148: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 149: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 150: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 167: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 168: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 169: + return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 170: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 171: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 172: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 173: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 174: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 175: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 176: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + case 178: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 179: + return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 180: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, true), context.endLexicalEnvironment())); + case 181: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 182: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 183: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 185: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 186: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 188: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 189: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 190: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 191: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 194: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 197: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + case 199: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 200: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 202: + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 203: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); + case 204: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 205: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 206: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 207: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 208: + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 209: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + case 210: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + case 211: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + case 212: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 213: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 214: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 215: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 216: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + case 218: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 219: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 220: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + case 221: + return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 227: + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 230: + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 231: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); + case 232: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 233: + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 234: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 235: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 236: + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); + case 237: + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + case 238: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 241: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 242: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 243: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 245: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 246: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 247: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 248: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 249: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + case 250: + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 251: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 252: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + case 253: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 254: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 256: + context.startLexicalEnvironment(); + return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); + case 288: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + default: + var updated = void 0; + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_2 = edgeTraversalPath; _i < edgeTraversalPath_2.length; _i++) { + var edge = edgeTraversalPath_2[_i]; + var value = node[edge.name]; + if (value !== undefined) { + var visited = ts.isArray(value) + ? visitNodes(value, visitor, edge.test, 0, value.length, edge.parenthesize, node) + : visitNode(value, visitor, edge.test, edge.optional, edge.lift, edge.parenthesize, node); + if (updated !== undefined || visited !== value) { + if (updated === undefined) { + updated = ts.getMutableClone(node); + } + if (visited !== value) { + updated[edge.name] = visited; + } + } + } + } + } + return updated ? ts.updateNode(updated, node) : node; + } + } + ts.visitEachChild = visitEachChild; + function mergeFunctionBodyLexicalEnvironment(body, declarations) { + if (body && declarations !== undefined && declarations.length > 0) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.createNodeArray(ts.concatenate(body.statements, declarations), body.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([ts.createReturn(body, body)].concat(declarations), body), body, true); + } + } + return body; + } + ts.mergeFunctionBodyLexicalEnvironment = mergeFunctionBodyLexicalEnvironment; + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + function extractSingleNode(nodes) { + Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0; + } + else if (node.transformFlags & 536870912) { + return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + } + function aggregateTransformFlagsForSubtree(node) { + if (ts.hasModifier(node, 2) || ts.isTypeNode(node)) { + return 0; + } + return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0); + } + function aggregateTransformFlagsForChildNode(transformFlags, child) { + return transformFlags | aggregateTransformFlagsForNode(child); + } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 154 && kind <= 166) { + return -3; + } + switch (kind) { + case 174: + case 175: + case 170: + return 537133909; + case 225: + return 546335573; + case 142: + return 538968917; + case 180: + return 550710101; + case 179: + case 220: + return 550726485; + case 219: + return 538968917; + case 221: + case 192: + return 537590613; + case 148: + return 550593365; + case 147: + case 149: + case 150: + return 550593365; + case 117: + case 130: + case 127: + case 132: + case 120: + case 133: + case 103: + case 141: + case 144: + case 146: + case 151: + case 152: + case 153: + case 222: + case 223: + return -3; + case 171: + return 537430869; + default: + return 536871765; + } + } + var Debug; + (function (Debug) { + Debug.failNotOptional = Debug.shouldAssert(1) + ? function (message) { return Debug.assert(false, message || "Node not optional."); } + : function (message) { }; + Debug.failBadSyntaxKind = Debug.shouldAssert(1) + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + : function (node, message) { }; + Debug.assertNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : function (node, test, message) { }; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + })(Debug = ts.Debug || (ts.Debug = {})); + var _a; +})(ts || (ts = {})); +var ts; +(function (ts) { + function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { + if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + var right = node.right; + if (ts.isDestructuringAssignment(right)) { + return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); + } + else { + return node.right; + } + } + var location = node; + var value = node.right; + var expressions = []; + if (needsValue) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment, visitor); + } + else if (ts.nodeIsSynthesized(node)) { + location = value; + } + flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); + if (needsValue) { + expressions.push(value); + } + var expression = ts.inlineExpressions(expressions); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location) { + var expression = ts.createAssignment(name, value, location); + context.setNodeEmitFlags(expression, 2048); + ts.aggregateTransformFlags(expression); + expressions.push(expression); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function flattenParameterDestructuring(context, node, value, visitor) { + var declarations = []; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location) { + var declaration = ts.createVariableDeclaration(name, undefined, value, location); + context.setNodeEmitFlags(declaration, 2048); + ts.aggregateTransformFlags(declaration); + declarations.push(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(undefined); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenParameterDestructuring = flattenParameterDestructuring; + function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { + var declarations = []; + var pendingAssignments; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location, original) { + if (pendingAssignments) { + pendingAssignments.push(value); + value = ts.inlineExpressions(pendingAssignments); + pendingAssignments = undefined; + } + var declaration = ts.createVariableDeclaration(name, undefined, value, location); + declaration.original = original; + context.setNodeEmitFlags(declaration, 2048); + declarations.push(declaration); + ts.aggregateTransformFlags(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + if (recordTempVariable) { + var assignment = ts.createAssignment(name, value, location); + if (pendingAssignments) { + pendingAssignments.push(assignment); + } + else { + pendingAssignments = [assignment]; + } + } + else { + emitAssignment(name, value, location, undefined); + } + return name; + } + } + ts.flattenVariableDestructuring = flattenVariableDestructuring; + function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { + var pendingAssignments = []; + flattenDestructuring(context, node, undefined, node, emitAssignment, emitTempVariableAssignment, visitor); + var expression = ts.inlineExpressions(pendingAssignments); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location, original) { + var left = nameSubstitution && nameSubstitution(name) || name; + emitPendingAssignment(left, value, location, original); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitPendingAssignment(name, value, location, undefined); + return name; + } + function emitPendingAssignment(name, value, location, original) { + var expression = ts.createAssignment(name, value, location); + expression.original = original; + context.setNodeEmitFlags(expression, 2048); + pendingAssignments.push(expression); + return expression; + } + } + ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; + function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { + if (value && visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + if (ts.isBinaryExpression(root)) { + emitDestructuringAssignment(root.left, value, location); + } + else { + emitBindingElement(root, value); + } + function emitDestructuringAssignment(bindingTarget, value, location) { + var target; + if (ts.isShorthandPropertyAssignment(bindingTarget)) { + var initializer = visitor + ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) + : bindingTarget.objectAssignmentInitializer; + if (initializer) { + value = createDefaultValueCheck(value, initializer, location); + } + target = bindingTarget.name; + } + else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56) { + var initializer = visitor + ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) + : bindingTarget.right; + value = createDefaultValueCheck(value, initializer, location); + target = bindingTarget.left; + } + else { + target = bindingTarget; + } + if (target.kind === 171) { + emitObjectLiteralAssignment(target, value, location); + } + else if (target.kind === 170) { + emitArrayLiteralAssignment(target, value, location); + } + else { + var name_28 = ts.getMutableClone(target); + context.setSourceMapRange(name_28, target); + context.setCommentRange(name_28, target); + emitAssignment(name_28, value, location, undefined); + } + } + function emitObjectLiteralAssignment(target, value, location) { + var properties = target.properties; + if (properties.length !== 1) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + if (p.kind === 253 || p.kind === 254) { + var propName = p.name; + var target_1 = p.kind === 254 ? p : p.initializer || propName; + emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); + } + } + } + function emitArrayLiteralAssignment(target, value, location) { + var elements = target.elements; + var numElements = elements.length; + if (numElements !== 1) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var e = elements[i]; + if (e.kind !== 193) { + if (e.kind !== 191) { + emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); + } + else if (i === numElements - 1) { + emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); + } + } + } + } + function emitBindingElement(target, value) { + var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + if (initializer) { + value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + } + else if (!value) { + value = ts.createVoidZero(); + } + var name = target.name; + if (ts.isBindingPattern(name)) { + var elements = name.elements; + var numElements = elements.length; + if (numElements !== 1) { + value = ensureIdentifier(value, numElements !== 0, target, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (ts.isOmittedExpression(element)) { + continue; + } + else if (name.kind === 167) { + var propName = element.propertyName || element.name; + emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); + } + else { + if (!element.dotDotDotToken) { + emitBindingElement(element, ts.createElementAccess(value, i)); + } + else if (i === numElements - 1) { + emitBindingElement(element, ts.createArraySlice(value, i)); + } + } + } + } + else { + emitAssignment(name, value, target, target); + } + } + function createDefaultValueCheck(value, defaultValue, location) { + value = ensureIdentifier(value, true, location, emitTempVariableAssignment); + return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53), defaultValue, ts.createToken(54), value); + } + function createDestructuringPropertyAccess(expression, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, false, propertyName, emitTempVariableAssignment)); + } + else if (ts.isLiteralExpression(propertyName)) { + var clone_2 = ts.getSynthesizedClone(propertyName); + clone_2.text = ts.unescapeIdentifier(clone_2.text); + return ts.createElementAccess(expression, clone_2); + } + else { + if (ts.isGeneratedIdentifier(propertyName)) { + var clone_3 = ts.getSynthesizedClone(propertyName); + clone_3.text = ts.unescapeIdentifier(clone_3.text); + return ts.createPropertyAccess(expression, clone_3); + } + else { + return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + } + } + } + } + function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + if (visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + return emitTempVariableAssignment(value, location); + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var USE_NEW_TYPE_METADATA_FORMAT = false; + function transformTypeScript(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentScope; + var currentSourceFileExternalHelpersModuleName; + var enabledSubstitutions; + var classAliases; + var applicableSubstitutions; + var currentSuperContainer; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function saveStateAndInvoke(node, f) { + var savedCurrentScope = currentScope; + onBeforeVisitNode(node); + var visited = f(node); + currentScope = savedCurrentScope; + return visited; + } + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + function visitorWorker(node) { + if (node.kind === 256) { + return visitSourceFile(node); + } + else if (node.transformFlags & 1) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + function namespaceElementVisitorWorker(node) { + if (node.kind === 236 || + node.kind === 230 || + node.kind === 231 || + (node.kind === 229 && + node.moduleReference.kind === 240)) { + return undefined; + } + else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { + return visitTypeScript(node); + } + else if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + function classElementVisitorWorker(node) { + switch (node.kind) { + case 148: + return undefined; + case 145: + case 153: + case 149: + case 150: + case 147: + return visitorWorker(node); + case 198: + return node; + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitTypeScript(node) { + if (ts.hasModifier(node, 2) && ts.isStatement(node)) { + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 82: + case 77: + return currentNamespace ? undefined : node; + case 112: + case 110: + case 111: + case 115: + case 118: + case 74: + case 122: + case 128: + case 160: + case 161: + case 159: + case 154: + case 141: + case 117: + case 120: + case 132: + case 130: + case 127: + case 103: + case 133: + case 157: + case 156: + case 158: + case 155: + case 162: + case 163: + case 164: + case 165: + case 166: + case 153: + case 143: + case 223: + case 145: + case 148: + return undefined; + case 222: + return ts.createNotEmittedStatement(node); + case 221: + return visitClassDeclaration(node); + case 192: + return visitClassExpression(node); + case 251: + return visitHeritageClause(node); + case 194: + return visitExpressionWithTypeArguments(node); + case 147: + return visitMethodDeclaration(node); + case 149: + return visitGetAccessor(node); + case 150: + return visitSetAccessor(node); + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + case 180: + return visitArrowFunction(node); + case 142: + return visitParameter(node); + case 178: + return visitParenthesizedExpression(node); + case 177: + case 195: + return visitAssertionExpression(node); + case 196: + return visitNonNullExpression(node); + case 224: + return visitEnumDeclaration(node); + case 184: + return visitAwaitExpression(node); + case 200: + return visitVariableStatement(node); + case 225: + return visitModuleDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 256: + case 227: + case 226: + case 199: + currentScope = node; + break; + } + } + function visitSourceFile(node) { + currentSourceFile = node; + if (node.flags & 31744 + && compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); + var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); + var externalHelpersModuleImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + externalHelpersModuleImport.parent = node; + externalHelpersModuleImport.flags &= ~8; + statements.push(externalHelpersModuleImport); + currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + currentSourceFileExternalHelpersModuleName = undefined; + node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + node.externalHelpersModuleName = externalHelpersModuleName; + } + else { + node = ts.visitEachChild(node, visitor, context); + } + setNodeEmitFlags(node, 1 | node.emitFlags); + return node; + } + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + function visitClassDeclaration(node) { + var staticProperties = getInitializedProperties(node, true); + var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; + var isDecoratedClass = shouldEmitDecorateCallForClass(node); + var classAlias; + var name = node.name; + if (!name && staticProperties.length > 0) { + name = ts.getGeneratedNameForNode(node); + } + var statements = []; + if (!isDecoratedClass) { + var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + ts.setOriginalNode(classDeclaration, node); + if (staticProperties.length > 0) { + setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + } + statements.push(classDeclaration); + } + else { + classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); + } + if (staticProperties.length) { + addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, true)); + } + addClassElementDecorationStatements(statements, node, false); + addClassElementDecorationStatements(statements, node, true); + addConstructorDecorationStatement(statements, node, classAlias); + if (isNamespaceExport(node)) { + addExportMemberAssignment(statements, node); + } + else if (isDecoratedClass) { + if (isDefaultExternalModuleExport(node)) { + statements.push(ts.createExportAssignment(undefined, undefined, false, getLocalName(node))); + } + else if (isNamedExternalModuleExport(node)) { + statements.push(createExternalModuleExport(name)); + } + } + return statements; + } + function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + var location = ts.moveRangePastDecorators(node); + var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), location), node); + if (!name) { + name = ts.getGeneratedNameForNode(node); + } + var classAlias; + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + } + var declaredName = getDeclarationName(node, true); + var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) + ]), location); + setCommentRange(transformedClassExpression, node); + statements.push(ts.setOriginalNode(transformedClassExpression, node)); + if (classAlias) { + statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(declaredName, undefined, classAlias) + ]), location), node)); + } + return classAlias; + } + function visitClassExpression(node) { + var staticProperties = getInitializedProperties(node, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, heritageClauses !== undefined); + var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members, node), node); + if (staticProperties.length > 0) { + var expressions = []; + var temp = ts.createTempVariable(hoistVariableDeclaration); + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + } + setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + return classExpression; + } + function transformClassMembers(node, hasExtendsClause) { + var members = []; + var constructor = transformConstructor(node, hasExtendsClause); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.createNodeArray(members, node.members); + } + function transformConstructor(node, hasExtendsClause) { + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = node.transformFlags & 131072; + var constructor = ts.getFirstConstructorWithBody(node); + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor(undefined, undefined, parameters, body, constructor || node), constructor)); + } + function transformConstructorParameters(constructor) { + return constructor + ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) + : []; + } + function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + var statements = []; + var indexOfFirstStatement = 0; + startLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (hasExtendsClause) { + statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + var properties = getInitializedProperties(node, false); + addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + if (constructor) { + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + ts.addRange(statements, endLexicalEnvironment()); + return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined), true); + } + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + var index = ts.addPrologueDirectives(result, statements, false, visitor); + if (index === statements.length) { + return index; + } + var statement = statements[index]; + if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92) + && ts.isIdentifier(parameter.name); + } + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + setNodeEmitFlags(propertyName, 49152 | 1536); + var localName = ts.getMutableClone(name); + setNodeEmitFlags(localName, 49152); + return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); + } + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, true); + } + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, false); + } + function isInitializedProperty(member, isStatic) { + return member.kind === 145 + && isStatic === ts.hasModifier(member, 32) + && member.initializer !== undefined; + } + function addInitializedPropertyStatements(statements, node, properties, receiver) { + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var property = properties_7[_i]; + var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); + setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + setCommentRange(statement, property); + statements.push(statement); + } + } + function generateInitializedPropertyExpressions(node, properties, receiver) { + var expressions = []; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var expression = transformInitializedProperty(node, property, receiver); + expression.startsOnNewLine = true; + setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + setCommentRange(expression, property); + expressions.push(expression); + } + return expressions; + } + function transformInitializedProperty(node, property, receiver) { + var propertyName = visitPropertyNameOfClassElement(property); + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); + return ts.createAssignment(memberAccess, initializer); + } + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + } + function isStaticDecoratedClassElement(member) { + return isDecoratedClassElement(member, true); + } + function isInstanceDecoratedClassElement(member) { + return isDecoratedClassElement(member, false); + } + function isDecoratedClassElement(member, isStatic) { + return ts.nodeOrChildIsDecorated(member) + && isStatic === ts.hasModifier(member, 32); + } + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 149: + case 150: + return getAllDecoratorsOfAccessors(node, member); + case 147: + return getAllDecoratorsOfMethod(member); + case 145: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + if (accessor !== firstAccessor) { + return undefined; + } + var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + function transformAllDecoratorsOfDeclaration(node, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, decoratorExpressions); + return decoratorExpressions; + } + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, true); + var descriptor = languageVersion > 0 + ? member.kind === 145 + ? ts.createVoidZero() + : ts.createNull() + : undefined; + var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + setNodeEmitFlags(helper, 49152); + return helper; + } + function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { + var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + if (expression) { + statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + } + } + function generateConstructorDecorationExpression(node, decoratedClassAlias) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + if (decoratedClassAlias) { + var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); + var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152); + return result; + } + else { + var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152); + return result; + } + } + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); + setNodeEmitFlags(helper, 49152); + expressions.push(helper); + } + } + return expressions; + } + function addTypeMetadata(node, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, decoratorExpressions); + } + else { + addOldTypeMetadata(node, decoratorExpressions); + } + } + function addOldTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeParameterTypesOfNode(node)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); + } + } + } + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 147 + || kind === 149 + || kind === 150 + || kind === 145; + } + function shouldAddReturnTypeMetadata(node) { + return node.kind === 147; + } + function shouldAddParamTypesMetadata(node) { + var kind = node.kind; + return kind === 221 + || kind === 192 + || kind === 147 + || kind === 149 + || kind === 150; + } + function serializeTypeOfNode(node) { + switch (node.kind) { + case 145: + case 142: + case 149: + return serializeTypeNode(node.type); + case 150: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 221: + case 192: + case 147: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + function getRestParameterElementType(node) { + if (node && node.kind === 160) { + return node.elementType; + } + else if (node && node.kind === 155) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + function serializeParameterTypesOfNode(node) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = valueDeclaration.parameters; + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunctionLike(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 103: + return ts.createVoidZero(); + case 164: + return serializeTypeNode(node.type); + case 156: + case 157: + return ts.createIdentifier("Function"); + case 160: + case 161: + return ts.createIdentifier("Array"); + case 154: + case 120: + return ts.createIdentifier("Boolean"); + case 132: + return ts.createIdentifier("String"); + case 166: + switch (node.literal.kind) { + case 9: + return ts.createIdentifier("String"); + case 8: + return ts.createIdentifier("Number"); + case 99: + case 84: + return ts.createIdentifier("Boolean"); + default: + ts.Debug.failBadSyntaxKind(node.literal); + break; + } + break; + case 130: + return ts.createIdentifier("Number"); + case 133: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 155: + return serializeTypeReferenceNode(node); + case 158: + case 159: + case 162: + case 163: + case 117: + case 165: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + return ts.createIdentifier("Object"); + } + function serializeTypeReferenceNode(node) { + switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + case ts.TypeReferenceSerializationKind.Unknown: + var serialized = serializeEntityNameAsExpression(node.typeName, true); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName, false); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + default: + return ts.createIdentifier("Object"); + } + } + function serializeEntityNameAsExpression(node, useFallback) { + switch (node.kind) { + case 69: + var name_29 = ts.getMutableClone(node); + name_29.flags &= ~8; + name_29.original = undefined; + name_29.parent = currentScope; + if (useFallback) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + } + return name_29; + case 139: + return serializeQualifiedNameAsExpression(node, useFallback); + } + } + function serializeQualifiedNameAsExpression(node, useFallback) { + var left; + if (node.left.kind === 69) { + left = serializeEntityNameAsExpression(node.left, useFallback); + } + else if (useFallback) { + var temp = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, true)), temp); + } + else { + left = serializeEntityNameAsExpression(node.left, false); + } + return ts.createPropertyAccess(left, node.right); + } + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53), ts.createIdentifier("Symbol"), ts.createToken(54), ts.createIdentifier("Object")); + } + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(name.text); + } + else { + return ts.getSynthesizedClone(name); + } + } + function visitPropertyNameOfClassElement(member) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + if (member.decorators) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + expression = ts.createAssignment(generatedName, expression); + } + return ts.setOriginalNode(ts.createComputedPropertyName(expression, name), name); + } + else { + return name; + } + } + function visitHeritageClause(node) { + if (node.token === 83) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.createHeritageClause(83, types, node); + } + return undefined; + } + function visitExpressionWithTypeArguments(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createExpressionWithTypeArguments(undefined, expression, node); + } + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + setCommentRange(method, node); + setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(method, node); + return method; + } + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); + } + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var func = ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + if (isNamespaceExport(node)) { + var statements = [func]; + addExportMemberAssignment(statements, node); + return statements; + } + return func; + } + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + var func = ts.createFunctionExpression(node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + return func; + } + function visitArrowFunction(node) { + var func = ts.createArrowFunction(undefined, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.equalsGreaterThanToken, transformConciseBody(node), node); + ts.setOriginalNode(func, node); + return func; + } + function transformFunctionBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformFunctionBodyWorker(node.body); + } + function transformFunctionBodyWorker(body, start) { + if (start === void 0) { start = 0; } + var savedCurrentScope = currentScope; + currentScope = body; + startLexicalEnvironment(); + var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); + var visited = ts.updateBlock(body, statements); + var declarations = endLexicalEnvironment(); + currentScope = savedCurrentScope; + return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + } + function transformConciseBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformConciseBodyWorker(node.body, false); + } + function transformConciseBodyWorker(body, forceBlockFunctionBody) { + if (ts.isBlock(body)) { + return transformFunctionBodyWorker(body); + } + else { + startLexicalEnvironment(); + var visited = ts.visitNode(body, visitor, ts.isConciseBody); + var declarations = endLexicalEnvironment(); + var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + if (forceBlockFunctionBody && !ts.isBlock(merged)) { + return ts.createBlock([ + ts.createReturn(merged) + ]); + } + else { + return merged; + } + } + } + function getPromiseConstructor(type) { + var typeName = ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function transformAsyncFunctionBody(node) { + var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(node.type) : undefined; + var isArrowFunction = node.kind === 180; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); + statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + var block = ts.createBlock(statements, node.body, true); + if (languageVersion >= 2) { + if (resolver.getNodeCheckFlags(node) & 4096) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 8); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 4); + } + } + return block; + } + else { + return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, true)); + } + } + function visitParameter(node) { + if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + return undefined; + } + var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); + ts.setOriginalNode(parameter, node); + setCommentRange(parameter, node); + setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + setNodeEmitFlags(parameter.name, 1024); + return parameter; + } + function visitVariableStatement(node) { + if (isNamespaceExport(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + } + else { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), node); + } + } + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + } + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2); + if (ts.isAssertionExpression(innerExpression)) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function shouldEmitEnumDeclaration(node) { + return !ts.isConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + function shouldEmitVarForEnumDeclaration(node) { + return !ts.hasModifier(node, 1) + || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + } + function addVarForEnumExportedFromNamespace(statements, node) { + var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); + setSourceMapRange(statement, node); + statements.push(statement); + } + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + var emitFlags = 64; + if (shouldEmitVarForEnumDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = getExportName(node); + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); + ts.setOriginalNode(enumStatement, node); + setNodeEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + if (isNamespaceExport(node)) { + addVarForEnumExportedFromNamespace(statements, node); + } + return statements; + } + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, ts.map(node.members, transformEnumMember)); + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); + } + function transformEnumMember(member) { + var name = getExpressionForPropertyName(member, false); + return ts.createStatement(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name, member), member); + } + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + function isModuleMergedWithES6Class(node) { + return languageVersion === 2 + && ts.isMergedWithClass(node); + } + function isES6ExportedDeclaration(node) { + return isExternalModuleExport(node) + && moduleKind === ts.ModuleKind.ES6; + } + function shouldEmitVarForModuleDeclaration(node) { + return !isModuleMergedWithES6Class(node) + && (!isES6ExportedDeclaration(node) + || ts.isFirstDeclarationOfKind(node, node.kind)); + } + function addVarForEnumOrModuleDeclaration(statements, node) { + var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) + ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) + : undefined, [ + ts.createVariableDeclaration(getDeclarationName(node, false, true)) + ]); + ts.setOriginalNode(statement, node); + if (node.kind === 224) { + setSourceMapRange(statement.declarationList, node); + } + else { + setSourceMapRange(statement, node); + } + setCommentRange(statement, node); + setNodeEmitFlags(statement, 32768); + statements.push(statement); + } + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + var emitFlags = 64; + if (shouldEmitVarForModuleDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384; + } + } + var parameterName = getNamespaceParameterName(node); + var containerName = getNamespaceContainerName(node); + var exportName = getExportName(node); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (ts.hasModifier(node, 1) && !isES6ExportedDeclaration(node)) { + var localName = getLocalName(node); + moduleArg = ts.createAssignment(localName, moduleArg); + } + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); + ts.setOriginalNode(moduleStatement, node); + setNodeEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + return statements; + } + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 226) { + ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); + if (body.kind !== 226) { + setNodeEmitFlags(block, block.emitFlags | 49152); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 225) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function shouldEmitImportEqualsDeclaration(node) { + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + return ts.visitEachChild(node, visitor, context); + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + setNodeEmitFlags(moduleReference, 49152 | 65536); + if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(node.name, undefined, moduleReference) + ]), node), node); + } + else { + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + function isNamespaceExport(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1); + } + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1); + } + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512); + } + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512); + } + function expressionToStatement(expression) { + return ts.createStatement(expression, undefined); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); + setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var statement = ts.createStatement(expression); + setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, false, true), exportValue), location); + } + function createExternalModuleExport(exportName) { + return ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([ + ts.createExportSpecifier(exportName) + ])); + } + function getNamespaceMemberName(name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), name); + var emitFlags; + if (!allowComments) { + emitFlags |= 49152; + } + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (emitFlags) { + setNodeEmitFlags(qualifiedName, emitFlags); + } + return qualifiedName; + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return getNamespaceMemberName(name, false, true); + } + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + setSourceMapRange(name, node.name); + return name; + } + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + function getLocalName(node, noSourceMaps, allowComments) { + return getDeclarationName(node, allowComments, !noSourceMaps, 262144); + } + function getExportName(node, noSourceMaps, allowComments) { + if (isNamespaceExport(node)) { + return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); + } + return getDeclarationName(node, allowComments, !noSourceMaps, 131072); + } + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name) { + var name_30 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (!allowComments) { + emitFlags |= 49152; + } + if (emitFlags) { + setNodeEmitFlags(name_30, emitFlags); + } + return name_30; + } + else { + return ts.getGeneratedNameForNode(node); + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32) + ? getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8) === 0) { + enabledSubstitutions |= 8; + context.enableSubstitution(69); + } + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 4) === 0) { + enabledSubstitutions |= 4; + context.enableSubstitution(174); + context.enableSubstitution(172); + context.enableSubstitution(173); + context.enableEmitNotification(221); + context.enableEmitNotification(147); + context.enableEmitNotification(149); + context.enableEmitNotification(150); + context.enableEmitNotification(148); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(69); + classAliases = ts.createMap(); + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(69); + context.enableSubstitution(254); + context.enableEmitNotification(225); + } + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 221 + || kind === 148 + || kind === 147 + || kind === 149 + || kind === 150; + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 225; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 224; + } + function onEmitNode(node, emit) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSuperContainer = currentSuperContainer; + if (enabledSubstitutions & 4 && isSuperContainer(node)) { + currentSuperContainer = node; + } + if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2; + } + if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8; + } + previousOnEmitNode(node, emit); + applicableSubstitutions = savedApplicableSubstitutions; + currentSuperContainer = savedCurrentSuperContainer; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2) { + var name_31 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_31); + if (exportedName) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name_31, initializer, node); + } + return ts.createPropertyAssignment(name_31, exportedName, node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + } + if (enabledSubstitutions & 4) { + switch (node.kind) { + case 174: + return substituteCallExpression(node); + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1) { + if (resolver.getNodeCheckFlags(node) & 16777216) { + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; + if (classAlias) { + var clone_4 = ts.getSynthesizedClone(classAlias); + setSourceMapRange(clone_4, node); + setCommentRange(clone_4, node); + return clone_4; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + var container = resolver.getReferencedExportContainer(node, false); + if (container) { + var substitute = (applicableSubstitutions & 2 && container.kind === 225) || + (applicableSubstitutions & 8 && container.kind === 224); + if (substitute) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, node); + } + } + } + return undefined; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 95) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 95) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + } + } + ts.transformTypeScript = transformTypeScript; +})(ts || (ts = {})); +var ts; +(function (ts) { + var entities = createEntitiesMap(); + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + return node; + } + function visitor(node) { + if (node.transformFlags & 4) { + return visitorWorker(node); + } + else if (node.transformFlags & 8) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 241: + return visitJsxElement(node, false); + case 242: + return visitJsxSelfClosingElement(node, false); + case 248: + return visitJsxExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 244: + return visitJsxText(node); + case 248: + return visitJsxExpression(node); + case 241: + return visitJsxElement(node, true); + case 242: + return visitJsxSelfClosingElement(node, true); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, undefined, isChild, node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes; + if (attrs.length === 0) { + objectProperties = ts.createNull(); + } + else { + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + segments.unshift(ts.createObjectLiteral()); + } + objectProperties = ts.singleOrUndefined(segments) + || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + } + var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createLiteral(true); + } + else if (node.kind === 9) { + var decoded = tryDecodeEntities(node.text); + return decoded ? ts.createLiteral(decoded, node) : node; + } + else if (node.kind === 248) { + return visitJsxExpression(node); + } + else { + ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var text = ts.getTextOfNode(node, true); + var parts; + var firstNonWhitespace = 0; + var lastNonWhitespace = -1; + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { + var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + if (!parts) { + parts = []; + } + parts.push(ts.createLiteral(decodeEntities(part))); + } + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpace(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + if (firstNonWhitespace !== -1) { + var part = text.substr(firstNonWhitespace); + if (!parts) { + parts = []; + } + parts.push(ts.createLiteral(decodeEntities(part))); + } + if (parts) { + return ts.reduceLeft(parts, aggregateJsxTextParts); + } + return undefined; + } + function aggregateJsxTextParts(left, right) { + return ts.createAdd(ts.createAdd(left, ts.createLiteral(" ")), right); + } + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities[word]; + return ch ? String.fromCharCode(ch) : match; + } + }); + } + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 241) { + return getTagName(node.openingElement); + } + else { + var name_32 = node.tagName; + if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { + return ts.createLiteral(name_32.text); + } + else { + return ts.createExpressionFromEntityName(name_32); + } + } + } + function getAttributeName(node) { + var name = node.name; + if (/^[A-Za-z_]\w*$/.test(name.text)) { + return name; + } + else { + return ts.createLiteral(name.text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + function createEntitiesMap() { + return ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES7(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if (node.transformFlags & 16) { + return visitorWorker(node); + } + else if (node.transformFlags & 32) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 187: + return visitBinaryExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (node.operatorToken.kind === 60) { + var target = void 0; + var value = void 0; + if (ts.isElementAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); + } + else if (ts.isPropertyAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); + value = ts.createPropertyAccess(expressionTemp, left.name, left); + } + else { + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, node), node); + } + else if (node.operatorToken.kind === 38) { + return ts.createMathPow(left, right, node); + } + else { + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + } + ts.transformES7 = transformES7; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES6(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + var convertedLoopState; + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64) !== 0 || + node.kind === 214 || + (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { + switch (node.kind) { + case 211: + return visitReturnStatement(node); + case 200: + return visitVariableStatement(node); + case 213: + return visitSwitchStatement(node); + case 210: + case 209: + return visitBreakOrContinueStatement(node); + case 97: + return visitThisKeyword(node); + case 69: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 82: + return node; + case 221: + return visitClassDeclaration(node); + case 192: + return visitClassExpression(node); + case 142: + return visitParameter(node); + case 220: + return visitFunctionDeclaration(node); + case 180: + return visitArrowFunction(node); + case 179: + return visitFunctionExpression(node); + case 218: + return visitVariableDeclaration(node); + case 69: + return visitIdentifier(node); + case 219: + return visitVariableDeclarationList(node); + case 214: + return visitLabeledStatement(node); + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 208: + return visitForOfStatement(node); + case 202: + return visitExpressionStatement(node); + case 171: + return visitObjectLiteralExpression(node); + case 254: + return visitShorthandPropertyAssignment(node); + case 170: + return visitArrayLiteralExpression(node); + case 174: + return visitCallExpression(node); + case 175: + return visitNewExpression(node); + case 178: + return visitParenthesizedExpression(node, true); + case 187: + return visitBinaryExpression(node, true); + case 11: + case 12: + case 13: + case 14: + return visitTemplateLiteral(node); + case 176: + return visitTaggedTemplateExpression(node); + case 189: + return visitTemplateExpression(node); + case 190: + return visitYieldExpression(node); + case 95: + return visitSuperKeyword(node); + case 190: + return ts.visitEachChild(node, visitor, context); + case 147: + return visitMethodDeclaration(node); + case 256: + return visitSourceFileNode(node); + case 200: + return visitVariableStatement(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 180) { + enclosingNonArrowFunction = currentNode; + if (!(currentNode.emitFlags & 2097152)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + switch (currentNode.kind) { + case 200: + enclosingVariableStatement = currentNode; + break; + case 219: + case 218: + case 169: + case 167: + case 168: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps |= 2; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 180) { + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + var jump = node.kind === 210 ? 2 : 4; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 210) { + convertedLoopState.nonLocalJumps |= 2; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4; + labelMarker = "continue"; + } + } + else { + if (node.kind === 210) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 24, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 24, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitClassDeclaration(node) { + var modifierFlags = ts.getModifierFlags(node); + var isExported = modifierFlags & 1; + var isDefault = modifierFlags & 512; + var modifiers = isExported && !isDefault + ? ts.filter(node.modifiers, isExportModifier) + : undefined; + var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(getDeclarationName(node, true), undefined, transformClassLikeDeclarationToExpression(node)) + ]), node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + if (isExported && isDefault) { + var statements = [statement]; + statements.push(ts.createExportAssignment(undefined, undefined, false, getDeclarationName(node, false))); + return statements; + } + return statement; + } + function isExportModifier(node) { + return node.kind === 82; + } + function visitClassExpression(node) { + return transformClassLikeDeclarationToExpression(node); + } + function transformClassLikeDeclarationToExpression(node) { + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); + if (getNodeEmitFlags(node) & 524288) { + setNodeEmitFlags(classFunction, 524288); + } + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + setNodeEmitFlags(inner, 49152); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + setNodeEmitFlags(outer, 49152); + return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16); + var localName = getLocalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + setNodeEmitFlags(outer, 49152); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + setNodeEmitFlags(statement, 49152 | 12288); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); + setNodeEmitFlags(block, 49152); + return block; + } + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), extendsClauseElement)); + } + } + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + } + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + if (constructor && !hasSynthesizedSuper) { + return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); + } + return []; + } + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + startLexicalEnvironment(); + if (constructor) { + addCaptureThisForNodeIfNeeded(statements, constructor); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + } + addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); + if (constructor) { + var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + ts.addRange(statements, body); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); + if (!constructor) { + setNodeEmitFlags(block, 49152); + } + return block; + } + function transformConstructorBodyWithSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); + } + function transformConstructorBodyWithoutSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + } + function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { + if (constructor ? hasSynthesizedSuper : extendsClauseElement) { + statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + } + } + function visitParameter(node) { + if (node.dotDotDotToken) { + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), undefined, node), node); + } + else if (node.initializer) { + return ts.setOriginalNode(ts.createParameter(node.name, undefined, node), node); + } + else { + return node; + } + } + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536) !== 0; + } + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_33)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + } + } + } + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + if (name.elements.length > 0) { + statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + } + else if (initializer) { + statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + } + } + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + ], parameter), 32 | 1024 | 12288), undefined, parameter); + statement.startsOnNewLine = true; + setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + statements.push(statement); + } + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 69 && !inConstructorWithSynthesizedSuper; + } + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + var declarationName = ts.getMutableClone(parameter.name); + setNodeEmitFlags(declarationName, 1536); + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) + ]), parameter), 8388608)); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) + ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) + ])); + setNodeEmitFlags(forStatement, 8388608); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 && node.kind !== 180) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, ts.createThis()) + ])); + setNodeEmitFlags(captureThisStatement, 49152 | 8388608); + setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + } + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 198: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 147: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 149: + case 150: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 148: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(member); + } + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = getCommentRange(member); + var sourceMapRange = getSourceMapRange(member); + var func = transformFunctionLikeToExpression(member, member, undefined); + setNodeEmitFlags(func, 49152); + setSourceMapRange(func, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); + ts.setOriginalNode(statement, member); + setCommentRange(statement, commentRange); + setNodeEmitFlags(statement, 1536); + return statement; + } + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); + setNodeEmitFlags(statement, 49152); + return statement; + } + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var target = ts.getMutableClone(receiver); + setNodeEmitFlags(target, 49152 | 1024); + setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + setNodeEmitFlags(propertyName, 49152 | 512); + setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); + setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + var getter = ts.createPropertyAssignment("get", getterFunction); + setCommentRange(getter, getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); + setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + var setter = ts.createPropertyAssignment("set", setterFunction); + setCommentRange(setter, getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, undefined, true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + function visitArrowFunction(node) { + if (node.transformFlags & 8192) { + enableSubstitutionsForCapturedThis(); + } + var func = transformFunctionLikeToExpression(node, node, undefined); + setNodeEmitFlags(func, 256); + return func; + } + function visitFunctionExpression(node) { + return transformFunctionLikeToExpression(node, node, node.name); + } + function visitFunctionDeclaration(node) { + return ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node), node); + } + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 180) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + function transformFunctionBody(node) { + var multiLine = false; + var singleLine = false; + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + startLexicalEnvironment(); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, false); + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 180); + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, body); + setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + statements.push(returnStatement); + closeBraceLocation = body; + } + var lexicalEnvironment = endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + setNodeEmitFlags(block, 32); + } + if (closeBraceLocation) { + setTokenSourceMapRange(block, 16, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitExpressionStatement(node) { + switch (node.expression.kind) { + case 178: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); + case 187: + return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParenthesizedExpression(node, needsDestructuringValue) { + if (needsDestructuringValue) { + switch (node.expression.kind) { + case 178: + return ts.createParen(visitParenthesizedExpression(node.expression, true), node); + case 187: + return ts.createParen(visitBinaryExpression(node.expression, true), node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitBinaryExpression(node, needsDestructuringValue) { + ts.Debug.assert(ts.isDestructuringAssignment(node)); + return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3) == 0) { + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); + } + else { + assignment = ts.createBinary(decl.name, 56, decl.initializer); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24, acc); }), node); + } + else { + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclarationList(node) { + if (node.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, node); + ts.setOriginalNode(declarationList, node); + setCommentRange(declarationList, node); + if (node.transformFlags & 2097152 + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + function shouldEmitExplicitInitializerForLetDeclaration(node) { + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072; + var isDeclaredInLoop = flags & 262144; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 207 + && enclosingBlockScopeContainer.kind !== 208 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, false))); + return emitExplicitInitializer; + } + function visitVariableDeclarationInLetDeclarationList(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_5 = ts.getMutableClone(node); + clone_5.initializer = ts.createVoidZero(); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name)) { + var recordTempVariablesInLine = !enclosingVariableStatement + || !ts.hasModifier(enclosingVariableStatement, 1); + return ts.flattenVariableDestructuring(context, node, undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 69 + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(undefined); + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); + var declarationList = ts.createVariableDeclarationList(declarations, initializer); + ts.setOriginalNode(declarationList, initializer); + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement(undefined, declarationList)); + } + else { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, ts.createElementAccess(rhsReference, counter)) + ], ts.moveRangePos(initializer, -1)), ts.moveRangeEnd(initializer, -1))); + } + } + else { + var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); + if (ts.isDestructuringAssignment(assignment)) { + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, false, hoistVariableDeclaration, visitor))); + } + else { + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); + setNodeEmitFlags(body, 1536 | 12288); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) + ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); + setNodeEmitFlags(forStatement, 8192); + return forStatement; + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var numProperties = properties.length; + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 4194304 + || property.name.kind === 140) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var expressions = []; + var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536) !== 0; + } + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 69) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 | 4; + } + var result = convert ? convert(node, undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 206: + case 207: + case 208: + var initializer = node.initializer; + if (initializer && initializer.kind === 219) { + loopInitializer = initializer; + } + break; + } + var loopParameters = []; + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + if (outerConvertedLoopState.argumentsName) { + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length) { + var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + copyOutParameters(loopOutParameters, 1, statements_3); + loopBody = ts.createBlock(statements_3, undefined, true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], undefined, true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (node.statement.transformFlags & 4194304) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 256; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 2097152; + } + var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ])); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + if (currentState.argumentsName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + if (outerConvertedLoopState) { + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var name_34 in currentState.hoistedLocalVariables) { + var identifier = currentState.hoistedLocalVariables[name_34]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { + var outParam = loopOutParameters_1[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + loop.statement = undefined; + loop = ts.visitEachChild(loop, visitor, context); + loop.statement = ts.createBlock(convertedLoopBodyStatements, undefined, true); + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 214 + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 56, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + var isSimpleLoop = !(state.nonLocalJumps & ~4) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0, statements); + if (state.nonLocalJumps & 8) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 32, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(name)); + if (resolver.getNodeCheckFlags(decl) & 2097152) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 149: + case 150: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 253: + expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 254: + expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 147: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined), method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function visitMethodDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); + setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, node); + } + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), node); + } + function visitYieldExpression(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitArrayLiteralExpression(node) { + return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); + } + function visitCallExpression(node) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.transformFlags & 262144) { + return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + } + else { + return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + } + } + function visitNewExpression(node) { + ts.Debug.assert((node.transformFlags & 262144) !== 0); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); + } + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpreadElement(node) { + return ts.isSpreadElementExpression(node) + ? visitSpanOfSpreadElements + : visitSpanOfNonSpreadElements; + } + function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.map(chunk, visitExpressionOfSpreadElement); + } + function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, undefined, hasTrailingComma), visitor, ts.isExpression), undefined, multiLine); + } + function visitExpressionOfSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, node); + } + function visitTaggedTemplateExpression(node) { + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, undefined, templateArguments) + ])); + } + function getRawLiteral(node) { + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + var isLast = node.kind === 11 || node.kind === 14; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, node); + } + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + function shouldAddTemplateHead(node) { + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + function visitSuperKeyword(node) { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32) + && currentParent.kind !== 174 + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + function visitSourceFileNode(node) { + var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, prologue); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); + ts.addRange(statements, endLexicalEnvironment()); + var clone = ts.getMutableClone(node); + clone.statements = ts.createNodeArray(statements, node.statements); + return clone; + } + function onEmitNode(node, emit) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { + enclosingFunction = node; + } + previousOnEmitNode(node, emit); + enclosingFunction = savedEnclosingFunction; + } + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(69); + } + } + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(97); + context.enableEmitNotification(148); + context.enableEmitNotification(147); + context.enableEmitNotification(149); + context.enableEmitNotification(150); + context.enableEmitNotification(180); + context.enableEmitNotification(179); + context.enableEmitNotification(220); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + function substituteIdentifier(node) { + if (enabledSubstitutions & 2) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 169: + case 221: + case 224: + case 218: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 97: + return substituteThisKeyword(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 + && enclosingFunction + && enclosingFunction.emitFlags & 256) { + return ts.createIdentifier("_this", node); + } + return node; + } + function getLocalName(node, allowComments, allowSourceMaps) { + return getDeclarationName(node, allowComments, allowSourceMaps, 262144); + } + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && !ts.isGeneratedIdentifier(node.name)) { + var name_35 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536; + } + if (!allowComments) { + emitFlags |= 49152; + } + if (emitFlags) { + setNodeEmitFlags(name_35, emitFlags); + } + return name_35; + } + return ts.getGeneratedNameForNode(node); + } + function getClassMemberPrefix(node, member) { + var expression = getLocalName(node); + return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + var parameter = ts.singleOrUndefined(constructor.parameters); + if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression === parameter.name; + } + } + ts.transformES6 = transformES6; +})(ts || (ts = {})); +var ts; +(function (ts) { + var instructionNames = ts.createMap((_a = {}, + _a[2] = "return", + _a[3] = "break", + _a[4] = "yield", + _a[5] = "yield*", + _a[7] = "endfinally", + _a)); + function transformGenerators(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + var blocks; + var blockOffsets; + var blockActions; + var blockStack; + var labelOffsets; + var labelExpressions; + var nextLabelId = 1; + var operations; + var operationArguments; + var operationLocations; + var state; + var blockIndex = 0; + var labelNumber = 0; + var labelNumbers; + var lastOperationWasAbrupt; + var lastOperationWasCompletion; + var clauses; + var statements; + var exceptionBlockStack; + var currentExceptionBlock; + var withBlockStack; + return transformSourceFile; + function transformSourceFile(node) { + if (node.transformFlags & 1024) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + } + return node; + } + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 512) { + return visitGenerator(node); + } + else if (transformFlags & 1024) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 213: + return visitSwitchStatement(node); + case 214: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + case 149: + case 150: + return visitAccessorDeclaration(node); + case 200: + return visitVariableStatement(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 210: + return visitBreakStatement(node); + case 209: + return visitContinueStatement(node); + case 211: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (1024 | 8388608)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 187: + return visitBinaryExpression(node); + case 188: + return visitConditionalExpression(node); + case 190: + return visitYieldExpression(node); + case 170: + return visitArrayLiteralExpression(node); + case 171: + return visitObjectLiteralExpression(node); + case 173: + return visitElementAccessExpression(node); + case 174: + return visitCallExpression(node); + case 175: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitGenerator(node) { + switch (node.kind) { + case 220: + return visitFunctionDeclaration(node); + case 179: + return visitFunctionExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitFunctionDeclaration(node) { + if (node.asteriskToken && node.emitFlags & 2097152) { + node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + function visitFunctionExpression(node) { + if (node.asteriskToken && node.emitFlags & 2097152) { + node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + function transformGeneratorFunctionBody(body) { + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(undefined); + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addRange(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.createBlock(statements, body, body.multiLine); + } + function visitVariableStatement(node) { + if (node.transformFlags & 4194304) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + if (node.emitFlags & 8388608) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + } + } + function visitBinaryExpression(node) { + switch (ts.getExpressionAssociativity(node)) { + case 0: + return visitLeftAssociativeBinaryExpression(node); + case 1: + return visitRightAssociativeBinaryExpression(node); + default: + ts.Debug.fail("Unknown associativity."); + } + } + function isCompoundAssignment(kind) { + return kind >= 57 + && kind <= 68; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 57: return 35; + case 58: return 36; + case 59: return 37; + case 60: return 38; + case 61: return 39; + case 62: return 40; + case 63: return 43; + case 64: return 44; + case 65: return 45; + case 66: return 46; + case 67: return 47; + case 68: return 48; + } + } + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 172: + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 173: + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.createBinary(target, 56, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 24) { + return visitCommaExpression(node); + } + var clone_6 = ts.getMutableClone(node); + clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitLogicalBinaryExpression(node) { + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); + if (node.operatorToken.kind === 51) { + emitBreakWhenFalse(resultLabel, resultLocal, node.left); + } + else { + emitBreakWhenTrue(resultLabel, resultLocal, node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), node.right); + markLabel(resultLabel); + return resultLocal; + } + function visitCommaExpression(node) { + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + function visitConditionalExpression(node) { + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + emitYieldStar(expression, node); + } + else { + emitYield(expression, node); + } + markLabel(resumeLabel); + return createGeneratorResume(); + } + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, node.multiLine); + } + function visitElements(elements, multiLine) { + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp = declareLocal(); + var hasAssignedTemp = false; + if (numInitialElements > 0) { + emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + hasAssignedTemp = true; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions)); + hasAssignedTemp = true; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + visited.startsOnNewLine = true; + } + expressions.push(visited); + } + return expressions; + } + } + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + var clone_7 = ts.getMutableClone(node); + clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_7; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, false), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, false)), undefined, [], node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 199: + return transformAndEmitBlock(node); + case 202: + return transformAndEmitExpressionStatement(node); + case 203: + return transformAndEmitIfStatement(node); + case 204: + return transformAndEmitDoStatement(node); + case 205: + return transformAndEmitWhileStatement(node); + case 206: + return transformAndEmitForStatement(node); + case 207: + return transformAndEmitForInStatement(node); + case 209: + return transformAndEmitContinueStatement(node); + case 210: + return transformAndEmitBreakStatement(node); + case 211: + return transformAndEmitReturnStatement(node); + case 212: + return transformAndEmitWithStatement(node); + case 213: + return transformAndEmitSwitchStatement(node); + case 214: + return transformAndEmitLabeledStatement(node); + case 215: + return transformAndEmitThrowStatement(node); + case 216: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement, true)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression), initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression), node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression, true), ts.visitNode(node.incrementor, visitor, ts.isExpression, true), ts.visitNode(node.statement, visitor, ts.isStatement, false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + if (containsYield(node)) { + var keysArray = declareLocal(); + var key = declareLocal(); + var keysIndex = ts.createLoopVariable(); + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); + emitBreak(label, node); + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); + emitBreak(label, node); + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression, true), node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression, true), node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 250 && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 249) { + var caseClause = clause; + if (containsYield(caseClause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(caseClause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], caseClause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + beginLabeledBlock(node.label.text); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(node.label.text); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return node && (node.transformFlags & 4194304) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (renamedCatchVariables && ts.hasProperty(renamedCatchVariables, node.text)) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_36) { + var clone_8 = ts.getMutableClone(name_36); + setSourceMapRange(clone_8, node); + setCommentRange(clone_8, node); + return clone_8; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node)) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(undefined); + hoistVariableDeclaration(temp); + return temp; + } + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + function endBlock() { + var block = peekBlock(); + ts.Debug.assert(block !== undefined, "beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1); + var block = endBlock(); + markLabel(block.endLabel); + } + function isWithBlock(block) { + return block.kind === 1; + } + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0, + state: 0, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0); + var text = variable.name.text; + var name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = ts.createMap(); + context.enableSubstitution(69); + } + renamedCatchVariables[text] = true; + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [])); + emitNop(); + } + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2; + exception.finallyLabel = finallyLabel; + } + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0); + var exception = endBlock(); + var state = exception.state; + if (state < 2) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3; + } + function isExceptionBlock(block) { + return block.kind === 0; + } + function beginScriptLoopBlock() { + beginBlock({ + kind: 3, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel + }); + return breakLabel; + } + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2, + isScript: true, + breakLabel: -1 + }); + } + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2, + isScript: false, + breakLabel: breakLabel + }); + return breakLabel; + } + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + function supportsUnlabeledBreak(block) { + return block.kind === 2 + || block.kind === 3; + } + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4; + } + function supportsUnlabeledContinue(block) { + return block.kind === 3; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + function findBreakTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + return 0; + } + function findContinueTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + return 0; + } + function createLabel(label) { + if (label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createSynthesizedNode(8); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createNode(193); + } + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + literal.trailingComment = instructionNames[instruction]; + return literal; + } + function createInlineBreak(label, location) { + ts.Debug.assert(label > 0, "Invalid label: " + label); + return ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), location); + } + function createInlineReturn(expression, location) { + return ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)]), location); + } + function createGeneratorResume(location) { + return ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [], location); + } + function emitNop() { + emitWorker(0); + } + function emitStatement(node) { + if (node) { + emitWorker(1, [node]); + } + else { + emitNop(); + } + } + function emitAssignment(left, right, location) { + emitWorker(2, [left, right], location); + } + function emitBreak(label, location) { + emitWorker(3, [label], location); + } + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4, [label, condition], location); + } + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5, [label, condition], location); + } + function emitYieldStar(expression, location) { + emitWorker(7, [expression], location); + } + function emitYield(expression, location) { + emitWorker(6, [expression], location); + } + function emitReturn(expression, location) { + emitWorker(8, [expression], location); + } + function emitThrow(expression, location) { + emitWorker(9, [expression], location); + } + function emitEndfinally() { + emitWorker(10); + } + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ + ts.createThis(), + setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ]); + } + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + switchStatement.startsOnNewLine = true; + return [switchStatement]; + } + if (statements) { + return statements; + } + return []; + } + function flushLabel() { + if (!statements) { + return; + } + appendLabel(!lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(undefined, undefined); + } + if (statements && clauses) { + appendLabel(false); + } + updateLabelExpressions(); + } + function isFinalLabelReachable(operationIndex) { + if (!lastOperationWasCompletion) { + return true; + } + if (!labelOffsets || !labelExpressions) { + return false; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + if (isExceptionBlock(block)) { + if (blockAction === 0) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + } + else if (isWithBlock(block)) { + if (blockAction === 0) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1) { + withBlockStack.pop(); + } + } + } + } + } + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0) { + return; + } + else if (opcode === 10) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2: + return writeAssign(args[0], args[1], location); + case 3: + return writeBreak(args[0], location); + case 4: + return writeBreakWhenTrue(args[0], args[1], location); + case 5: + return writeBreakWhenFalse(args[0], args[1], location); + case 6: + return writeYield(args[0], location); + case 7: + return writeYieldStar(args[0], location); + case 8: + return writeReturn(args[0], location); + case 9: + return writeThrow(args[0], location); + } + } + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + function writeAssign(left, right, operationLocation) { + writeStatement(ts.createStatement(ts.createAssignment(left, right), operationLocation)); + } + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createThrow(expression, operationLocation)); + } + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2), expression] + : [createInstruction(2)]), operationLocation)); + } + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation)); + } + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.createIf(condition, ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation))); + } + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.createIf(ts.createLogicalNot(condition), ts.createReturn(ts.createArrayLiteral([ + createInstruction(3), + createLabel(label) + ]), operationLocation))); + } + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4), expression] + : [createInstruction(4)]), operationLocation)); + } + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5), + expression + ]), operationLocation)); + } + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7) + ]))); + } + } + ts.transformGenerators = transformGenerators; + var _a; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69); + context.enableSubstitution(187); + context.enableSubstitution(185); + context.enableSubstitution(186); + context.enableSubstitution(254); + context.enableEmitNotification(256); + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var bindingNameExportSpecifiersMap; + var bindingNameExportSpecifiersForFileMap = ts.createMap(); + var hasExportStarsToExportValues; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule_1(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + return updated; + } + return node; + var _a; + } + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, false); + var updated = updateSourceFile(node, statements); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + } + return updated; + } + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, true); + } + function transformUMDModule(node) { + var define = ts.createIdentifier("define"); + setNodeEmitFlags(define, 16); + return transformAsynchronousModule(node, define, undefined, false); + } + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createFunctionExpression(undefined, undefined, undefined, [ + ts.createParameter("require"), + ts.createParameter("exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + ]))) + ]); + } + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, true); + var body = ts.createBlock(statements, undefined, true); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(body, 2); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (emitAsReturn) { + var statement = ts.createReturn(exportEquals.expression, exportEquals); + setNodeEmitFlags(statement, 12288 | 49152); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); + setNodeEmitFlags(statement, 49152); + statements.push(statement); + } + } + } + function visitor(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 236: + return visitExportDeclaration(node); + case 235: + return visitExportAssignment(node); + case 200: + return visitVariableStatement(node); + case 220: + return visitFunctionDeclaration(node); + case 221: + return visitClassDeclaration(node); + case 202: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var statements = []; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + statements.push(ts.createStatement(createRequireCall(node), node)); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + } + else { + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); + } + } + statements.push(ts.createVariableStatement(undefined, ts.createConstDeclarationList(variables), node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node), node) + ]))); + } + addExportImportAssignments(statements, node); + return ts.singleOrMany(statements); + } + function visitImportEqualsDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + setNodeEmitFlags(node.name, 128); + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1)) { + statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), node)); + } + else { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) + ], undefined, languageVersion >= 2 ? 2 : 0), node)); + } + } + else { + if (ts.hasModifier(node, 1)) { + statements.push(ts.createStatement(createExportAssignment(node.name, node.name), node)); + } + } + addExportImportAssignments(statements, node); + return statements; + } + function visitExportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) + ]), node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + if (resolver.isValueAliasDeclaration(specifier)) { + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), specifier)); + } + } + return ts.singleOrMany(statements); + } + else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), node); + } + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + var statements = []; + addExportDefault(statements, node.expression, node); + return statements; + } + } + return undefined; + } + function addExportDefault(statements, expression, location) { + tryAddExportDefaultCompat(statements); + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); + } + function tryAddExportDefaultCompat(statements) { + var original = ts.getOriginalNode(currentSourceFile); + ts.Debug.assert(original.kind === 256); + if (!original.symbol.exports["___esModule"]) { + if (languageVersion === 0) { + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + function addExportImportAssignments(statements, node) { + if (ts.isImportEqualsDeclaration(node)) { + addExportMemberAssignments(statements, node.name); + } + else { + var names = ts.reduceEachChild(node, collectExportMembers, []); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_37 = names_1[_i]; + addExportMemberAssignments(statements, name_37); + } + } + } + function collectExportMembers(names, node) { + if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { + var name_38 = node.name; + if (ts.isIdentifier(name_38)) { + names.push(name_38); + } + } + return ts.reduceEachChild(node, collectExportMembers, names); + } + function addExportMemberAssignments(statements, name) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), specifier.name))); + } + } + } + function addExportMemberAssignment(statements, node) { + if (ts.hasModifier(node, 512)) { + addExportDefault(statements, getDeclarationName(node), node); + } + else { + statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + } + } + function visitVariableStatement(node) { + var originalKind = ts.getOriginalNode(node).kind; + if (originalKind === 225 || + originalKind === 224 || + originalKind === 221) { + if (!ts.hasModifier(node, 1)) { + return node; + } + return ts.setOriginalNode(ts.createVariableStatement(undefined, node.declarationList), node); + } + var resultStatements = []; + if (ts.hasModifier(node, 1)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length > 0) { + var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + resultStatements.push(inlineAssignments); + } + } + else { + resultStatements.push(node); + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + addExportMemberAssignmentsForBindingName(resultStatements, decl.name); + } + return resultStatements; + } + function addExportMemberAssignmentsForBindingName(resultStatements, name) { + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + addExportMemberAssignmentsForBindingName(resultStatements, element.name); + } + } + } + else { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + var sourceFileId = ts.getOriginalNodeId(currentSourceFile); + if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { + bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); + } + bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; + addExportMemberAssignments(resultStatements, name); + } + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); + } + else { + return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + } + function visitFunctionDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1)) { + statements.push(ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name, undefined, node.parameters, undefined, node.body, node), node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitClassDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1)) { + statements.push(ts.setOriginalNode(ts.createClassDeclaration(undefined, undefined, name, undefined, node.heritageClauses, node.members, node), node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name && !(node.decorators && node.decorators.length)) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitExpressionStatement(node) { + var original = ts.getOriginalNode(node); + var origKind = original.kind; + if (origKind === 224 || origKind === 225) { + return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); + } + else if (origKind === 221) { + var classDecl = original; + if (classDecl.name) { + var statements = [node]; + addExportMemberAssignments(statements, classDecl.name); + return statements; + } + } + return node; + } + function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { + var statements = [node]; + if (ts.hasModifier(original, 1) && + original.kind === 224 && + ts.isFirstDeclarationOfKind(original, 224)) { + addVarForExportedEnumOrNamespaceDeclaration(statements, original); + } + addExportMemberAssignments(statements, original.name); + return statements; + } + function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { + var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); + setNodeEmitFlags(transformedStatement, 49152); + statements.push(transformedStatement); + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function onEmitNode(node, emit) { + if (node.kind === 256) { + bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + bindingNameExportSpecifiersMap = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 187: + return substituteBinaryExpression(node); + case 186: + case 185: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteExportedName(node) + || trySubstituteImportedName(node) + || node; + } + function substituteBinaryExpression(node) { + var left = node.left; + if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { + setNodeEmitFlags(node, 128); + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, node); + } + return nestedExportAssignment; + } + } + return node; + } + function substituteUnaryExpression(node) { + var operator = node.operator; + var operand = node.operand; + if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { + setNodeEmitFlags(node, 128); + var transformedUnaryExpression = void 0; + if (node.kind === 186) { + transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + setNodeEmitFlags(transformedUnaryExpression, 128); + } + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, transformedUnaryExpression || node); + } + return nestedExportAssignment; + } + } + return node; + } + function trySubstituteExportedName(node) { + var emitFlags = getNodeEmitFlags(node); + if ((emitFlags & 262144) === 0) { + var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); + if (container) { + if (container.kind === 256) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); + } + } + } + return undefined; + } + function trySubstituteImportedName(node) { + if ((getNodeEmitFlags(node) & 262144) === 0) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (ts.isImportClause(declaration)) { + if (languageVersion >= 1) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), node); + } + else { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), node); + } + } + else if (ts.isImportSpecifier(declaration)) { + var name_39 = declaration.propertyName || declaration.name; + if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); + } + else { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); + } + } + } + } + return undefined; + } + function getModuleMemberName(name) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), name, name); + } + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (ts.isDefined(moduleName)) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), undefined, args); + } + function createExportStatement(name, value, location) { + var statement = ts.createStatement(createExportAssignment(name, value)); + statement.startsOnNewLine = true; + if (location) { + setSourceMapRange(statement, location); + } + return statement; + } + function createExportAssignment(name, value) { + return ts.createAssignment(name.originalKeywordKind === 77 && languageVersion === 0 + ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) + : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + var aliasedModuleNames = []; + var unaliasedModuleNames = []; + var importAliasNames = []; + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, externalImports_1 = externalImports; _b < externalImports_1.length; _b++) { + var importNode = externalImports_1[_b]; + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + setNodeEmitFlags(importAliasName, 128); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function updateSourceFile(node, statements) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + return updated; + } + var _a; + } + ts.transformModule = transformModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformSystemModule(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69); + context.enableSubstitution(187); + context.enableSubstitution(185); + context.enableSubstitution(186); + context.enableEmitNotification(256); + var exportFunctionForFileMap = []; + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var hasExportStarsToExportValues; + var exportFunctionForFile; + var contextObjectForFile; + var exportedLocalNames; + var exportedFunctionDeclarations; + var enclosingBlockScopedContainer; + var currentParent; + var currentNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + currentNode = node; + var updated = transformSystemModuleWorker(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + exportedLocalNames = undefined; + exportedFunctionDeclarations = undefined; + return updated; + } + return node; + } + function transformSystemModuleWorker(node) { + ts.Debug.assert(!exportFunctionForFile); + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + exportFunctionForFile = ts.createUniqueName("exports"); + contextObjectForFile = ts.createUniqueName("context"); + exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; + var dependencyGroups = collectDependencyGroups(externalImports); + var statements = []; + addSystemModuleBody(statements, node, dependencyGroups); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); + var body = ts.createFunctionExpression(undefined, undefined, undefined, [ + ts.createParameter(exportFunctionForFile), + ts.createParameter(contextObjectForFile) + ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ? [moduleName, dependencies, body] + : [dependencies, body])) + ], ~1 & getNodeEmitFlags(node)); + var _a; + } + function addSystemModuleBody(statements, node, dependencyGroups) { + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitSourceElement); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) + ]))); + var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); + ts.addRange(statements, endLexicalEnvironment()); + ts.addRange(statements, exportedFunctionDeclarations); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) + ]), true))); + } + function addExportStarIfNeeded(statements) { + if (!hasExportStarsToExportValues) { + return; + } + if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, externalImports_2 = externalImports; _i < externalImports_2.length; _i++) { + var externalImport = externalImports_2[_i]; + if (externalImport.kind === 236 && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + return addExportStarFunction(statements, undefined); + } + } + var exportedNames = []; + if (exportedLocalNames) { + for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { + var exportedLocalName = exportedLocalNames_1[_a]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); + } + } + for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { + var externalImport = externalImports_3[_b]; + if (externalImport.kind !== 236) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + continue; + } + for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { + var element = _d[_c]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) + ]))); + return addExportStarFunction(statements, exportedNamesStorageRef); + } + function generateSetters(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 230: + if (!entry.importClause) { + break; + } + case 229: + ts.Debug.assert(importVariableName !== undefined); + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 236: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); + } + else { + statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, ts.createBlock(statements, undefined, true))); + } + return ts.createArrayLiteral(setters, undefined, true); + } + function visitSourceElement(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 236: + return visitExportDeclaration(node); + case 235: + return visitExportAssignment(node); + default: + return visitNestedNode(node); + } + } + function visitNestedNode(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var currentGrandparent = currentParent; + currentParent = currentNode; + currentNode = node; + if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { + enclosingBlockScopedContainer = currentParent; + } + var result = visitNestedNodeWorker(node); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return result; + } + function visitNestedNodeWorker(node) { + switch (node.kind) { + case 200: + return visitVariableStatement(node); + case 220: + return visitFunctionDeclaration(node); + case 221: + return visitClassDeclaration(node); + case 206: + return visitForStatement(node); + case 207: + return visitForInStatement(node); + case 208: + return visitForOfStatement(node); + case 204: + return visitDoStatement(node); + case 205: + return visitWhileStatement(node); + case 214: + return visitLabeledStatement(node); + case 212: + return visitWithStatement(node); + case 213: + return visitSwitchStatement(node); + case 227: + return visitCaseBlock(node); + case 249: + return visitCaseClause(node); + case 250: + return visitDefaultClause(node); + case 216: + return visitTryStatement(node); + case 252: + return visitCatchClause(node); + case 199: + return visitBlock(node); + case 202: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (node.importClause && ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitImportEqualsDeclaration(node) { + if (ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + var statements = []; + ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); + return statements; + } + return undefined; + } + function visitExportSpecifier(specifier) { + if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) + || resolver.isValueAliasDeclaration(specifier)) { + recordExportName(specifier.name); + return createExportStatement(specifier.name, specifier.propertyName || specifier.name); + } + return undefined; + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + return createExportStatement(ts.createLiteral("default"), node.expression); + } + } + return undefined; + } + function visitVariableStatement(node) { + var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3) == 0) || + enclosingBlockScopedContainer.kind === 256; + if (!shouldHoist) { + return node; + } + var isExported = ts.hasModifier(node, 1); + var expressions = []; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, isExported); + if (visited) { + expressions.push(visited); + } + } + if (expressions.length) { + return ts.createStatement(ts.inlineExpressions(expressions), node); + } + return undefined; + } + function transformVariable(node, isExported) { + hoistBindingElement(node, isExported); + if (!node.initializer) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + return ts.createAssignment(name, node.initializer); + } + else { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); + } + } + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1)) { + var name_40 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); + recordExportedFunctionDeclaration(node); + if (!ts.hasModifier(node, 512)) { + recordExportName(name_40); + } + ts.setOriginalNode(newNode, node); + node = newNode; + } + hoistFunctionDeclaration(node); + return undefined; + } + function visitExpressionStatement(node) { + var originalNode = ts.getOriginalNode(node); + if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { + var name_41 = getDeclarationName(originalNode); + if (originalNode.kind === 224) { + hoistVariableDeclaration(name_41); + } + return [ + node, + createExportStatement(name_41, name_41) + ]; + } + return node; + } + function visitClassDeclaration(node) { + var name = getDeclarationName(node); + hoistVariableDeclaration(name); + var statements = []; + statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, node.heritageClauses, node.members, node)), node)); + if (ts.hasModifier(node, 1)) { + if (!ts.hasModifier(node, 512)) { + recordExportName(name); + } + statements.push(createDeclarationExport(node)); + } + return statements; + } + function shouldHoistLoopInitializer(node) { + return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3) === 0; + } + function visitForStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var expressions = []; + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, false); + if (visited) { + expressions.push(visited); + } + } + ; + return ts.createFor(expressions.length + ? ts.inlineExpressions(expressions) + : ts.createSynthesizedNode(193), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), node); + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function transformForBinding(node) { + var firstDeclaration = ts.firstOrUndefined(node.declarations); + hoistBindingElement(firstDeclaration, false); + var name = firstDeclaration.name; + return ts.isIdentifier(name) + ? name + : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); + } + function visitForInStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function visitForOfStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + function visitDoStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitWhileStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitLabeledStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitWithStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + function visitSwitchStatement(node) { + var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); + if (caseBlock !== node.caseBlock) { + var updated = ts.getMutableClone(node); + updated.caseBlock = caseBlock; + return updated; + } + return node; + } + function visitCaseBlock(node) { + var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); + if (clauses !== node.clauses) { + var updated = ts.getMutableClone(node); + updated.clauses = clauses; + return updated; + } + return node; + } + function visitCaseClause(node) { + var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); + if (statements !== node.statements) { + var updated = ts.getMutableClone(node); + updated.statements = statements; + return updated; + } + return node; + } + function visitDefaultClause(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function visitTryStatement(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function visitCatchClause(node) { + var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); + if (block !== node.block) { + var updated = ts.getMutableClone(node); + updated.block = block; + return updated; + } + return node; + } + function visitBlock(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + function onEmitNode(node, emit) { + if (node.kind === 256) { + exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + exportFunctionForFile = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69: + return substituteExpressionIdentifier(node); + case 187: + return substituteBinaryExpression(node); + case 185: + case 186: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + var importBinding = createImportBinding(importDeclaration); + if (importBinding) { + return importBinding; + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return substituteAssignmentExpression(node); + } + return node; + } + function substituteAssignmentExpression(node) { + setNodeEmitFlags(node, 128); + var left = node.left; + switch (left.kind) { + case 69: + var exportDeclaration = resolver.getReferencedExportContainer(left); + if (exportDeclaration) { + return createExportExpression(left, node); + } + break; + case 171: + case 170: + if (hasExportedReferenceInDestructuringPattern(left)) { + return substituteDestructuring(node); + } + break; + } + return node; + } + function isExportedBinding(name) { + var container = resolver.getReferencedExportContainer(name); + return container && container.kind === 256; + } + function hasExportedReferenceInDestructuringPattern(node) { + switch (node.kind) { + case 69: + return isExportedBinding(node); + case 171: + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (hasExportedReferenceInObjectDestructuringElement(property)) { + return true; + } + } + break; + case 170: + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (hasExportedReferenceInArrayDestructuringElement(element)) { + return true; + } + } + break; + } + return false; + } + function hasExportedReferenceInObjectDestructuringElement(node) { + if (ts.isShorthandPropertyAssignment(node)) { + return isExportedBinding(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringElement(node.initializer); + } + else { + return false; + } + } + function hasExportedReferenceInArrayDestructuringElement(node) { + if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else { + return hasExportedReferenceInDestructuringElement(node); + } + } + function hasExportedReferenceInDestructuringElement(node) { + if (ts.isBinaryExpression(node)) { + var left = node.left; + return node.operatorToken.kind === 56 + && isDestructuringPattern(left) + && hasExportedReferenceInDestructuringPattern(left); + } + else if (ts.isIdentifier(node)) { + return isExportedBinding(node); + } + else if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else if (isDestructuringPattern(node)) { + return hasExportedReferenceInDestructuringPattern(node); + } + else { + return false; + } + } + function isDestructuringPattern(node) { + var kind = node.kind; + return kind === 69 + || kind === 171 + || kind === 170; + } + function substituteDestructuring(node) { + return ts.flattenDestructuringAssignment(context, node, true, hoistVariableDeclaration); + } + function substituteUnaryExpression(node) { + var operand = node.operand; + var operator = node.operator; + var substitute = ts.isIdentifier(operand) && + (node.kind === 186 || + (node.kind === 185 && (operator === 41 || operator === 42))); + if (substitute) { + var exportDeclaration = resolver.getReferencedExportContainer(operand); + if (exportDeclaration) { + var expr = ts.createPrefix(node.operator, operand, node); + setNodeEmitFlags(expr, 128); + var call = createExportExpression(operand, expr); + if (node.kind === 185) { + return call; + } + else { + return operator === 41 + ? ts.createSubtract(call, ts.createLiteral(1)) + : ts.createAdd(call, ts.createLiteral(1)); + } + } + } + return node; + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function addExportStarFunction(statements, localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); + } + statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(m)], undefined, ts.createBlock([ + ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, undefined) + ]), m, ts.createBlock([ + setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ])), + ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) + ], undefined, true))); + return exportStarFunction; + } + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; + return ts.createCall(exportFunctionForFile, undefined, [exportName, value]); + } + function createExportStatement(name, value) { + return ts.createStatement(createExportExpression(name, value)); + } + function createDeclarationExport(node) { + var declarationName = getDeclarationName(node); + var exportName = ts.hasModifier(node, 512) ? ts.createLiteral("default") : declarationName; + return createExportStatement(exportName, declarationName); + } + function createImportBinding(importDeclaration) { + var importAlias; + var name; + if (ts.isImportClause(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); + name = ts.createIdentifier("default"); + } + else if (ts.isImportSpecifier(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); + name = importDeclaration.propertyName || importDeclaration.name; + } + else { + return undefined; + } + if (name.originalKeywordKind && languageVersion === 0) { + return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); + } + else { + return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); + } + } + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + continue; + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + function getNameOfDependencyGroup(dependencyGroup) { + return dependencyGroup.name; + } + function recordExportName(name) { + if (!exportedLocalNames) { + exportedLocalNames = []; + } + exportedLocalNames.push(name); + } + function recordExportedFunctionDeclaration(node) { + if (!exportedFunctionDeclarations) { + exportedFunctionDeclarations = []; + } + exportedFunctionDeclarations.push(createDeclarationExport(node)); + } + function hoistBindingElement(node, isExported) { + if (ts.isOmittedExpression(node)) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + if (isExported) { + recordExportName(name); + } + } + else if (ts.isBindingPattern(name)) { + ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + } + } + function hoistExportedBindingElement(node) { + hoistBindingElement(node, true); + } + function hoistNonExportedBindingElement(node) { + hoistBindingElement(node, false); + } + function updateSourceFile(node, statements, nodeEmitFlags) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + setNodeEmitFlags(updated, nodeEmitFlags); + return updated; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES6Module(context) { + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 230: + return visitImportDeclaration(node); + case 229: + return visitImportEqualsDeclaration(node); + case 231: + return visitImportClause(node); + case 233: + case 232: + return visitNamedBindings(node); + case 234: + return visitImportSpecifier(node); + case 235: + return visitExportAssignment(node); + case 236: + return visitExportDeclaration(node); + case 237: + return visitNamedExports(node); + case 238: + return visitExportSpecifier(node); + } + return node; + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var original = ts.getOriginalNode(node); + return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, true); + if (node.exportClause === newExportClause) { + return node; + } + return newExportClause + ? ts.createExportDeclaration(undefined, undefined, newExportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); + if (node.elements === newExports) { + return node; + } + return newExports.length ? ts.createNamedExports(newExports) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + function visitImportEqualsDeclaration(node) { + return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitImportDeclaration(node) { + if (node.importClause) { + var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); + if (!newImportClause.name && !newImportClause.namedBindings) { + return undefined; + } + else if (newImportClause !== node.importClause) { + return ts.createImportDeclaration(undefined, undefined, newImportClause, node.moduleSpecifier); + } + } + return node; + } + function visitImportClause(node) { + var newDefaultImport = node.name; + if (!resolver.isReferencedAliasDeclaration(node)) { + newDefaultImport = undefined; + } + var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true); + return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings + ? ts.createImportClause(newDefaultImport, newNamedBindings) + : node; + } + function visitNamedBindings(node) { + if (node.kind === 232) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); + if (!newNamedImportElements || newNamedImportElements.length == 0) { + return undefined; + } + if (newNamedImportElements === node.elements) { + return node; + } + return ts.createNamedImports(newNamedImportElements); + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + } + ts.transformES6Module = transformES6Module; +})(ts || (ts = {})); +var ts; +(function (ts) { + var moduleTransformerMap = ts.createMap((_a = {}, + _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.System] = ts.transformSystemModule, + _a[ts.ModuleKind.AMD] = ts.transformModule, + _a[ts.ModuleKind.CommonJS] = ts.transformModule, + _a[ts.ModuleKind.UMD] = ts.transformModule, + _a[ts.ModuleKind.None] = ts.transformModule, + _a)); + function getTransformers(compilerOptions) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + transformers.push(ts.transformTypeScript); + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (jsx === 2) { + transformers.push(ts.transformJsx); + } + transformers.push(ts.transformES7); + if (languageVersion < 2) { + transformers.push(ts.transformES6); + transformers.push(ts.transformGenerators); + } + return transformers; + } + ts.getTransformers = getTransformers; + var nextTransformId = 1; + function transformFiles(resolver, host, sourceFiles, transformers) { + var transformId = nextTransformId; + nextTransformId++; + var tokenSourceMapRanges = ts.createMap(); + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var enabledSyntaxKindFeatures = new Array(289); + var parseTreeNodesWithAnnotations = []; + var lastTokenSourceMapRangeNode; + var lastTokenSourceMapRangeToken; + var lastTokenSourceMapRange; + var lexicalEnvironmentStackOffset = 0; + var hoistedVariableDeclarations; + var hoistedFunctionDeclarations; + var lexicalEnvironmentDisabled; + var context = { + getCompilerOptions: function () { return host.getCompilerOptions(); }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + getNodeEmitFlags: getNodeEmitFlags, + setNodeEmitFlags: setNodeEmitFlags, + getSourceMapRange: getSourceMapRange, + setSourceMapRange: setSourceMapRange, + getTokenSourceMapRange: getTokenSourceMapRange, + setTokenSourceMapRange: setTokenSourceMapRange, + getCommentRange: getCommentRange, + setCommentRange: setCommentRange, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + startLexicalEnvironment: startLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + onSubstituteNode: onSubstituteNode, + enableSubstitution: enableSubstitution, + isSubstitutionEnabled: isSubstitutionEnabled, + onEmitNode: onEmitNode, + enableEmitNotification: enableEmitNotification, + isEmitNotificationEnabled: isEmitNotificationEnabled + }; + var transformation = chain.apply(void 0, transformers)(context); + var transformed = ts.map(sourceFiles, transformSourceFile); + lexicalEnvironmentDisabled = true; + return { + getSourceFiles: function () { return transformed; }, + getTokenSourceMapRange: getTokenSourceMapRange, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + onSubstituteNode: context.onSubstituteNode, + onEmitNode: context.onEmitNode, + dispose: function () { + for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { + var node = parseTreeNodesWithAnnotations_1[_i]; + if (node.transformId === transformId) { + node.transformId = 0; + node.emitFlags = 0; + node.commentRange = undefined; + node.sourceMapRange = undefined; + } + } + parseTreeNodesWithAnnotations.length = 0; + } + }; + function transformSourceFile(sourceFile) { + if (ts.isDeclarationFile(sourceFile)) { + return sourceFile; + } + return transformation(sourceFile); + } + function enableSubstitution(kind) { + enabledSyntaxKindFeatures[kind] |= 1; + } + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + } + function onSubstituteNode(node, isExpression) { + return node; + } + function enableEmitNotification(kind) { + enabledSyntaxKindFeatures[kind] |= 2; + } + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 + || (getNodeEmitFlags(node) & 64) !== 0; + } + function onEmitNode(node, emit) { + emit(node); + } + function beforeSetAnnotation(node) { + if ((node.flags & 8) === 0 && node.transformId !== transformId) { + parseTreeNodesWithAnnotations.push(node); + node.transformId = transformId; + } + } + function getNodeEmitFlags(node) { + return node.emitFlags; + } + function setNodeEmitFlags(node, emitFlags) { + beforeSetAnnotation(node); + node.emitFlags = emitFlags; + return node; + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + function setSourceMapRange(node, range) { + beforeSetAnnotation(node); + node.sourceMapRange = range; + return node; + } + function getTokenSourceMapRange(node, token) { + if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { + return lastTokenSourceMapRange; + } + var range; + var current = node; + while (current) { + range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; + if (range !== undefined) { + break; + } + current = current.original; + } + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + return range; + } + function setTokenSourceMapRange(node, token, range) { + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; + return node; + } + function getCommentRange(node) { + return node.commentRange || node; + } + function setCommentRange(node, range) { + beforeSetAnnotation(node); + node.commentRange = range; + return node; + } + function hoistVariableDeclaration(name) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var decl = ts.createVariableDeclaration(name); + if (!hoistedVariableDeclarations) { + hoistedVariableDeclarations = [decl]; + } + else { + hoistedVariableDeclarations.push(decl); + } + } + function hoistFunctionDeclaration(func) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + if (!hoistedFunctionDeclarations) { + hoistedFunctionDeclarations = [func]; + } + else { + hoistedFunctionDeclarations.push(func); + } + } + function startLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentStackOffset++; + hoistedVariableDeclarations = undefined; + hoistedFunctionDeclarations = undefined; + } + function endLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + var statements; + if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { + if (hoistedFunctionDeclarations) { + statements = hoistedFunctionDeclarations.slice(); + } + if (hoistedVariableDeclarations) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + lexicalEnvironmentStackOffset--; + hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + return statements; + } + } + ts.transformFiles = transformFiles; + function chain(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + function compose(a, b, c, d, e) { + if (e) { + var args_4 = []; + for (var i = 0; i < arguments.length; i++) { + args_4[i] = arguments[i]; + } + return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + var _a; })(ts || (ts = {})); var ts; (function (ts) { @@ -29056,9 +42292,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -29147,11 +42381,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = {}; + usedTypeDirectiveReferences = ts.createMap(); } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { + if (!(directive in usedTypeDirectiveReferences)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -29176,7 +42410,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -29235,7 +42469,7 @@ var ts; if (declaration) { var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, false, true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -29303,7 +42537,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); emitEntityName(node.expression); if (node.typeArguments) { @@ -29372,15 +42606,15 @@ var ts; } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentIdentifiers, baseName)) { + if (!(baseName in currentIdentifiers)) { return baseName; } var count = 0; while (true) { count++; - var name_24 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_24)) { - return name_24; + var name_42 = baseName + "_" + count; + if (!(name_42 in currentIdentifiers)) { + return name_42; } } } @@ -29478,10 +42712,11 @@ var ts; } function emitModuleElementDeclarationFlags(node) { if (node.parent.kind === 256) { - if (node.flags & 1) { + var modifiers = ts.getModifierFlags(node); + if (modifiers & 1) { write("export "); } - if (node.flags & 512) { + if (modifiers & 512) { write("default "); } else if (node.kind !== 222 && !noDeclare) { @@ -29508,7 +42743,7 @@ var ts; } function writeImportEqualsDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { write("export "); } write("import "); @@ -29544,7 +42779,7 @@ var ts; } function writeImportDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (ts.hasModifier(node, 1)) { write("export "); } write("import "); @@ -29635,7 +42870,7 @@ var ts; write("global "); } else { - if (node.flags & 4096) { + if (node.flags & 16) { write("namespace "); } else { @@ -29718,7 +42953,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 && (node.parent.flags & 8); + return node.parent.kind === 147 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -29760,7 +42995,7 @@ var ts; break; case 147: case 146: - if (node.parent.flags & 32) { + if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 221) { @@ -29795,7 +43030,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93) { @@ -29827,7 +43062,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 92) { + if (ts.hasModifier(param, 92)) { emitPropertyDeclaration(param); } }); @@ -29835,7 +43070,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 128) { + if (ts.hasModifier(node, 128)) { write("abstract "); } write("class "); @@ -29881,7 +43116,7 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); emitVariableDeclaration(node); write(";"); writeLine(); @@ -29893,13 +43128,18 @@ var ts; } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || node.kind === 142) && ts.hasQuestionToken(node)) { + if ((node.kind === 145 || node.kind === 144 || + (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 8)) { + else if (resolver.isLiteralConstDeclaration(node)) { + write(" = "); + resolver.writeLiteralConstValue(node, writer); + } + else if (!ts.hasModifier(node, 8)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -29913,7 +43153,7 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } else if (node.kind === 145 || node.kind === 144) { - if (node.flags & 32) { + if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -30006,9 +43246,9 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64)); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); writeTextOfNode(currentText, node.name); - if (!(node.flags & 8)) { + if (!ts.hasModifier(node, 8)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -30035,7 +43275,7 @@ var ts; function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 150) { - if (accessorWithTypeAnnotation.parent.flags & 32) { + if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -30052,7 +43292,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 32) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -30084,7 +43324,7 @@ var ts; emitModuleElementDeclarationFlags(node); } else if (node.kind === 147 || node.kind === 148) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } if (node.kind === 220) { write("function "); @@ -30111,7 +43351,7 @@ var ts; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; if (node.kind === 153) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { @@ -30142,7 +43382,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 148 && !(node.flags & 8)) { + else if (node.kind !== 148 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -30173,7 +43413,7 @@ var ts; break; case 147: case 146: - if (node.flags & 32) { + if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -30230,7 +43470,7 @@ var ts; node.parent.parent.kind === 159) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 8)) { + else if (!ts.hasModifier(node.parent, 8)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { @@ -30259,7 +43499,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 147: case 146: - if (node.parent.flags & 32) { + if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -30417,6283 +43657,725 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getResolvedExternalModuleName(host, file) { - return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); - } - ts.getResolvedExternalModuleName = getResolvedExternalModuleName; - function getExternalModuleNameFromDeclaration(host, resolver, declaration) { - var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || ts.isDeclarationFile(file)) { - return undefined; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { + if (compilerOptions.extendedDiagnostics) { + return createSourceMapWriterWithExtendedDiagnostics(host, writer); + } + return createSourceMapWriterWorker(host, writer); + } + else { + return getNullSourceMapWriter(); } - return getResolvedExternalModuleName(host, file); } - ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = { - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 + ts.createSourceMapWriter = createSourceMapWriter; + var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { }, + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitPos: function (pos) { }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + changeEmitSourcePos: function () { }, + stopOverridingSpan: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + var defaultLastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 }; + function createSourceMapWriterWorker(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; + var currentSourceFile; + var currentSourceText; + var sourceMapDir; + var stopOverridingSpan = false; + var modifyLastSourcePos = false; + var sourceMapSourceIndex; + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + var sourceMapData; + var disableDepth; + return { + initialize: initialize, + reset: reset, + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + emitTokenStart: emitTokenStart, + emitTokenEnd: emitTokenEnd, + changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: function () { return stopOverridingSpan = true; }, + getText: getText, + getSourceMappingURL: getSourceMappingURL + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + currentSourceText = undefined; + disableDepth = 0; + sourceMapSourceIndex = -1; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; + lastEncodedNameIndex = 0; + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + disableDepth = 0; + } + function enable() { + if (disableDepth > 0) { + disableDepth--; + } + } + function disable() { + disableDepth++; + } + function updateLastEncodedAndRecordedSpans() { + if (modifyLastSourcePos) { + modifyLastSourcePos = false; + lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; + lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; + sourceMapData.sourceMapDecodedMappings.pop(); + lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? + sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : + defaultLastEncodedSourceMapSpan; + var sourceMapMappings = sourceMapData.sourceMapMappings; + var lenthToSet = sourceMapMappings.length - 1; + for (; lenthToSet >= 0; lenthToSet--) { + var currentChar = sourceMapMappings.charAt(lenthToSet); + if (currentChar === ",") { + break; + } + if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { + break; + } + } + sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); + } + } + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + return; + } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + stopOverridingSpan = false; + } + else if (!stopOverridingSpan) { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } + } + function getStartPosPastDecorators(range) { + var rangeHasDecorators = !!range.decorators; + return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); + } + function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(getStartPosPastDecorators(range)); + } + if (ignoreChildrenCallback(contextNode)) { + disable(); + } + } + else { + emitPos(getStartPosPastDecorators(range)); + } + } + function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (ignoreChildrenCallback(contextNode)) { + enable(); + } + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(range.end); + } + } + else { + emitPos(range.end); + } + stopOverridingSpan = false; + } + function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return ts.skipTrivia(currentSourceText, tokenStartPos); + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenStartPos = range.pos; + } + } + tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); + emitPos(tokenStartPos); + return tokenStartPos; + } + function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return tokenEndPos; + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenEndPos = range.end; + } + } + emitPos(tokenEndPos); + return tokenEndPos; + } + function changeEmitSourcePos() { + ts.Debug.assert(!modifyLastSourcePos); + modifyLastSourcePos = true; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentSourceText = currentSourceFile.text; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + function createSourceMapWriterWithExtendedDiagnostics(host, writer) { + var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; + return { + initialize: initialize, + reset: reset, + getSourceMapData: getSourceMapData, + setSourceFile: setSourceFile, + emitPos: function (pos) { + ts.performance.mark("sourcemapStart"); + emitPos(pos); + ts.performance.measure("sourceMapTime", "sourcemapStart"); + }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitStart"); + emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); + }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitEnd"); + emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); + }, + emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenStart"); + tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); + return tokenStartPos; + }, + emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenEnd"); + tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); + return tokenEndPos; + }, + changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: stopOverridingSpan, + getText: getText, + getSourceMappingURL: getSourceMappingURL + }; + } + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function createCommentWriter(host, writer, sourceMap) { + var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; + var newLine = host.getNewLine(); + var emitPos = sourceMap.emitPos; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentSourceFile; + var currentText; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var disabled = compilerOptions.removeComments; + return { + reset: reset, + setSourceFile: setSourceFile, + emitNodeWithComments: emitNodeWithComments, + emitBodyWithDetachedComments: emitBodyWithDetachedComments, + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + }; + function emitNodeWithComments(node, emitCallback) { + if (disabled) { + emitCallback(node); + return; + } + if (node) { + var _a = node.commentRange || node, pos = _a.pos, end = _a.end; + var emitFlags = node.emitFlags; + if ((pos < 0 && end < 0) || (pos === end)) { + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + } + else { + if (extendedDiagnostics) { + ts.performance.mark("preEmitNodeWithComment"); + } + var isEmittedNode = node.kind !== 287; + var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 32768) !== 0; + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if (!skipLeadingComments) { + containerPos = pos; + } + if (!skipTrailingComments) { + containerEnd = end; + if (node.kind === 219) { + declarationListContainerEnd = end; + } + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitNodeWithComment"); + } + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitNodeWithComment"); + } + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitNodeWithComment"); + } + } + } + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + if (extendedDiagnostics) { + ts.performance.mark("preEmitBodyWithDetachedComments"); + } + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = node.emitFlags; + var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); + } + if (emitFlags & 65536) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + } + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, true); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + } + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); + hasWrittenComment = true; + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + if (!writer.isAtStartOfLine()) { + writer.write(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos) { + if (disabled) { + return; + } + if (extendedDiagnostics) { + ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); + } + forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); + } + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + if (containerPos === -1 || pos !== containerPos) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { + ts.forEachTrailingCommentRange(currentText, end, cb); + } + } + function reset() { + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentText = currentSourceFile.text; + currentLineMap = ts.getLineStarts(currentSourceFile); + detachedCommentsInfo = undefined; + } + function disableCommentsAndEmit(node, emitCallback) { + if (disabled) { + emitCallback(node); + } + else { + disabled = true; + emitCallback(node); + disabled = false; + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + function isTripleSlashComment(commentPos, commentEnd) { + if (currentText.charCodeAt(commentPos + 1) === 47 && + commentPos + 2 < commentEnd && + currentText.charCodeAt(commentPos + 2) === 47) { + var textSubStr = currentText.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? + true : false; + } + return false; + } + } + ts.createCommentWriter = createCommentWriter; +})(ts || (ts = {})); +var ts; +(function (ts) { function emitFiles(resolver, host, targetSourceFile) { + var delimiters = createDelimiterMap(); + var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; + var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; + var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; + var superHelper = "\nconst _super = name => super[name];"; + var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var emitSkipped = false; var newLine = host.getNewLine(); - var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); + var transformers = ts.getTransformers(compilerOptions); + var writer = ts.createTextWriter(newLine); + var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = ts.createSourceMapWriter(host, writer); + var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var comments = ts.createCommentWriter(host, writer, sourceMap); + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var nodeIdToGeneratedName; + var autoGeneratedIdToGeneratedName; + var generatedNameSet; + var tempFlags; + var currentSourceFile; + var currentText; + var currentFileIdentifiers; + var extendsEmitted; + var assignEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; + var isOwnFileEmit; + var emitSkipped = false; + ts.performance.mark("beforeTransform"); + var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.measure("transformTime", "beforeTransform"); + var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); + transformed.dispose(); + ts.performance.measure("printTime", "beforePrint"); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList }; - function isUniqueLocalName(name, container) { - for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name)) { - if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { - return false; - } - } - } - return true; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function hoistVariableDeclarationFromLoop(state, declaration) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(declaration.name); - function visit(node) { - if (node.kind === 69) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _a = 0, _b = node.elements; _a < _b.length; _a++) { - var element = _b[_a]; - visit(element.name); - } - } - } - } - function createFileEmitter() { - var writer = ts.createTextWriter(newLine); - var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; - var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); - var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; - var currentSourceFile; - var currentText; - var currentLineMap; - var currentFileIdentifiers; - var renamedDependencies; - var isEs6Module; - var isCurrentFileExternalModule; - var exportFunctionForFile; - var contextObjectForFile; - var generatedNameSet; - var nodeToGeneratedName; - var computedPropertyNamesToGeneratedNames; - var decoratedClassAliases; - var convertedLoopState; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; - var tempFlags = 0; - var tempVariables; - var tempParameters; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var detachedCommentsInfo; - var sourceMapData; - var isOwnFileEmit; - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; - var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, - _a[ts.ModuleKind.ES6] = emitES6Module, - _a[ts.ModuleKind.AMD] = emitAMDModule, - _a[ts.ModuleKind.System] = emitSystemModule, - _a[ts.ModuleKind.UMD] = emitUMDModule, - _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, - _a - ); - var bundleEmitDelegates = (_b = {}, - _b[ts.ModuleKind.ES6] = function () { }, - _b[ts.ModuleKind.AMD] = emitAMDModule, - _b[ts.ModuleKind.System] = emitSystemModule, - _b[ts.ModuleKind.UMD] = function () { }, - _b[ts.ModuleKind.CommonJS] = function () { }, - _b - ); - return doEmit; - function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = {}; - nodeToGeneratedName = []; - decoratedClassAliases = []; - isOwnFileEmit = !isBundledEmit; - if (isBundledEmit && modulekind) { - ts.forEach(sourceFiles, emitEmitHelpers); - } - ts.forEach(sourceFiles, emitSourceFile); - writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); - if (sourceMappingURL) { - write("//# sourceMappingURL=" + sourceMappingURL); - } - writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles); - sourceMap.reset(); - writer.reset(); - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - generatedNameSet = undefined; - nodeToGeneratedName = undefined; - decoratedClassAliases = undefined; - computedPropertyNamesToGeneratedNames = undefined; - convertedLoopState = undefined; - extendsEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; - assignEmitted = false; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = undefined; - detachedCommentsInfo = undefined; - sourceMapData = undefined; - isEs6Module = false; - renamedDependencies = undefined; - isCurrentFileExternalModule = false; - } - function emitSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = sourceFile.text; - currentLineMap = ts.getLineStarts(sourceFile); - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; - renamedDependencies = sourceFile.renamedDependencies; - currentFileIdentifiers = sourceFile.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - setSourceFile(sourceFile); - emitNodeWithCommentsAndWithoutSourcemap(sourceFile); - } - function isUniqueName(name) { - return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); - } - function makeTempVariableName(flags) { - if (flags && !(tempFlags & flags)) { - var name_25 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_25)) { - tempFlags |= flags; - return name_25; - } - } - while (true) { - var count = tempFlags & 268435455; - tempFlags++; - if (count !== 8 && count !== 13) { - var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_26)) { - return name_26; - } - } - } - } - function makeUniqueName(baseName) { - if (baseName.charCodeAt(baseName.length - 1) !== 95) { - baseName += "_"; - } - var i = 1; - while (true) { - var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - return generatedNameSet[generatedName] = generatedName; - } - i++; - } - } - function generateNameForModuleOrEnum(node) { - var name = node.name.text; - return isUniqueLocalName(name, node) ? name : makeUniqueName(name); - } - function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - return makeUniqueName(baseName); - } - function generateNameForExportDefault() { - return makeUniqueName("default"); - } - function generateNameForClassExpression() { - return makeUniqueName("class"); - } - function generateNameForNode(node) { - switch (node.kind) { - case 69: - return makeUniqueName(node.text); - case 225: - case 224: - return generateNameForModuleOrEnum(node); - case 230: - case 236: - return generateNameForImportOrExportDeclaration(node); - case 220: - case 221: - case 235: - return generateNameForExportDefault(); - case 192: - return generateNameForClassExpression(); - default: - ts.Debug.fail(); - } - } - function getGeneratedNameForNode(node) { - var id = ts.getNodeId(node); - return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); - } - function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark, sourceFiles) { - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); - } - ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark, sourceFiles); - } - function createTempVariable(flags) { - var result = ts.createSynthesizedNode(69); - result.text = makeTempVariableName(flags); - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function createAndRecordTempVariable(flags) { - var temp = createTempVariable(flags); - recordTempDeclaration(temp); - return temp; - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - function emitToken(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - emitPos(tokenStartPos); - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - var tokenEndPos = tokenStartPos + tokenString.length; - emitPos(tokenEndPos); - return tokenEndPos; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitParenthesizedIf(node, parenthesized) { - if (parenthesized) { - write("("); - } - emit(node); - if (parenthesized) { - write(")"); - } - } - function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { - ts.Debug.assert(nodes.length > 0); - increaseIndent(); - if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - for (var i = 0, n = nodes.length; i < n; i++) { - if (i) { - if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { - write(", "); - } - else { - write(","); - writeLine(); - } - } - emit(nodes[i]); - } - if (nodes.hasTrailingComma && allowTrailingComma) { - write(","); - } - decreaseIndent(); - if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - } - function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) { - if (!emitNode) { - emitNode = emit; - } - for (var i = 0; i < count; i++) { - if (multiLine) { - if (i || leadingComma) { - write(","); - } - writeLine(); - } - else { - if (i || leadingComma) { - write(", "); - } - } - var node = nodes[start + i]; - emitTrailingCommentsOfPosition(node.pos); - emitNode(node); - leadingComma = true; - } - if (trailingComma) { - write(","); - } - if (multiLine && !noTrailingNewLine) { - writeLine(); - } - return count; - } - function emitCommaList(nodes) { - if (nodes) { - emitList(nodes, 0, nodes.length, false, false); - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(node, text) { - if (node.kind === 8 && text.length > 1) { - switch (text.charCodeAt(1)) { - case 98: - case 66: - case 111: - case 79: - return true; - } - } - return false; - } - function emitLiteral(node) { - var text = getLiteralText(node); - if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (languageVersion < 2 && isBinaryOrOctalIntegerLiteral(node, text)) { - write(node.text); - } - else { - write(text); - } - } - function getLiteralText(node) { - if (languageVersion < 2 && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { - return getQuotedEscapedLiteralText('"', node.text, '"'); - } - if (node.parent) { - return ts.getTextOfNodeFromSourceText(currentText, node); - } - switch (node.kind) { - case 9: - return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11: - return getQuotedEscapedLiteralText("`", node.text, "`"); - case 12: - return getQuotedEscapedLiteralText("`", node.text, "${"); - case 13: - return getQuotedEscapedLiteralText("}", node.text, "${"); - case 14: - return getQuotedEscapedLiteralText("}", node.text, "`"); - case 8: - return node.text; - } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); - } - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; - } - function emitDownlevelRawTemplateLiteral(node) { - var text = ts.getTextOfNodeFromSourceText(currentText, node); - var isLast = node.kind === 11 || node.kind === 14; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - text = text.replace(/\r\n?/g, "\n"); - text = ts.escapeString(text); - write("\"" + text + "\""); - } - function emitDownlevelTaggedTemplateArray(node, literalEmitter) { - write("["); - if (node.template.kind === 11) { - literalEmitter(node.template); - } - else { - literalEmitter(node.template.head); - ts.forEach(node.template.templateSpans, function (child) { - write(", "); - literalEmitter(child.literal); - }); - } - write("]"); - } - function emitDownlevelTaggedTemplate(node) { - var tempVariable = createAndRecordTempVariable(0); - write("("); - emit(tempVariable); - write(" = "); - emitDownlevelTaggedTemplateArray(node, emit); - write(", "); - emit(tempVariable); - write(".raw = "); - emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral); - write(", "); - emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); - write("("); - emit(tempVariable); - if (node.template.kind === 189) { - ts.forEach(node.template.templateSpans, function (templateSpan) { - write(", "); - var needsParens = templateSpan.expression.kind === 187 - && templateSpan.expression.operatorToken.kind === 24; - emitParenthesizedIf(templateSpan.expression, needsParens); - }); - } - write("))"); - } - function emitTemplateExpression(node) { - if (languageVersion >= 2) { - ts.forEachChild(node, emit); - return; - } - var emitOuterParens = ts.isExpression(node.parent) - && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - var headEmitted = false; - if (shouldEmitTemplateHead()) { - emitLiteral(node.head); - headEmitted = true; - } - for (var i = 0, n = node.templateSpans.length; i < n; i++) { - var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 178 - && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; - if (i > 0 || headEmitted) { - write(" + "); - } - emitParenthesizedIf(templateSpan.expression, needsParens); - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - } - if (emitOuterParens) { - write(")"); - } - function shouldEmitTemplateHead() { - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 174: - case 175: - return parent.expression === template; - case 176: - case 178: - return false; - default: - return comparePrecedenceToBinaryPlus(parent) !== -1; - } - } - function comparePrecedenceToBinaryPlus(expression) { - switch (expression.kind) { - case 187: - switch (expression.operatorToken.kind) { - case 37: - case 39: - case 40: - return 1; - case 35: - case 36: - return 0; - default: - return -1; - } - case 190: - case 188: - return -1; - default: - return 1; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - function jsxEmitReact(node) { - function emitTagName(name) { - if (name.kind === 69 && ts.isIntrinsicJsxName(name.text)) { - write('"'); - emit(name); - write('"'); - } - else { - emit(name); - } - } - function emitAttributeName(name) { - if (/^[A-Za-z_]\w*$/.test(name.text)) { - emit(name); - } - else { - write('"'); - emit(name); - write('"'); - } - } - function emitJsxAttribute(node) { - emitAttributeName(node.name); - write(": "); - if (node.initializer) { - emit(node.initializer); - } - else { - write("true"); - } - } - function emitJsxElement(openingNode, children) { - var syntheticReactRef = ts.createSynthesizedNode(69); - syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; - syntheticReactRef.parent = openingNode; - emitLeadingComments(openingNode); - emitExpressionIdentifier(syntheticReactRef); - write(".createElement("); - emitTagName(openingNode.tagName); - write(", "); - if (openingNode.attributes.length === 0) { - write("null"); - } - else { - var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 247; })) { - write("__assign("); - var haveOpenedObjectLiteral = false; - for (var i = 0; i < attrs.length; i++) { - if (attrs[i].kind === 247) { - if (i === 0) { - write("{}, "); - } - if (haveOpenedObjectLiteral) { - write("}"); - haveOpenedObjectLiteral = false; - } - if (i > 0) { - write(", "); - } - emit(attrs[i].expression); - } - else { - ts.Debug.assert(attrs[i].kind === 246); - if (haveOpenedObjectLiteral) { - write(", "); - } - else { - haveOpenedObjectLiteral = true; - if (i > 0) { - write(", "); - } - write("{"); - } - emitJsxAttribute(attrs[i]); - } - } - if (haveOpenedObjectLiteral) - write("}"); - write(")"); - } - else { - write("{"); - for (var i = 0, n = attrs.length; i < n; i++) { - if (i > 0) { - write(", "); - } - emitJsxAttribute(attrs[i]); - } - write("}"); - } - } - if (children) { - var firstChild = void 0; - var multipleEmittableChildren = false; - for (var i = 0, n = children.length; i < n; i++) { - var jsxChild = children[i]; - if (isJsxChildEmittable(jsxChild)) { - if (!firstChild) { - write(", "); - firstChild = jsxChild; - } - else { - if (!multipleEmittableChildren) { - multipleEmittableChildren = true; - increaseIndent(); - writeLine(); - emit(firstChild); - } - write(", "); - writeLine(); - emit(jsxChild); - } - } - } - if (multipleEmittableChildren) { - decreaseIndent(); - } - else if (firstChild) { - if (firstChild.kind !== 241 && firstChild.kind !== 242) { - emit(firstChild); - } - else { - increaseIndent(); - writeLine(); - emit(firstChild); - writeLine(); - decreaseIndent(); - } - } - } - write(")"); - emitTrailingComments(openingNode); - } - if (node.kind === 241) { - emitJsxElement(node.openingElement, node.children); - } - else { - ts.Debug.assert(node.kind === 242); - emitJsxElement(node); - } - } - function jsxEmitPreserve(node) { - function emitJsxAttribute(node) { - emit(node.name); - if (node.initializer) { - write("="); - emit(node.initializer); - } - } - function emitJsxSpreadAttribute(node) { - write("{..."); - emit(node.expression); - write("}"); - } - function emitAttributes(attribs) { - for (var i = 0, n = attribs.length; i < n; i++) { - if (i > 0) { - write(" "); - } - if (attribs[i].kind === 247) { - emitJsxSpreadAttribute(attribs[i]); - } - else { - ts.Debug.assert(attribs[i].kind === 246); - emitJsxAttribute(attribs[i]); - } - } - } - function emitJsxOpeningOrSelfClosingElement(node) { - write("<"); - emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 242)) { - write(" "); - } - emitAttributes(node.attributes); - if (node.kind === 242) { - write("/>"); - } - else { - write(">"); - } - } - function emitJsxClosingElement(node) { - write(""); - } - function emitJsxElement(node) { - emitJsxOpeningOrSelfClosingElement(node.openingElement); - for (var i = 0, n = node.children.length; i < n; i++) { - emit(node.children[i]); - } - emitJsxClosingElement(node.closingElement); - } - if (node.kind === 241) { - emitJsxElement(node); - } - else { - ts.Debug.assert(node.kind === 242); - emitJsxOpeningOrSelfClosingElement(node); - } - } - function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 169); - if (node.kind === 9) { - emitLiteral(node); - } - else if (node.kind === 140) { - if (ts.nodeIsDecorated(node.parent)) { - if (!computedPropertyNamesToGeneratedNames) { - computedPropertyNamesToGeneratedNames = []; - } - var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)]; - if (generatedName) { - write(generatedName); - return; - } - generatedName = createAndRecordTempVariable(0).text; - computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName; - write(generatedName); - write(" = "); - } - emit(node.expression); - } - else { - write('"'); - if (node.kind === 8) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - write('"'); - } - } - function isExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 170: - case 195: - case 184: - case 187: - case 174: - case 249: - case 140: - case 188: - case 143: - case 181: - case 204: - case 173: - case 235: - case 202: - case 194: - case 206: - case 207: - case 208: - case 203: - case 245: - case 242: - case 243: - case 247: - case 248: - case 175: - case 196: - case 178: - case 186: - case 185: - case 211: - case 254: - case 191: - case 213: - case 176: - case 197: - case 215: - case 177: - case 182: - case 183: - case 205: - case 212: - case 190: - return true; - case 169: - case 255: - case 142: - case 253: - case 145: - case 218: - return parent.initializer === node; - case 172: - return parent.expression === node; - case 180: - case 179: - return parent.body === node; - case 229: - return parent.moduleReference === node; - case 139: - return parent.left === node; - } - return false; - } - function emitExpressionIdentifier(node) { - var container = resolver.getReferencedExportContainer(node); - if (container) { - if (container.kind === 256) { - if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - else { - write(getGeneratedNameForNode(container)); - write("."); - } - } - else { - if (modulekind !== ts.ModuleKind.ES6) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (declaration.kind === 231) { - write(getGeneratedNameForNode(declaration.parent)); - write(languageVersion === 0 ? '["default"]' : ".default"); - return; - } - else if (declaration.kind === 234) { - write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_27 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); - if (languageVersion === 0 && identifier === "default") { - write('["default"]'); - } - else { - write("."); - write(identifier); - } - return; - } - } - } - if (languageVersion < 2) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - else if (resolver.getNodeCheckFlags(node) & 1048576) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; - if (classAlias !== undefined) { - write(classAlias); - return; - } - } - } - } - if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { - if (languageVersion < 2) { - var parent_13 = node.parent; - switch (parent_13.kind) { - case 169: - case 221: - case 224: - case 218: - return parent_13.name === node && resolver.isDeclarationWithCollidingName(parent_13); - } - } - return false; - } - function getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node) { - if (languageVersion >= 2) { - var parent_14 = node.parent; - if (parent_14.kind === 172 && parent_14.expression === node) { - parent_14 = parent_14.parent; - while (parent_14 && parent_14.kind !== 145) { - parent_14 = parent_14.parent; - } - return parent_14 && parent_14.kind === 145 && (parent_14.flags & 32) !== 0 && - parent_14.parent.kind === 192 ? parent_14.parent : undefined; - } - } - return undefined; - } - function emitIdentifier(node) { - if (convertedLoopState) { - if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_28); - return; - } - } - if (!node.parent) { - write(node.text); - } - else if (isExpressionIdentifier(node)) { - var classExpression = getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node); - if (classExpression) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration === classExpression) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - emitExpressionIdentifier(node); - } - else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { - write(getGeneratedNameForNode(node)); - } - else if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2) { - write("_this"); - } - else if (convertedLoopState) { - write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); - } - else { - write("this"); - } - } - function emitSuper(node) { - if (languageVersion >= 2) { - write("super"); - } - else { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 256) { - write("_super.prototype"); - } - else { - write("_super"); - } - } - } - function emitObjectBindingPattern(node) { - write("{ "); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write("]"); - } - function emitBindingElement(node) { - if (node.propertyName) { - emit(node.propertyName); - write(": "); - } - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emit(node.name); - } - else { - emitModuleMemberName(node); - } - emitOptional(" = ", node.initializer); - } - function emitSpreadElementExpression(node) { - write("..."); - emit(node.expression); - } - function emitYieldExpression(node) { - write(ts.tokenToString(114)); - if (node.asteriskToken) { - write("*"); - } - if (node.expression) { - write(" "); - emit(node.expression); - } - } - function emitAwaitExpression(node) { - var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); - if (needsParenthesis) { - write("("); - } - write(ts.tokenToString(114)); - write(" "); - emit(node.expression); - if (needsParenthesis) { - write(")"); - } - } - function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 187 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { - return true; - } - else if (node.parent.kind === 188 && node.parent.condition === node) { - return true; - } - return false; - } - function needsParenthesisForPropertyAccessOrInvocation(node) { - switch (node.kind) { - case 69: - case 170: - case 172: - case 173: - case 174: - case 178: - return false; - } - return true; - } - function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { - var pos = 0; - var group = 0; - var length = elements.length; - while (pos < length) { - if (group === 1 && useConcat) { - write(".concat("); - } - else if (group > 0) { - write(", "); - } - var e = elements[pos]; - if (e.kind === 191) { - e = e.expression; - emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); - pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 170) { - write(".slice()"); - } - } - else { - var i = pos; - while (i < length && elements[i].kind !== 191) { - i++; - } - write("["); - if (multiLine) { - increaseIndent(); - } - emitList(elements, pos, i - pos, multiLine, trailingComma && i === length); - if (multiLine) { - decreaseIndent(); - } - write("]"); - pos = i; - } - group++; - } - if (group > 1) { - if (useConcat) { - write(")"); - } - } - } - function isSpreadElementExpression(node) { - return node.kind === 191; - } - function emitArrayLiteral(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else if (languageVersion >= 2 || !ts.forEach(elements, isSpreadElementExpression)) { - write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, false); - write("]"); - } - else { - emitListWithSpread(elements, true, node.multiLine, elements.hasTrailingComma, true); - } - } - function emitObjectLiteralBody(node, numElements) { - if (numElements === 0) { - write("{}"); - return; - } - write("{"); - if (numElements > 0) { - var properties = node.properties; - if (numElements === properties.length) { - emitLinePreservingList(node, properties, languageVersion >= 1, true); - } - else { - var multiLine = node.multiLine; - if (!multiLine) { - write(" "); - } - else { - increaseIndent(); - } - emitList(properties, 0, numElements, multiLine, false); - if (!multiLine) { - write(" "); - } - else { - decreaseIndent(); - } - } - } - write("}"); - } - function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = node.multiLine; - var properties = node.properties; - write("("); - if (multiLine) { - increaseIndent(); - } - var tempVar = createAndRecordTempVariable(0); - emit(tempVar); - write(" = "); - emitObjectLiteralBody(node, firstComputedPropertyIndex); - for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); - var property = properties[i]; - emitStart(property); - if (property.kind === 149 || property.kind === 150) { - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property !== accessors.firstAccessor) { - continue; - } - write("Object.defineProperty("); - emit(tempVar); - write(", "); - emitStart(property.name); - emitExpressionForPropertyName(property.name); - emitEnd(property.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("})"); - emitEnd(property); - } - else { - emitLeadingComments(property); - emitStart(property.name); - emit(tempVar); - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - if (property.kind === 253) { - emit(property.initializer); - } - else if (property.kind === 254) { - emitExpressionIdentifier(property.name); - } - else if (property.kind === 147) { - emitFunctionDeclaration(property); - } - else { - ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); - } - } - emitEnd(property); - } - writeComma(); - emit(tempVar); - if (multiLine) { - decreaseIndent(); - writeLine(); - } - write(")"); - function writeComma() { - if (multiLine) { - write(","); - writeLine(); - } - else { - write(", "); - } - } - } - function emitObjectLiteral(node) { - var properties = node.properties; - if (languageVersion < 2) { - var numProperties = properties.length; - var numInitialNonComputedProperties = numProperties; - for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 140) { - numInitialNonComputedProperties = i; - break; - } - } - var hasComputedProperty = numInitialNonComputedProperties !== properties.length; - if (hasComputedProperty) { - emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); - return; - } - } - emitObjectLiteralBody(node, properties.length); - } - function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(187, startsOnNewLine); - result.operatorToken = ts.createSynthesizedNode(operator); - result.left = left; - result.right = right; - return result; - } - function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(172); - result.expression = parenthesizeForAccess(expression); - result.name = name; - return result; - } - function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(173); - result.expression = parenthesizeForAccess(expression); - result.argumentExpression = argumentExpression; - return result; - } - function parenthesizeForAccess(expr) { - while (expr.kind === 177 || - expr.kind === 195 || - expr.kind === 196) { - expr = expr.expression; - } - if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 175 && - expr.kind !== 8) { - return expr; - } - var node = ts.createSynthesizedNode(178); - node.expression = expr; - return node; - } - function emitComputedPropertyName(node) { - write("["); - emitExpressionForPropertyName(node); - write("]"); - } - function emitMethod(node) { - if (languageVersion >= 2 && node.asteriskToken) { - write("*"); - } - emit(node.name); - if (languageVersion < 2) { - write(": function "); - } - emitSignatureAndBody(node); - } - function emitPropertyAssignment(node) { - emit(node.name); - write(": "); - emitTrailingCommentsOfPosition(node.initializer.pos); - emit(node.initializer); - } - function isExportReference(node) { - var container = resolver.getReferencedExportContainer(node); - return !!container; - } - function isImportedReference(node) { - var declaration = resolver.getReferencedImportDeclaration(node); - return declaration && (declaration.kind === 231 || declaration.kind === 234); - } - function emitShorthandPropertyAssignment(node) { - writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { - write(": "); - emitExpressionIdentifier(node.name); - } - if (languageVersion >= 2 && node.objectAssignmentInitializer) { - write(" = "); - emit(node.objectAssignmentInitializer); - } - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(constantValue.toString()); - if (!compilerOptions.removeComments) { - var propertyName = node.kind === 172 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return node.kind === 172 || node.kind === 173 - ? resolver.getConstantValue(node) - : undefined; - } - function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) { - var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); - var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); - if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { - increaseIndent(); - writeLine(); - return true; - } - else { - if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); - } - return false; - } - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 && - node.expression.kind === 95 && - isInAsyncMethodWithSuperInES6(node)) { - var name_29 = ts.createSynthesizedNode(9); - name_29.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_29); - return; - } - emit(node.expression); - var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; - var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); - var shouldEmitSpace = false; - if (!indentedBeforeDot) { - if (node.expression.kind === 8) { - var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); - shouldEmitSpace = text.indexOf(ts.tokenToString(21)) < 0; - } - else { - var constantValue = tryGetConstEnumValue(node.expression); - shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; - } - } - if (shouldEmitSpace) { - write(" ."); - } - else { - write("."); - } - var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); - emit(node.name); - decreaseIndentIf(indentedBeforeDot, indentedAfterDot); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitQualifiedNameAsExpression(node, useFallback) { - if (node.left.kind === 69) { - emitEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = createAndRecordTempVariable(0); - write("("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(node.left, true); - write(") && "); - emitNodeWithoutSourceMap(temp); - } - else { - emitEntityNameAsExpression(node.left, false); - } - write("."); - emit(node.right); - } - function emitEntityNameAsExpression(node, useFallback) { - switch (node.kind) { - case 69: - if (useFallback) { - write("typeof "); - emitExpressionIdentifier(node); - write(" !== 'undefined' && "); - } - emitExpressionIdentifier(node); - break; - case 139: - emitQualifiedNameAsExpression(node, useFallback); - break; - default: - emitNodeWithoutSourceMap(node); - break; - } - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 && - node.expression.kind === 95 && - isInAsyncMethodWithSuperInES6(node)) { - emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 191; }); - } - function skipParentheses(node) { - while (node.kind === 178 || - node.kind === 177 || - node.kind === 195 || - node.kind === 196) { - node = node.expression; - } - return node; - } - function emitCallTarget(node) { - if (node.kind === 69 || node.kind === 97 || node.kind === 95) { - emit(node); - return node; - } - var temp = createAndRecordTempVariable(0); - write("("); - emit(temp); - write(" = "); - emit(node); - write(")"); - return temp; - } - function emitCallWithSpread(node) { - var target; - var expr = skipParentheses(node.expression); - if (expr.kind === 172) { - target = emitCallTarget(expr.expression); - write("."); - emit(expr.name); - } - else if (expr.kind === 173) { - target = emitCallTarget(expr.expression); - write("["); - emit(expr.argumentExpression); - write("]"); - } - else if (expr.kind === 95) { - target = expr; - write("_super"); - } - else { - emit(node.expression); - } - write(".apply("); - if (target) { - if (target.kind === 95) { - emitThis(target); - } - else { - emit(target); - } - } - else { - write("void 0"); - } - write(", "); - emitListWithSpread(node.arguments, false, false, false, true); - write(")"); - } - function isInAsyncMethodWithSuperInES6(node) { - if (languageVersion === 2) { - var container = ts.getSuperContainer(node, false); - if (container && resolver.getNodeCheckFlags(container) & (2048 | 4096)) { - return true; - } - } - return false; - } - function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { - var container = ts.getSuperContainer(superNode, false); - var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096; - write("_super("); - emit(argumentExpression); - write(isSuperBinding ? ").value" : ")"); - } - function emitCallExpression(node) { - if (languageVersion < 2 && hasSpreadElement(node.arguments)) { - emitCallWithSpread(node); - return; - } - var expression = node.expression; - var superCall = false; - var isAsyncMethodWithSuper = false; - if (expression.kind === 95) { - emitSuper(expression); - superCall = true; - } - else { - superCall = ts.isSuperPropertyOrElementAccess(expression); - isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); - emit(expression); - } - if (superCall && (languageVersion < 2 || isAsyncMethodWithSuper)) { - write(".call("); - emitThis(expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - if (languageVersion === 1 && - node.arguments && - hasSpreadElement(node.arguments)) { - write("("); - var target = emitCallTarget(node.expression); - write(".bind.apply("); - emit(target); - write(", [void 0].concat("); - emitListWithSpread(node.arguments, false, false, false, false); - write(")))"); - write("()"); - } - else { - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - } - function emitTaggedTemplateExpression(node) { - if (languageVersion >= 2) { - emit(node.tag); - write(" "); - emit(node.template); - } - else { - emitDownlevelTaggedTemplate(node); - } - } - function emitParenExpression(node) { - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 180) { - if (node.expression.kind === 177 || - node.expression.kind === 195 || - node.expression.kind === 196) { - var operand = node.expression.expression; - while (operand.kind === 177 || - operand.kind === 195 || - operand.kind === 196) { - operand = operand.expression; - } - if (operand.kind !== 185 && - operand.kind !== 183 && - operand.kind !== 182 && - operand.kind !== 181 && - operand.kind !== 186 && - operand.kind !== 175 && - !(operand.kind === 174 && node.parent.kind === 175) && - !(operand.kind === 179 && node.parent.kind === 174) && - !(operand.kind === 8 && node.parent.kind === 172)) { - emit(operand); - return; - } - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(78)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(103)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(101)); - write(" "); - emit(node.expression); - } - function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) { - if (!isCurrentFileSystemExternalModule() || node.kind !== 69 || ts.nodeIsSynthesized(node)) { - return false; - } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 218 || node.parent.kind === 169); - var targetDeclaration = isVariableDeclarationOrBindingElement - ? node.parent - : resolver.getReferencedValueDeclaration(node); - return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, true); - } - function isNameOfExportedDeclarationInNonES6Module(node) { - if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { - return false; - } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); - } - function emitPrefixUnaryExpression(node) { - var isPlusPlusOrMinusMinus = (node.operator === 41 - || node.operator === 42); - var externalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - if (externalExportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - } - var internalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedDeclarationInNonES6Module(node.operand); - if (internalExportChanged) { - emitAliasEqual(node.operand); - } - write(ts.tokenToString(node.operator)); - if (node.operand.kind === 185) { - var operand = node.operand; - if (node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) { - write(" "); - } - else if (node.operator === 36 && (operand.operator === 36 || operand.operator === 42)) { - write(" "); - } - } - emit(node.operand); - if (externalExportChanged) { - write(")"); - } - } - function emitPostfixUnaryExpression(node) { - var externalExportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - var internalExportChanged = isNameOfExportedDeclarationInNonES6Module(node.operand); - if (externalExportChanged) { - write("(" + exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - write(ts.tokenToString(node.operator)); - emit(node.operand); - if (node.operator === 41) { - write(") - 1)"); - } - else { - write(") + 1)"); - } - } - else if (internalExportChanged) { - emitAliasEqual(node.operand); - emit(node.operand); - if (node.operator === 41) { - write(" += 1"); - } - else { - write(" -= 1"); - } - } - else { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - } - function shouldHoistDeclarationInSystemJsModule(node) { - return isSourceFileLevelDeclarationInSystemJsModule(node, false); - } - function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { - if (!node || !isCurrentFileSystemExternalModule()) { - return false; - } - var current = ts.getRootDeclaration(node).parent; - while (current) { - if (current.kind === 256) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); - } - else if (ts.isDeclaration(current)) { - return false; - } - else { - current = current.parent; - } - } - } - function emitExponentiationOperator(node) { - var leftHandSideExpression = node.left; - if (node.operatorToken.kind === 60) { - var synthesizedLHS = void 0; - var shouldEmitParentheses = false; - if (ts.isElementAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(173, false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); - synthesizedLHS.expression = identifier; - if (leftHandSideExpression.argumentExpression.kind !== 8 && - leftHandSideExpression.argumentExpression.kind !== 9) { - var tempArgumentExpression = createAndRecordTempVariable(268435456); - synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, true, leftHandSideExpression.expression); - } - else { - synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; - } - write(", "); - } - else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(172, false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); - synthesizedLHS.expression = identifier; - synthesizedLHS.name = leftHandSideExpression.name; - write(", "); - } - emit(synthesizedLHS || leftHandSideExpression); - write(" = "); - write("Math.pow("); - emit(synthesizedLHS || leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - if (shouldEmitParentheses) { - write(")"); - } - } - else { - write("Math.pow("); - emit(leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - } - } - function emitAliasEqual(name) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - emitStart(specifier.name); - emitContainingModuleName(specifier); - if (languageVersion === 0 && name.text === "default") { - write('["default"]'); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - } - emitEnd(specifier.name); - write(" = "); - } - return true; - } - function emitBinaryExpression(node) { - if (languageVersion < 2 && node.operatorToken.kind === 56 && - (node.left.kind === 171 || node.left.kind === 170)) { - emitDestructuring(node, node.parent.kind === 202); - } - else { - var isAssignment = ts.isAssignmentOperator(node.operatorToken.kind); - var externalExportChanged = isAssignment && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left); - if (externalExportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.left); - write("\", "); - } - var internalExportChanged = isAssignment && - isNameOfExportedDeclarationInNonES6Module(node.left); - if (internalExportChanged) { - emitAliasEqual(node.left); - } - if (node.operatorToken.kind === 38 || node.operatorToken.kind === 60) { - emitExponentiationOperator(node); - } - else { - emit(node.left); - var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 ? " " : undefined); - write(ts.tokenToString(node.operatorToken.kind)); - var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); - emit(node.right); - decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); - } - if (externalExportChanged) { - write(")"); - } - } - } - function synthesizedNodeStartsOnNewLine(node) { - return ts.nodeIsSynthesized(node) && node.startsOnNewLine; - } - function emitConditionalExpression(node) { - emit(node.condition); - var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); - write("?"); - var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); - emit(node.whenTrue); - decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); - write(":"); - var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); - emit(node.whenFalse); - decreaseIndentIf(indentedBeforeColon, indentedAfterColon); - } - function decreaseIndentIf(value1, value2) { - if (value1) { - decreaseIndent(); - } - if (value2) { - decreaseIndent(); - } - } - function isSingleLineEmptyBlock(node) { - if (node && node.kind === 199) { - var block = node; - return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); - } - } - function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - emitToken(15, node.pos); - write(" "); - emitToken(16, node.statements.end); - return; - } - emitToken(15, node.pos); - increaseIndent(); - if (node.kind === 226) { - ts.Debug.assert(node.parent.kind === 225); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 226) { - emitTempDeclarations(true); - } - decreaseIndent(); - writeLine(); - emitToken(16, node.statements.end); - } - function emitEmbeddedStatement(node) { - if (node.kind === 199) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 180); - write(";"); - } - function emitIfStatement(node) { - var endPos = emitToken(88, node.pos); - write(" "); - endPos = emitToken(17, endPos); - emit(node.expression); - emitToken(18, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(80, node.thenStatement.end); - if (node.elseStatement.kind === 203) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - } - function emitDoStatement(node) { - emitLoop(node, emitDoStatementWorker); - } - function emitDoStatementWorker(node, loop) { - write("do"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - if (node.statement.kind === 199) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - emitLoop(node, emitWhileStatementWorker); - } - function emitWhileStatementWorker(node, loop) { - write("while ("); - emit(node.expression); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function tryEmitStartOfVariableDeclarationList(decl) { - if (shouldHoistVariable(decl, true)) { - return false; - } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072) === 0) { - for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { - var varDecl = _b[_a]; - hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); - } - return false; - } - emitStart(decl); - if (decl && languageVersion >= 2) { - if (ts.isLet(decl)) { - write("let "); - } - else if (ts.isConst(decl)) { - write("const "); - } - else { - write("var "); - } - } - else { - write("var "); - } - return true; - } - function emitVariableDeclarationListSkippingUninitializedEntries(list) { - var started = false; - for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) { - var decl = _b[_a]; - if (!decl.initializer) { - continue; - } - if (!started) { - started = true; - } - else { - write(", "); - } - emit(decl); - } - return started; - } - function shouldConvertLoopBody(node) { - return languageVersion < 2 && - (resolver.getNodeCheckFlags(node) & 65536) !== 0; - } - function emitLoop(node, loopEmitter) { - var shouldConvert = shouldConvertLoopBody(node); - if (!shouldConvert) { - loopEmitter(node, undefined); - } - else { - var loop = convertLoopBody(node); - if (node.parent.kind === 214) { - emitLabelAndColon(node.parent); - } - loopEmitter(node, loop); - } - } - function convertLoopBody(node) { - var functionName = makeUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206: - case 207: - case 208: - var initializer = node.initializer; - if (initializer && initializer.kind === 219) { - loopInitializer = node.initializer; - } - break; - } - var loopParameters; - var loopOutParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072)) { - loopParameters = []; - for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { - var varDeclaration = _b[_a]; - processVariableDeclaration(varDeclaration.name); - } - } - var bodyIsBlock = node.statement.kind === 199; - var paramList = loopParameters ? loopParameters.join(", ") : ""; - writeLine(); - write("var " + functionName + " = function(" + paramList + ")"); - var convertedOuterLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (convertedOuterLoopState) { - if (convertedOuterLoopState.argumentsName) { - convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; - } - if (convertedOuterLoopState.thisName) { - convertedLoopState.thisName = convertedOuterLoopState.thisName; - } - if (convertedOuterLoopState.hoistedLocalVariables) { - convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; - } - } - write(" {"); - writeLine(); - increaseIndent(); - if (bodyIsBlock) { - emitLines(node.statement.statements); - } - else { - emit(node.statement); - } - writeLine(); - copyLoopOutParameters(convertedLoopState, 1, true); - decreaseIndent(); - writeLine(); - write("};"); - writeLine(); - if (loopOutParameters) { - write("var "); - for (var i = 0; i < loopOutParameters.length; i++) { - if (i !== 0) { - write(", "); - } - write(loopOutParameters[i].outParamName); - } - write(";"); - writeLine(); - } - if (convertedLoopState.argumentsName) { - if (convertedOuterLoopState) { - convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; - } - else { - write("var " + convertedLoopState.argumentsName + " = arguments;"); - writeLine(); - } - } - if (convertedLoopState.thisName) { - if (convertedOuterLoopState) { - convertedOuterLoopState.thisName = convertedLoopState.thisName; - } - else { - write("var " + convertedLoopState.thisName + " = this;"); - writeLine(); - } - } - if (convertedLoopState.hoistedLocalVariables) { - if (convertedOuterLoopState) { - convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; - } - else { - write("var "); - var seen = void 0; - for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { - var id = _d[_c]; - if (!seen) { - seen = {}; - } - else { - write(", "); - } - if (!ts.hasProperty(seen, id.text)) { - emit(id); - seen[id.text] = id.text; - } - } - write(";"); - writeLine(); - } - } - var currentLoopState = convertedLoopState; - convertedLoopState = convertedOuterLoopState; - return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function processVariableDeclaration(name) { - if (name.kind === 69) { - var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) - ? getGeneratedNameForNode(name) - : name.text; - loopParameters.push(nameText); - if (resolver.getNodeCheckFlags(name.parent) & 2097152) { - var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; - (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); - } - } - else { - for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { - var element = _b[_a]; - processVariableDeclaration(element.name); - } - } - } - } - function emitNormalLoopBody(node, emitAsEmbeddedStatement) { - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 | 4; - } - if (emitAsEmbeddedStatement) { - emitEmbeddedStatement(node.statement); - } - else if (node.statement.kind === 199) { - emitLines(node.statement.statements); - } - else { - writeLine(); - emit(node.statement); - } - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function copyLoopOutParameters(state, copyDirection, emitAsStatements) { - if (state.loopOutParameters) { - for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { - var outParam = _b[_a]; - if (copyDirection === 0) { - emitIdentifier(outParam.originalName); - write(" = " + outParam.outParamName); - } - else { - write(outParam.outParamName + " = "); - emitIdentifier(outParam.originalName); - } - if (emitAsStatements) { - write(";"); - writeLine(); - } - else { - write(", "); - } - } - } - } - function emitConvertedLoopCall(loop, emitAsBlock) { - if (emitAsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } - var isSimpleLoop = !(loop.state.nonLocalJumps & ~4) && - !loop.state.labeledNonLocalBreaks && - !loop.state.labeledNonLocalContinues; - var loopResult = makeUniqueName("state"); - if (!isSimpleLoop) { - write("var " + loopResult + " = "); - } - write(loop.functionName + "(" + loop.paramList + ");"); - writeLine(); - copyLoopOutParameters(loop.state, 0, true); - if (!isSimpleLoop) { - writeLine(); - if (loop.state.nonLocalJumps & 8) { - write("if (typeof " + loopResult + " === \"object\") "); - if (convertedLoopState) { - write("return " + loopResult + ";"); - convertedLoopState.nonLocalJumps |= 8; - } - else { - write("return " + loopResult + ".value;"); - } - writeLine(); - } - if (loop.state.nonLocalJumps & 2) { - write("if (" + loopResult + " === \"break\") break;"); - writeLine(); - } - emitDispatchTableForLabeledJumps(loopResult, loop.state, convertedLoopState); - } - if (emitAsBlock) { - writeLine(); - decreaseIndent(); - write("}"); - } - function emitDispatchTableForLabeledJumps(loopResultVariable, currentLoop, outerLoop) { - if (!currentLoop.labeledNonLocalBreaks && !currentLoop.labeledNonLocalContinues) { - return; - } - write("switch(" + loopResultVariable + ") {"); - increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, false, loopResultVariable, outerLoop); - decreaseIndent(); - writeLine(); - write("}"); - } - function emitDispatchEntriesForLabeledJumps(table, isBreak, loopResultVariable, outerLoop) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - writeLine(); - write("case \"" + labelMarker + "\": "); - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - if (isBreak) { - write("break "); - } - else { - write("continue "); - } - write(labelText + ";"); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - write("return " + loopResultVariable + ";"); - } - } - } - } - function emitForStatement(node) { - emitLoop(node, emitForStatementWorker); - } - function emitForStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - if (node.initializer && node.initializer.kind === 219) { - var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); - if (startIsEmitted) { - emitCommaList(variableDeclarationList.declarations); - } - else { - emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList); - } - } - else if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.incrementor); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 208) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } - else { - emitLoop(node, emitForInOrForOfStatementWorker); - } - } - function emitForInOrForOfStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - if (node.initializer.kind === 219) { - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList); - emit(variableDeclarationList.declarations[0]); - } - } - else { - emit(node.initializer); - } - if (node.kind === 207) { - write(" in "); - } - else { - write(" of "); - } - emit(node.expression); - emitToken(18, node.expression.end); - if (loop) { - emitConvertedLoopCall(loop, true); - } - else { - emitNormalLoopBody(node, true); - } - } - function emitDownLevelForOfStatementWorker(node, loop) { - var endPos = emitToken(86, node.pos); - write(" "); - endPos = emitToken(17, endPos); - var counter = createTempVariable(268435456); - var rhsReference = ts.createSynthesizedNode(69); - rhsReference.text = node.expression.kind === 69 ? - makeUniqueName(node.expression.text) : - makeTempVariableName(0); - emitStart(node.expression); - write("var "); - emitNodeWithoutSourceMap(counter); - write(" = 0"); - emitEnd(node.expression); - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - write("; "); - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write(" < "); - emitNodeWithCommentsAndWithoutSourcemap(rhsReference); - write(".length"); - emitEnd(node.expression); - write("; "); - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write("++"); - emitEnd(node.expression); - emitToken(18, node.expression.end); - write(" {"); - writeLine(); - increaseIndent(); - var rhsIterationValue = createElementAccessExpression(rhsReference, counter); - emitStart(node.initializer); - if (node.initializer.kind === 219) { - write("var "); - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length > 0) { - var declaration = variableDeclarationList.declarations[0]; - if (ts.isBindingPattern(declaration.name)) { - emitDestructuring(declaration, false, rhsIterationValue); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(declaration); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - emitNodeWithoutSourceMap(createTempVariable(0)); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - var assignmentExpression = createBinaryExpression(node.initializer, 56, rhsIterationValue, false); - if (node.initializer.kind === 170 || node.initializer.kind === 171) { - emitDestructuring(assignmentExpression, true, undefined); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression); - } - } - emitEnd(node.initializer); - write(";"); - if (loop) { - writeLine(); - emitConvertedLoopCall(loop, false); - } - else { - emitNormalLoopBody(node, false); - } - writeLine(); - decreaseIndent(); - write("}"); - } - function emitBreakOrContinueStatement(node) { - if (convertedLoopState) { - var jump = node.kind === 210 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - write("return "); - copyLoopOutParameters(convertedLoopState, 1, false); - if (!node.label) { - if (node.kind === 210) { - convertedLoopState.nonLocalJumps |= 2; - write("\"break\";"); - } - else { - convertedLoopState.nonLocalJumps |= 4; - write("\"continue\";"); - } - } - else { - var labelMarker = void 0; - if (node.kind === 210) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); - } - write("\"" + labelMarker + "\";"); - } - return; - } - } - emitToken(node.kind === 210 ? 70 : 75, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - if (convertedLoopState) { - convertedLoopState.nonLocalJumps |= 8; - write("return { value: "); - if (node.expression) { - emit(node.expression); - } - else { - write("void 0"); - } - write(" };"); - return; - } - emitToken(94, node.pos); - emitOptional(" ", node.expression); - write(";"); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(96, node.pos); - write(" "); - emitToken(17, endPos); - emit(node.expression); - endPos = emitToken(18, node.expression.end); - write(" "); - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps |= 2; - } - emitCaseBlock(node.caseBlock, endPos); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function emitCaseBlock(node, startPos) { - emitToken(15, startPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(16, node.clauses.end); - } - function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); - } - function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 249) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(72, node.pos); - write(" "); - emitToken(17, endPos); - emit(node.variableDeclaration); - emitToken(18, node.variableDeclaration ? node.variableDeclaration.end : endPos); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(76, node.pos); - write(";"); - } - function emitLabelAndColon(node) { - emit(node.label); - write(": "); - } - function emitLabeledStatement(node) { - if (!ts.isIterationStatement(node.statement, false) || !shouldConvertLoopBody(node.statement)) { - emitLabelAndColon(node); - } - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - emit(node.statement); - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 225); - return node; - } - function emitContainingModuleName(node) { - var container = getContainingModule(node); - write(container ? getGeneratedNameForNode(container) : "exports"); - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1) { - var container = getContainingModule(node); - if (container) { - write(getGeneratedNameForNode(container)); - write("."); - } - else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - emitNodeWithCommentsAndWithoutSourcemap(node.name); - emitEnd(node.name); - } - function createVoidZero() { - var zero = ts.createSynthesizedNode(8); - zero.text = "0"; - var result = ts.createSynthesizedNode(183); - result.expression = zero; - return result; - } - function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 256) { - ts.Debug.assert(!!(node.flags & 512) || node.kind === 235); - if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { - if (!isEs6Module) { - if (languageVersion !== 0) { - write('Object.defineProperty(exports, "__esModule", { value: true });'); - writeLine(); - } - else { - write("exports.__esModule = true;"); - writeLine(); - } - } - } - } - } - function emitExportMemberAssignment(node) { - if (node.flags & 1) { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { - write(exportFunctionForFile + "(\""); - if (node.flags & 512) { - write("default"); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - write("\", "); - emitDeclarationName(node); - write(")"); - } - else { - if (node.flags & 512) { - emitEs6ExportDefaultCompat(node); - if (languageVersion === 0) { - write('exports["default"]'); - } - else { - write("exports.default"); - } - } - else { - emitModuleMemberName(node); - } - write(" = "); - emitDeclarationName(node); - } - emitEnd(node); - write(";"); - } - } - function emitExportMemberAssignments(name) { - if (modulekind === ts.ModuleKind.System) { - return; - } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - writeLine(); - emitStart(specifier.name); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - emitEnd(specifier.name); - write(" = "); - emitExpressionIdentifier(name); - write(";"); - } - } - } - function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === ts.ModuleKind.System); - if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { - return; - } - writeLine(); - emitStart(specifier.name); - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write("\", "); - emitExpressionIdentifier(specifier.propertyName || specifier.name); - write(")"); - emitEnd(specifier.name); - write(";"); - } - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { - if (shouldEmitCommaBeforeAssignment) { - write(", "); - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(name); - write("\", "); - } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 218 || name.parent.kind === 169); - emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); - withTemporaryNoSourceMap(function () { - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - }); - emitEnd(nodeForSourceMap, true); - if (exportChanged) { - write(")"); - } - } - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { - var identifier = createTempVariable(0); - if (!canDefineTempVariablesInPlace) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); - return identifier; - } - function isFirstVariableDeclaration(root) { - return root.kind === 218 && - root.parent.kind === 219 && - root.parent.declarations[0] === root; - } - function emitDestructuring(root, isAssignmentExpressionStatement, value) { - var emitCount = 0; - var canDefineTempVariablesInPlace = false; - if (root.kind === 218) { - var isExported = ts.getCombinedNodeFlags(root) & 1; - var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); - canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; - } - else if (root.kind === 142) { - canDefineTempVariablesInPlace = true; - } - if (root.kind === 187) { - emitAssignmentExpression(root); - } - else { - ts.Debug.assert(!isAssignmentExpressionStatement); - if (isFirstVariableDeclaration(root)) { - sourceMap.changeEmitSourcePos(); - } - emitBindingElement(root, value); - } - function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { - if (expr.kind === 69 && reuseIdentifierExpressions) { - return expr; - } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); - emitCount++; - return identifier; - } - function createDefaultValueCheck(value, defaultValue, sourceMapNode) { - value = ensureIdentifier(value, true, sourceMapNode); - var equals = ts.createSynthesizedNode(187); - equals.left = value; - equals.operatorToken = ts.createSynthesizedNode(32); - equals.right = createVoidZero(); - return createConditionalExpression(equals, defaultValue, value); - } - function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(188); - cond.condition = condition; - cond.questionToken = ts.createSynthesizedNode(53); - cond.whenTrue = whenTrue; - cond.colonToken = ts.createSynthesizedNode(54); - cond.whenFalse = whenFalse; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createSynthesizedNode(8); - node.text = "" + value; - return node; - } - function createPropertyAccessForDestructuringProperty(object, propName) { - var index; - var nameIsComputed = propName.kind === 140; - if (nameIsComputed) { - index = ensureIdentifier(propName.expression, false, propName); - } - else { - index = ts.createSynthesizedNode(propName.kind); - index.text = ts.unescapeIdentifier(propName.text); - } - return !nameIsComputed && index.kind === 69 - ? createPropertyAccessExpression(object, index) - : createElementAccessExpression(object, index); - } - function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(174); - var sliceIdentifier = ts.createSynthesizedNode(69); - sliceIdentifier.text = "slice"; - call.expression = createPropertyAccessExpression(value, sliceIdentifier); - call.arguments = ts.createSynthesizedNodeArray(); - call.arguments[0] = createNumericLiteral(sliceIndex); - return call; - } - function emitObjectLiteralAssignment(target, value, sourceMapNode) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value, true, sourceMapNode); - } - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var p = properties_5[_a]; - if (p.kind === 253 || p.kind === 254) { - var propName = p.name; - var target_1 = p.kind === 254 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, sourceMapNode) { - var elements = target.elements; - if (elements.length !== 1) { - value = ensureIdentifier(value, true, sourceMapNode); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 193) { - if (e.kind !== 191) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); - } - else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); - } - } - } - } - function emitDestructuringAssignment(target, value, sourceMapNode) { - if (target.kind === 254) { - if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); - } - target = target.name; - } - else if (target.kind === 187 && target.operatorToken.kind === 56) { - value = createDefaultValueCheck(value, target.right, sourceMapNode); - target = target.left; - } - if (target.kind === 171) { - emitObjectLiteralAssignment(target, value, sourceMapNode); - } - else if (target.kind === 170) { - emitArrayLiteralAssignment(target, value, sourceMapNode); - } - else { - emitAssignment(target, value, emitCount > 0, sourceMapNode); - emitCount++; - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) { - emit(value); - } - else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); - } - else { - if (root.parent.kind !== 178) { - write("("); - } - value = ensureIdentifier(value, true, root); - emitDestructuringAssignment(target, value, root); - write(", "); - emit(value); - if (root.parent.kind !== 178) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - if (target.initializer) { - value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; - } - else if (!value) { - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0, target); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (pattern.kind === 167) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); - } - else if (element.kind !== 193) { - if (!element.dotDotDotToken) { - emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); - } - else if (i === numElements - 1) { - emitBindingElement(element, createSliceCall(value, i)); - } - } - } - } - else { - emitAssignment(target.name, value, emitCount > 0, target); - emitCount++; - } - } - } - function emitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name)) { - var isExported = ts.getCombinedNodeFlags(node) & 1; - if (languageVersion >= 2 && (!isExported || modulekind === ts.ModuleKind.ES6)) { - var isTopLevelDeclarationInSystemModule = modulekind === ts.ModuleKind.System && - shouldHoistVariable(node, true); - if (isTopLevelDeclarationInSystemModule) { - write("("); - } - emit(node.name); - emitOptional(" = ", node.initializer); - if (isTopLevelDeclarationInSystemModule) { - write(")"); - } - } - else { - emitDestructuring(node, false); - } - } - else { - var initializer = node.initializer; - if (!initializer && - languageVersion < 2 && - node.name.kind === 69) { - var container = ts.getEnclosingBlockScopeContainer(node); - var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || - (isCapturedInFunction && isDeclaredInLoop && container.kind === 199 && ts.isIterationStatement(container.parent, false)); - var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 && - !emittedAsTopLevel; - var emitExplicitInitializer = emittedAsNestedLetDeclaration && - container.kind !== 207 && - container.kind !== 208 && - (!resolver.isDeclarationWithCollidingName(node) || - (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, false))); - if (emitExplicitInitializer) { - initializer = createVoidZero(); - } - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(node.name); - write("\", "); - } - emitModuleMemberName(node); - emitOptional(" = ", initializer); - if (exportChanged) { - write(")"); - } - } - } - function emitExportVariableAssignments(node) { - if (node.kind === 193) { - return; - } - var name = node.name; - if (name.kind === 69) { - emitExportMemberAssignments(name); - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, emitExportVariableAssignments); - } - } - function isES6ExportedDeclaration(node) { - return !!(node.flags & 1) && - modulekind === ts.ModuleKind.ES6 && - node.parent.kind === 256; - } - function emitVariableStatement(node) { - var startIsEmitted = false; - if (node.flags & 1) { - if (isES6ExportedDeclaration(node)) { - write("export "); - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - } - else { - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - if (startIsEmitted) { - emitCommaList(node.declarationList.declarations); - write(";"); - } - else { - var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); - if (atLeastOneItem) { - write(";"); - } - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); - } - } - function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - if (!(node.flags & 1)) { - return true; - } - if (isES6ExportedDeclaration(node)) { - return true; - } - for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { - var declaration = _b[_a]; - if (declaration.initializer) { - return true; - } - } - return false; - } - function emitParameter(node) { - if (languageVersion < 2) { - if (ts.isBindingPattern(node.name)) { - var name_30 = createTempVariable(0); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name_30); - emit(name_30); - } - else { - emit(node.name); - } - } - else { - if (node.dotDotDotToken) { - write("..."); - } - emit(node.name); - emitOptional(" = ", node.initializer); - } - } - function emitDefaultValueAssignments(node) { - if (languageVersion < 2) { - var tempIndex_1 = 0; - ts.forEach(node.parameters, function (parameter) { - if (parameter.dotDotDotToken) { - return; - } - var paramName = parameter.name, initializer = parameter.initializer; - if (ts.isBindingPattern(paramName)) { - var hasBindingElements = paramName.elements.length > 0; - if (hasBindingElements || initializer) { - writeLine(); - write("var "); - if (hasBindingElements) { - emitDestructuring(parameter, false, tempParameters[tempIndex_1]); - } - else { - emit(tempParameters[tempIndex_1]); - write(" = "); - emit(initializer); - } - write(";"); - } - tempIndex_1++; - } - else if (initializer) { - writeLine(); - emitStart(parameter); - write("if ("); - emitNodeWithoutSourceMap(paramName); - write(" === void 0)"); - emitEnd(parameter); - write(" { "); - emitStart(parameter); - emitNodeWithCommentsAndWithoutSourcemap(paramName); - write(" = "); - emitNodeWithCommentsAndWithoutSourcemap(initializer); - emitEnd(parameter); - write("; }"); - } - }); - } - } - function emitRestParameter(node) { - if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - if (ts.isBindingPattern(restParam.name)) { - return; - } - var tempName = createTempVariable(268435456).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - write(node.kind === 149 ? "get " : "set "); - emit(node.name); - emitSignatureAndBody(node); - } - function shouldEmitAsArrowFunction(node) { - return node.kind === 180 && languageVersion >= 2; - } - function emitDeclarationName(node) { - if (node.name) { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - else { - write(getGeneratedNameForNode(node)); - } - } - function shouldEmitFunctionName(node) { - if (node.kind === 179) { - return !!node.name; - } - if (node.kind === 220) { - return !!node.name || modulekind !== ts.ModuleKind.ES6; - } - } - function emitFunctionDeclaration(node) { - if (ts.nodeIsMissing(node.body)) { - return emitCommentsOnNotEmittedNode(node); - } - var kind = node.kind, parent = node.parent; - if (kind !== 147 && - kind !== 146 && - parent && - parent.kind !== 253 && - parent.kind !== 174 && - parent.kind !== 170) { - emitLeadingComments(node); - } - emitStart(node); - if (!shouldEmitAsArrowFunction(node)) { - if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512) { - write("default "); - } - } - write("function"); - if (languageVersion >= 2 && node.asteriskToken) { - write("*"); - } - write(" "); - } - if (shouldEmitFunctionName(node)) { - emitDeclarationName(node); - } - emitSignatureAndBody(node); - if (modulekind !== ts.ModuleKind.ES6 && kind === 220 && parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - emitEnd(node); - if (kind !== 147 && - kind !== 146 && - kind !== 180) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; - var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; - emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); - } - write(")"); - decreaseIndent(); - } - function emitSignatureParametersForArrow(node) { - if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { - emit(node.parameters[0]); - return; - } - emitSignatureParameters(node); - } - function emitAsyncFunctionBodyForES6(node) { - var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 180; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; - if (!isArrowFunction) { - write(" {"); - increaseIndent(); - writeLine(); - if (resolver.getNodeCheckFlags(node) & 4096) { - writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); - writeLine(); - } - else if (resolver.getNodeCheckFlags(node) & 2048) { - write("const _super = name => super[name];"); - writeLine(); - } - write("return"); - } - write(" __awaiter(this"); - if (hasLexicalArguments) { - write(", arguments, "); - } - else { - write(", void 0, "); - } - if (languageVersion >= 2 || !promiseConstructor) { - write("void 0"); - } - else { - emitEntityNameAsExpression(promiseConstructor, false); - } - write(", function* ()"); - emitFunctionBody(node); - write(")"); - if (!isArrowFunction) { - write(";"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitFunctionBody(node) { - if (!node.body) { - write(" { }"); - } - else { - if (node.body.kind === 199) { - emitBlockFunctionBody(node, node.body); - } - else { - emitExpressionFunctionBody(node, node.body); - } - } - } - function emitSignatureAndBody(node) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - if (shouldEmitAsArrowFunction(node)) { - emitSignatureParametersForArrow(node); - write(" =>"); - } - else { - emitSignatureParameters(node); - } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAsyncFunctionBodyForES6(node); - } - else { - emitFunctionBody(node); - } - if (!isES6ExportedDeclaration(node)) { - emitExportMemberAssignment(node); - } - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitFunctionBodyPreamble(node) { - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - } - function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 || node.flags & 256) { - emitDownLevelExpressionFunctionBody(node, body); - return; - } - write(" "); - var current = body; - while (current.kind === 177) { - current = current.expression; - } - emitParenthesizedIf(body, current.kind === 171); - } - function emitDownLevelExpressionFunctionBody(node, body) { - write(" {"); - increaseIndent(); - var outPos = writer.getTextPos(); - emitDetachedCommentsAndUpdateCommentsInfo(node.body); - emitFunctionBodyPreamble(node); - var preambleEmitted = writer.getTextPos() !== outPos; - decreaseIndent(); - if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) { - write(" "); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTempDeclarations(false); - write(" "); - } - else { - increaseIndent(); - writeLine(); - emitLeadingComments(node.body); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTrailingComments(node.body); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - } - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - function emitBlockFunctionBody(node, body) { - write(" {"); - var initialTextPos = writer.getTextPos(); - increaseIndent(); - emitDetachedCommentsAndUpdateCommentsInfo(body.statements); - var startIndex = emitDirectivePrologues(body.statements, true); - emitFunctionBodyPreamble(node); - decreaseIndent(); - var preambleEmitted = writer.getTextPos() !== initialTextPos; - if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { - var statement = _b[_a]; - write(" "); - emit(statement); - } - emitTempDeclarations(false); - write(" "); - emitLeadingCommentsOfPosition(body.statements.end); - } - else { - increaseIndent(); - emitLinesStartingAt(body.statements, startIndex); - emitTempDeclarations(true); - writeLine(); - emitLeadingCommentsOfPosition(body.statements.end); - decreaseIndent(); - } - emitToken(16, body.statements.end); - } - function getSuperCallAtGivenIndex(ctor, index) { - if (!ctor.body) { - return undefined; - } - var statements = ctor.body.statements; - if (!statements || index >= statements.length) { - return undefined; - } - var statement = statements[index]; - if (statement.kind === 202) { - return ts.isSuperCallExpression(statement.expression) ? statement : undefined; - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 92) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNodeWithoutSourceMap(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - if (memberName.kind === 9 || memberName.kind === 8) { - write("["); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - write("]"); - } - else if (memberName.kind === 140) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - } - } - function getInitializedProperties(node, isStatic) { - var properties = []; - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 145 && isStatic === ((member.flags & 32) !== 0) && member.initializer) { - properties.push(member); - } - } - return properties; - } - function emitPropertyDeclarations(node, properties) { - for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { - var property = properties_6[_a]; - emitPropertyDeclaration(node, property); - } - } - function emitPropertyDeclaration(node, property, receiver, isExpression) { - writeLine(); - emitLeadingComments(property); - emitStart(property); - emitStart(property.name); - if (receiver) { - write(receiver); - } - else { - if (property.flags & 32) { - emitDeclarationName(node); - } - else { - write("this"); - } - } - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - emit(property.initializer); - if (!isExpression) { - write(";"); - } - emitEnd(property); - emitTrailingComments(property); - } - function emitMemberFunctionsForES5AndLower(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 198) { - writeLine(); - write(";"); - } - else if (member.kind === 147 || node.kind === 146) { - if (!member.body) { - return emitCommentsOnNotEmittedNode(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitClassMemberPrefix(node, member); - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitFunctionDeclaration(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 149 || member.kind === 150) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitMemberFunctionsForES6AndHigher(node) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.kind === 147 || node.kind === 146) && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - else if (member.kind === 147 || - member.kind === 149 || - member.kind === 150) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - if (member.flags & 32) { - write("static "); - } - if (member.kind === 149) { - write("get "); - } - else if (member.kind === 150) { - write("set "); - } - if (member.asteriskToken) { - write("*"); - } - emit(member.name); - emitSignatureAndBody(member); - emitEnd(member); - emitTrailingComments(member); - } - else if (member.kind === 198) { - writeLine(); - write(";"); - } - } - } - function emitConstructor(node, baseTypeElement) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - emitConstructorWorker(node, baseTypeElement); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitConstructorWorker(node, baseTypeElement) { - var hasInstancePropertyWithInitializer = false; - ts.forEach(node.members, function (member) { - if (member.kind === 148 && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - if (member.kind === 145 && member.initializer && (member.flags & 32) === 0) { - hasInstancePropertyWithInitializer = true; - } - }); - var ctor = ts.getFirstConstructorWithBody(node); - if (languageVersion >= 2 && !ctor && !hasInstancePropertyWithInitializer) { - return; - } - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - if (languageVersion < 2) { - write("function "); - emitDeclarationName(node); - emitSignatureParameters(ctor); - } - else { - write("constructor"); - if (ctor) { - emitSignatureParameters(ctor); - } - else { - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } - } - } - var startIndex = 0; - write(" {"); - increaseIndent(); - if (ctor) { - startIndex = emitDirectivePrologues(ctor.body.statements, true); - emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - var superCall; - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeElement) { - superCall = getSuperCallAtGivenIndex(ctor, startIndex); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeElement) { - writeLine(); - emitStart(baseTypeElement); - if (languageVersion < 2) { - write("_super.apply(this, arguments);"); - } - else { - write("super(...args);"); - } - emitEnd(baseTypeElement); - } - } - emitPropertyDeclarations(node, getInitializedProperties(node, false)); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) { - statements = statements.slice(1); - } - emitLinesStartingAt(statements, startIndex); - } - emitTempDeclarations(true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(16, ctor ? ctor.body.statements.end : node.members.end); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - } - function emitClassExpression(node) { - return emitClassLikeDeclaration(node); - } - function emitClassDeclaration(node) { - return emitClassLikeDeclaration(node); - } - function emitClassLikeDeclaration(node) { - if (languageVersion < 2) { - emitClassLikeDeclarationBelowES6(node); - } - else { - emitClassLikeDeclarationForES6AndHigher(node); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - } - function emitClassLikeDeclarationForES6AndHigher(node) { - var decoratedClassAlias; - var isHoistedDeclarationInSystemModule = shouldHoistDeclarationInSystemJsModule(node); - var isDecorated = ts.nodeIsDecorated(node); - var rewriteAsClassExpression = isDecorated || isHoistedDeclarationInSystemModule; - if (node.kind === 221) { - if (rewriteAsClassExpression) { - if (isDecorated && resolver.getNodeCheckFlags(node) & 524288) { - decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); - decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; - } - if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) { - write("export "); - } - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } - if (decoratedClassAlias !== undefined) { - write("" + decoratedClassAlias); - } - else { - emitDeclarationName(node); - } - write(" = "); - } - else if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512) { - write("default "); - } - } - } - var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; - var generatedName; - if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); - var synthesizedNode = ts.createSynthesizedNode(69); - synthesizedNode.text = generatedName; - recordTempDeclaration(synthesizedNode); - write("("); - increaseIndent(); - emit(synthesizedNode); - write(" = "); - } - write("class"); - if (node.name || (node.flags & 512 && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !rewriteAsClassExpression)) { - write(" "); - emitDeclarationName(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write(" extends "); - emit(baseTypeNode.expression); - } - write(" {"); - increaseIndent(); - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES6AndHigher(node); - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - if (rewriteAsClassExpression) { - if (decoratedClassAlias !== undefined) { - write(";"); - writeLine(); - if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { - write("export "); - } - write("let "); - emitDeclarationName(node); - write(" = " + decoratedClassAlias); - } - decoratedClassAliases[ts.getNodeId(node)] = undefined; - write(";"); - } - if (isClassExpressionWithStaticProperties) { - for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { - var property = staticProperties_1[_a]; - write(","); - writeLine(); - emitPropertyDeclaration(node, property, generatedName, true); - } - write(","); - writeLine(); - write(generatedName); - decreaseIndent(); - write(")"); - } - else { - writeLine(); - emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node, decoratedClassAlias); - } - if (!(node.flags & 1)) { - return; - } - if (modulekind !== ts.ModuleKind.ES6) { - emitExportMemberAssignment(node); - } - else { - if (node.flags & 512) { - if (isDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - else if (node.parent.kind !== 256) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); - } - } - } - function emitClassLikeDeclarationBelowES6(node) { - var isES6ExportedClass = isES6ExportedDeclaration(node); - if (node.kind === 221) { - if (isES6ExportedClass && !(node.flags & 512)) { - write("export "); - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - write("var "); - } - emitDeclarationName(node); - write(" = "); - } - write("(function ("); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - var saveConvertedLoopState = convertedLoopState; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - computedPropertyNamesToGeneratedNames = undefined; - increaseIndent(); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emitDeclarationName(node); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, true)); - writeLine(); - emitDecoratorsOfClass(node, undefined); - writeLine(); - emitToken(16, node.members.end, function () { - write("return "); - emitDeclarationName(node); - }); - write(";"); - emitTempDeclarations(true); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames; - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - emitStart(node); - write("("); - if (baseTypeNode) { - emit(baseTypeNode.expression); - } - write("))"); - if (node.kind === 221) { - write(";"); - } - emitEnd(node); - if (node.kind === 221 && !isES6ExportedClass) { - emitExportMemberAssignment(node); - } - else if (isES6ExportedClass && (node.flags & 512)) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - function emitClassMemberPrefix(node, member) { - emitDeclarationName(node); - if (!(member.flags & 32)) { - write(".prototype"); - } - } - function emitDecoratorsOfClass(node, decoratedClassAlias) { - emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 32); - emitDecoratorsOfConstructor(node, decoratedClassAlias); - } - function emitDecoratorsOfConstructor(node, decoratedClassAlias) { - var decorators = node.decorators; - var constructor = ts.getFirstConstructorWithBody(node); - var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); - if (!decorators && !firstParameterDecorator) { - return; - } - writeLine(); - emitStart(node.decorators || firstParameterDecorator); - emitDeclarationName(node); - if (decoratedClassAlias !== undefined) { - write(" = " + decoratedClassAlias); - } - write(" = __decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); - } - emitSerializedTypeMetadata(node, argumentsWritten >= 0); - decreaseIndent(); - writeLine(); - write("], "); - emitDeclarationName(node); - write(")"); - emitEnd(node.decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - function emitDecoratorsOfMembers(node, staticFlag) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.flags & 32) !== staticFlag) { - continue; - } - if (!ts.nodeCanBeDecorated(member)) { - continue; - } - var decorators = void 0; - var functionLikeMember = void 0; - if (ts.isAccessor(member)) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member !== accessors.firstAccessor) { - continue; - } - decorators = accessors.firstAccessor.decorators; - if (!decorators && accessors.secondAccessor) { - decorators = accessors.secondAccessor.decorators; - } - functionLikeMember = accessors.setAccessor; - } - else { - decorators = member.decorators; - if (member.kind === 147) { - functionLikeMember = member; - } - } - var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); - if (!decorators && !firstParameterDecorator) { - continue; - } - writeLine(); - emitStart(decorators || firstParameterDecorator); - write("__decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); - } - emitSerializedTypeMetadata(member, argumentsWritten > 0); - decreaseIndent(); - writeLine(); - write("], "); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - if (languageVersion > 0) { - if (member.kind !== 145) { - write(", null"); - } - else { - write(", void 0"); - } - } - write(")"); - emitEnd(decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - } - function emitDecoratorsOfParameters(node, leadingComma) { - var argumentsWritten = 0; - if (node) { - var parameterIndex_1 = 0; - for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { - var parameter = _b[_a]; - if (ts.nodeIsDecorated(parameter)) { - var decorators = parameter.decorators; - argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - write("__param(" + parameterIndex_1 + ", "); - emit(decorator.expression); - write(")"); - }); - leadingComma = true; - } - parameterIndex_1++; - } - } - return argumentsWritten; - } - function shouldEmitTypeMetadata(node) { - switch (node.kind) { - case 147: - case 149: - case 150: - case 145: - return true; - } - return false; - } - function shouldEmitReturnTypeMetadata(node) { - switch (node.kind) { - case 147: - return true; - } - return false; - } - function shouldEmitParamTypesMetadata(node) { - switch (node.kind) { - case 221: - case 147: - case 150: - return true; - } - return false; - } - function emitSerializedTypeOfNode(node) { - switch (node.kind) { - case 221: - write("Function"); - return; - case 145: - emitSerializedTypeNode(node.type); - return; - case 142: - emitSerializedTypeNode(node.type); - return; - case 149: - emitSerializedTypeNode(node.type); - return; - case 150: - emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - return; - } - if (ts.isFunctionLike(node)) { - write("Function"); - return; - } - write("void 0"); - } - function emitSerializedTypeNode(node) { - if (node) { - switch (node.kind) { - case 103: - write("void 0"); - return; - case 164: - emitSerializedTypeNode(node.type); - return; - case 156: - case 157: - write("Function"); - return; - case 160: - case 161: - write("Array"); - return; - case 154: - case 120: - write("Boolean"); - return; - case 132: - case 166: - write("String"); - return; - case 130: - write("Number"); - return; - case 133: - write("Symbol"); - return; - case 155: - emitSerializedTypeReferenceNode(node); - return; - case 158: - case 159: - case 162: - case 163: - case 117: - case 165: - break; - default: - ts.Debug.fail("Cannot serialize unexpected type node."); - break; - } - } - write("Object"); - } - function emitSerializedTypeReferenceNode(node) { - var location = node.parent; - while (ts.isDeclaration(location) || ts.isTypeNode(location)) { - location = location.parent; - } - var typeName = ts.cloneEntityName(node.typeName, location); - var result = resolver.getTypeReferenceSerializationKind(typeName); - switch (result) { - case ts.TypeReferenceSerializationKind.Unknown: - var temp = createAndRecordTempVariable(0); - write("(typeof ("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(typeName, true); - write(") === 'function' && "); - emitNodeWithoutSourceMap(temp); - write(") || Object"); - break; - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - emitEntityNameAsExpression(typeName, false); - break; - case ts.TypeReferenceSerializationKind.VoidType: - write("void 0"); - break; - case ts.TypeReferenceSerializationKind.BooleanType: - write("Boolean"); - break; - case ts.TypeReferenceSerializationKind.NumberLikeType: - write("Number"); - break; - case ts.TypeReferenceSerializationKind.StringLikeType: - write("String"); - break; - case ts.TypeReferenceSerializationKind.ArrayLikeType: - write("Array"); - break; - case ts.TypeReferenceSerializationKind.ESSymbolType: - if (languageVersion < 2) { - write("typeof Symbol === 'function' ? Symbol : Object"); - } - else { - write("Symbol"); - } - break; - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - write("Function"); - break; - case ts.TypeReferenceSerializationKind.ObjectType: - write("Object"); - break; - } - } - function emitSerializedParameterTypesOfNode(node) { - if (node) { - var valueDeclaration = void 0; - if (node.kind === 221) { - valueDeclaration = ts.getFirstConstructorWithBody(node); - } - else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { - valueDeclaration = node; - } - if (valueDeclaration) { - var parameters = valueDeclaration.parameters; - var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { - write(", "); - } - if (parameters[i].dotDotDotToken) { - var parameterType = parameters[i].type; - if (parameterType && parameterType.kind === 160) { - parameterType = parameterType.elementType; - } - else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { - parameterType = parameterType.typeArguments[0]; - } - else { - parameterType = undefined; - } - emitSerializedTypeNode(parameterType); - } - else { - emitSerializedTypeOfNode(parameters[i]); - } - } - } - } - } - } - function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node)) { - if (node.type) { - emitSerializedTypeNode(node.type); - return; - } - else if (ts.isAsyncFunctionLike(node)) { - write("Promise"); - return; - } - } - write("void 0"); - } - function emitSerializedTypeMetadata(node, writeComma) { - var argumentsWritten = 0; - if (compilerOptions.emitDecoratorMetadata) { - if (shouldEmitTypeMetadata(node)) { - if (writeComma) { - write(", "); - } - writeLine(); - write("__metadata('design:type', "); - emitSerializedTypeOfNode(node); - write(")"); - argumentsWritten++; - } - if (shouldEmitParamTypesMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:paramtypes', ["); - emitSerializedParameterTypesOfNode(node); - write("])"); - argumentsWritten++; - } - if (shouldEmitReturnTypeMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:returntype', "); - emitSerializedReturnTypeOfNode(node); - write(")"); - argumentsWritten++; - } - } - return argumentsWritten; - } - function emitInterfaceDeclaration(node) { - emitCommentsOnNotEmittedNode(node); - } - function shouldEmitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; - } - function emitEnumDeclaration(node) { - if (!shouldEmitEnumDeclaration(node)) { - return; - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - var isES6ExportedEnum = isES6ExportedDeclaration(node); - if (!(node.flags & 1) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 224))) { - emitStart(node); - if (isES6ExportedEnum) { - write("export "); - } - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - writeLine(); - emitToken(16, node.members.end); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 && !shouldHoistDeclarationInSystemJsModule(node)) { - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function emitEnumMember(node) { - var enumParent = node.parent; - emitStart(node); - write(getGeneratedNameForNode(enumParent)); - write("["); - write(getGeneratedNameForNode(enumParent)); - write("["); - emitExpressionForPropertyName(node.name); - write("] = "); - writeEnumMemberDeclarationValue(node); - write("] = "); - emitExpressionForPropertyName(node.name); - emitEnd(node); - write(";"); - } - function writeEnumMemberDeclarationValue(member) { - var value = resolver.getConstantValue(member); - if (value !== undefined) { - write(value.toString()); - return; - } - else if (member.initializer) { - emit(member.initializer); - } - else { - write("undefined"); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); - } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 32768); - } - function isFirstDeclarationOfKind(node, declarations, kind) { - return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); - } - function emitModuleDeclaration(node) { - var shouldEmit = shouldEmitModuleDeclaration(node); - if (!shouldEmit) { - return emitCommentsOnNotEmittedNode(node); - } - var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); - var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); - if (emitVarForModule) { - var isES6ExportedNamespace = isES6ExportedDeclaration(node); - if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 225)) { - emitStart(node); - if (isES6ExportedNamespace) { - write("export "); - } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - } - } - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") "); - ts.Debug.assert(node.body !== undefined); - if (node.body.kind === 226) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - emit(node.body); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(16, moduleBlock.statements.end); - } - write(")("); - if ((node.flags & 1) && !isES6ExportedDeclaration(node)) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.name.kind === 69 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { - return "\"" + renamedDependencies[moduleName.text] + "\""; - } - return undefined; - } - function emitRequire(moduleName) { - if (moduleName.kind === 9) { - write("require("); - var text = tryRenameExternalModule(moduleName); - if (text) { - write(text); - } - else { - emitStart(moduleName); - emitLiteral(moduleName); - emitEnd(moduleName); - } - emitToken(18, moduleName.end); - } - else { - write("require()"); - } - } - function getNamespaceDeclarationNode(node) { - if (node.kind === 229) { - return node; - } - var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { - return importClause.namedBindings; - } - } - function isDefaultImport(node) { - return node.kind === 230 && node.importClause && !!node.importClause.name; - } - function emitExportImportAssignments(node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - emitExportMemberAssignments(node.name); - } - ts.forEachChild(node, emitExportImportAssignments); - } - function emitImportDeclaration(node) { - if (modulekind !== ts.ModuleKind.ES6) { - return emitExternalImportDeclaration(node); - } - if (node.importClause) { - var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, true); - if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { - write("import "); - emitStart(node.importClause); - if (shouldEmitDefaultBindings) { - emit(node.importClause.name); - if (shouldEmitNamedBindings) { - write(", "); - } - } - if (shouldEmitNamedBindings) { - emitLeadingComments(node.importClause.namedBindings); - emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 232) { - write("* as "); - emit(node.importClause.namedBindings.name); - } - else { - write("{ "); - emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration); - write(" }"); - } - emitEnd(node.importClause.namedBindings); - emitTrailingComments(node.importClause.namedBindings); - } - emitEnd(node.importClause); - write(" from "); - emit(node.moduleSpecifier); - write(";"); - } - } - else { - write("import "); - emit(node.moduleSpecifier); - write(";"); - } - } - function emitExternalImportDeclaration(node) { - if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 229 && (node.flags & 1) !== 0; - var namespaceDeclaration = getNamespaceDeclarationNode(node); - var varOrConst = (languageVersion <= 1) ? "var " : "const "; - if (modulekind !== ts.ModuleKind.AMD) { - emitLeadingComments(node); - emitStart(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - if (!isExportedImport) { - write(varOrConst); - } - ; - emitModuleMemberName(namespaceDeclaration); - write(" = "); - } - else { - var isNakedImport = 230 && !node.importClause; - if (!isNakedImport) { - write(varOrConst); - write(getGeneratedNameForNode(node)); - write(" = "); - } - } - emitRequire(ts.getExternalModuleName(node)); - if (namespaceDeclaration && isDefaultImport(node)) { - write(", "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - else { - if (isExportedImport) { - emitModuleMemberName(namespaceDeclaration); - write(" = "); - emit(namespaceDeclaration.name); - write(";"); - } - else if (namespaceDeclaration && isDefaultImport(node)) { - write(varOrConst); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - write(";"); - } - emitExportImportAssignments(node); - } - } - } - function emitImportEqualsDeclaration(node) { - if (ts.isExternalModuleImportEqualsDeclaration(node)) { - emitExternalImportDeclaration(node); - return; - } - if (resolver.isReferencedAliasDeclaration(node) || - (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { - emitLeadingComments(node); - emitStart(node); - var variableDeclarationIsHoisted = shouldHoistVariable(node, true); - var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, true); - if (!variableDeclarationIsHoisted) { - ts.Debug.assert(!isExported); - if (isES6ExportedDeclaration(node)) { - write("export "); - write("var "); - } - else if (!(node.flags & 1)) { - write("var "); - } - } - if (isExported) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.name); - write("\", "); - } - emitModuleMemberName(node); - write(" = "); - emit(node.moduleReference); - if (isExported) { - write(")"); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - } - function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== ts.ModuleKind.System); - if (modulekind !== ts.ModuleKind.ES6) { - if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { - emitStart(node); - var generatedName = getGeneratedNameForNode(node); - if (node.exportClause) { - if (modulekind !== ts.ModuleKind.AMD) { - write("var "); - write(generatedName); - write(" = "); - emitRequire(ts.getExternalModuleName(node)); - write(";"); - } - for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) { - var specifier = _b[_a]; - if (resolver.isValueAliasDeclaration(specifier)) { - writeLine(); - emitStart(specifier); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write(" = "); - write(generatedName); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name); - write(";"); - emitEnd(specifier); - } - } - } - else { - if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - writeLine(); - write("__export("); - if (modulekind !== ts.ModuleKind.AMD) { - emitRequire(ts.getExternalModuleName(node)); - } - else { - write(generatedName); - } - write(");"); - } - } - emitEnd(node); - } - } - else { - if (!node.exportClause || resolver.isValueAliasDeclaration(node)) { - write("export "); - if (node.exportClause) { - write("{ "); - emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emit(node.moduleSpecifier); - } - write(";"); - } - } - } - function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === ts.ModuleKind.ES6); - var needsComma = false; - for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { - var specifier = specifiers_1[_a]; - if (shouldEmit(specifier)) { - if (needsComma) { - write(", "); - } - if (specifier.propertyName) { - emit(specifier.propertyName); - write(" as "); - } - emit(specifier.name); - needsComma = true; - } - } - } - function emitExportAssignment(node) { - if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === ts.ModuleKind.ES6) { - writeLine(); - emitStart(node); - write("export default "); - var expression = node.expression; - emit(expression); - if (expression.kind !== 220 && - expression.kind !== 221) { - write(";"); - } - emitEnd(node); - } - else { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System) { - write(exportFunctionForFile + "(\"default\","); - emit(node.expression); - write(")"); - } - else { - emitEs6ExportDefaultCompat(node); - emitContainingModuleName(node); - if (languageVersion === 0) { - write('["default"] = '); - } - else { - write(".default = "); - } - emit(node.expression); - } - write(";"); - emitEnd(node); - } - } - } - function collectExternalModuleInfo(sourceFile) { - externalImports = []; - exportSpecifiers = {}; - exportEquals = undefined; - hasExportStarsToExportValues = false; - for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { - var node = _b[_a]; - switch (node.kind) { - case 230: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, true)) { - externalImports.push(node); - } - break; - case 229: - if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { - externalImports.push(node); - } - break; - case 236: - if (node.moduleSpecifier) { - if (!node.exportClause) { - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - externalImports.push(node); - } - } - else { - for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { - var specifier = _d[_c]; - var name_31 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); - } - } - break; - case 235: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; - } - } - } - function emitExportStarHelper() { - if (hasExportStarsToExportValues) { - writeLine(); - write("function __export(m) {"); - increaseIndent(); - writeLine(); - write("for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function getLocalNameForExternalImport(node) { - var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); - } - if (node.kind === 230 && node.importClause) { - return getGeneratedNameForNode(node); - } - if (node.kind === 236 && node.moduleSpecifier) { - return getGeneratedNameForNode(node); - } - } - function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { - if (emitRelativePathAsModuleName) { - var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_32) { - return "\"" + name_32 + "\""; - } - } - var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 9) { - return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); - } - return undefined; - } - function emitVariableDeclarationsForImports() { - if (externalImports.length === 0) { - return; - } - writeLine(); - var started = false; - for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { - var importNode = externalImports_1[_a]; - var skipNode = importNode.kind === 236 || - (importNode.kind === 230 && !importNode.importClause); - if (skipNode) { - continue; - } - if (!started) { - write("var "); - started = true; - } - else { - write(", "); - } - write(getLocalNameForExternalImport(importNode)); - } - if (started) { - write(";"); - } - } - function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - if (!hasExportStarsToExportValues) { - return undefined; - } - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { - var hasExportDeclarationWithExportClause = false; - for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { - var externalImport = externalImports_2[_a]; - if (externalImport.kind === 236 && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - return emitExportStarFunction(undefined); - } - } - var exportedNamesStorageRef = makeUniqueName("exportedNames"); - writeLine(); - write("var " + exportedNamesStorageRef + " = {"); - increaseIndent(); - var started = false; - if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; i++) { - writeExportedName(exportedDeclarations[i]); - } - } - if (exportSpecifiers) { - for (var n in exportSpecifiers) { - for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) { - var specifier = _c[_b]; - writeExportedName(specifier.name); - } - } - } - for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { - var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 236) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - continue; - } - for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) { - var element = _f[_e]; - writeExportedName(element.name || element.propertyName); - } - } - decreaseIndent(); - writeLine(); - write("};"); - return emitExportStarFunction(exportedNamesStorageRef); - function emitExportStarFunction(localNames) { - var exportStarFunction = makeUniqueName("exportStar"); - writeLine(); - write("function " + exportStarFunction + "(m) {"); - increaseIndent(); - writeLine(); - write("var exports = {};"); - writeLine(); - write("for(var n in m) {"); - increaseIndent(); - writeLine(); - write("if (n !== \"default\""); - if (localNames) { - write("&& !" + localNames + ".hasOwnProperty(n)"); - } - write(") exports[n] = m[n];"); - decreaseIndent(); - writeLine(); - write("}"); - writeLine(); - write(exportFunctionForFile + "(exports);"); - decreaseIndent(); - writeLine(); - write("}"); - return exportStarFunction; - } - function writeExportedName(node) { - if (node.kind !== 69 && node.flags & 512) { - return; - } - if (started) { - write(","); - } - else { - started = true; - } - writeLine(); - write("'"); - if (node.kind === 69) { - emitNodeWithCommentsAndWithoutSourcemap(node); - } - else { - emitDeclarationName(node); - } - write("': true"); - } - } - function processTopLevelVariableAndFunctionDeclarations(node) { - var hoistedVars; - var hoistedFunctionDeclarations; - var exportedDeclarations; - visit(node); - if (hoistedVars) { - writeLine(); - write("var "); - var seen = {}; - for (var i = 0; i < hoistedVars.length; i++) { - var local = hoistedVars[i]; - var name_33 = local.kind === 69 - ? local - : local.name; - if (name_33) { - var text = ts.unescapeIdentifier(name_33.text); - if (ts.hasProperty(seen, text)) { - continue; - } - else { - seen[text] = text; - } - } - if (i !== 0) { - write(", "); - } - if (local.kind === 221 || local.kind === 225 || local.kind === 224) { - emitDeclarationName(local); - } - else { - emit(local); - } - var flags = ts.getCombinedNodeFlags(local.kind === 69 ? local.parent : local); - if (flags & 1) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(local); - } - } - write(";"); - } - if (hoistedFunctionDeclarations) { - for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { - var f = hoistedFunctionDeclarations_1[_a]; - writeLine(); - emit(f); - if (f.flags & 1) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(f); - } - } - } - return exportedDeclarations; - function visit(node) { - if (node.flags & 2) { - return; - } - if (node.kind === 220) { - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = []; - } - hoistedFunctionDeclarations.push(node); - return; - } - if (node.kind === 221) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - return; - } - if (node.kind === 224) { - if (shouldEmitEnumDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 225) { - if (shouldEmitModuleDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 218 || node.kind === 169) { - if (shouldHoistVariable(node, false)) { - var name_34 = node.name; - if (name_34.kind === 69) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(name_34); - } - else { - ts.forEachChild(name_34, visit); - } - } - return; - } - if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node.name); - return; - } - if (ts.isBindingPattern(node)) { - ts.forEach(node.elements, visit); - return; - } - if (!ts.isDeclaration(node)) { - ts.forEachChild(node, visit); - } - } - } - function shouldHoistVariable(node, checkIfSourceFileLevelDecl) { - if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { - return false; - } - return (ts.getCombinedNodeFlags(node) & 3072) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 256; - } - function isCurrentFileSystemExternalModule() { - return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; - } - function emitSystemModuleBody(node, dependencyGroups, startIndex) { - emitVariableDeclarationsForImports(); - writeLine(); - var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); - writeLine(); - write("return {"); - increaseIndent(); - writeLine(); - emitSetters(exportStarFunction, dependencyGroups); - writeLine(); - emitExecute(node, startIndex); - decreaseIndent(); - writeLine(); - write("}"); - emitTempDeclarations(true); - } - function emitSetters(exportStarFunction, dependencyGroups) { - write("setters:["); - for (var i = 0; i < dependencyGroups.length; i++) { - if (i !== 0) { - write(","); - } - writeLine(); - increaseIndent(); - var group = dependencyGroups[i]; - var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); - write("function (" + parameterName + ") {"); - increaseIndent(); - for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { - var entry = group_1[_a]; - var importVariableName = getLocalNameForExternalImport(entry) || ""; - switch (entry.kind) { - case 230: - if (!entry.importClause) { - break; - } - case 229: - ts.Debug.assert(importVariableName !== ""); - writeLine(); - write(importVariableName + " = " + parameterName + ";"); - writeLine(); - break; - case 236: - ts.Debug.assert(importVariableName !== ""); - if (entry.exportClause) { - writeLine(); - write(exportFunctionForFile + "({"); - writeLine(); - increaseIndent(); - for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { - if (i_1 !== 0) { - write(","); - writeLine(); - } - var e = entry.exportClause.elements[i_1]; - write("\""); - emitNodeWithCommentsAndWithoutSourcemap(e.name); - write("\": " + parameterName + "[\""); - emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name); - write("\"]"); - } - decreaseIndent(); - writeLine(); - write("});"); - } - else { - writeLine(); - write(exportStarFunction + "(" + parameterName + ");"); - } - writeLine(); - break; - } - } - decreaseIndent(); - write("}"); - decreaseIndent(); - } - write("],"); - } - function emitExecute(node, startIndex) { - write("execute: function() {"); - increaseIndent(); - writeLine(); - for (var i = startIndex; i < node.statements.length; i++) { - var statement = node.statements[i]; - switch (statement.kind) { - case 220: - case 230: - continue; - case 236: - if (!statement.moduleSpecifier) { - for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { - var element = _b[_a]; - emitExportSpecifierInSystemModule(element); - } - } - continue; - case 229: - if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { - continue; - } - default: - writeLine(); - emit(statement); - } - } - decreaseIndent(); - writeLine(); - write("}"); - } - function writeModuleName(node, emitRelativePathAsModuleName) { - var moduleName = node.moduleName; - if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { - write("\"" + moduleName + "\", "); - } - } - function emitSystemModule(node, emitRelativePathAsModuleName) { - collectExternalModuleInfo(node); - ts.Debug.assert(!exportFunctionForFile); - exportFunctionForFile = makeUniqueName("exports"); - contextObjectForFile = makeUniqueName("context"); - writeLine(); - write("System.register("); - writeModuleName(node, emitRelativePathAsModuleName); - write("["); - var groupIndices = {}; - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); - if (text === undefined) { - continue; - } - var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { - var groupIndex = groupIndices[key]; - dependencyGroups[groupIndex].push(externalImports[i]); - continue; - } - else { - groupIndices[key] = dependencyGroups.length; - dependencyGroups.push([externalImports[i]]); - } - if (i !== 0) { - write(", "); - } - write(text); - } - write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); - writeLine(); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - writeLine(); - write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); - writeLine(); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitSystemModuleBody(node, dependencyGroups, startIndex); - decreaseIndent(); - writeLine(); - write("});"); - } - function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - var aliasedModuleNames = []; - var unaliasedModuleNames = []; - var importAliasNames = []; - for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) { - var amdDependency = _b[_a]; - if (amdDependency.name) { - aliasedModuleNames.push('"' + amdDependency.path + '"'); - importAliasNames.push(amdDependency.name); - } - else { - unaliasedModuleNames.push('"' + amdDependency.path + '"'); - } - } - for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { - var importNode = externalImports_4[_c]; - var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); - var importAliasName = getLocalNameForExternalImport(importNode); - if (includeNonAmdDependencies && importAliasName) { - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(importAliasName); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); - emitAMDDependencyList(dependencyNames); - write(", "); - emitAMDFactoryHeader(dependencyNames); - } - function emitAMDDependencyList(_a) { - var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames; - write('["require", "exports"'); - if (aliasedModuleNames.length) { - write(", "); - write(aliasedModuleNames.join(", ")); - } - if (unaliasedModuleNames.length) { - write(", "); - write(unaliasedModuleNames.join(", ")); - } - write("]"); - } - function emitAMDFactoryHeader(_a) { - var importAliasNames = _a.importAliasNames; - write("function (require, exports"); - if (importAliasNames.length) { - write(", "); - write(importAliasNames.join(", ")); - } - write(") {"); - } - function emitAMDModule(node, emitRelativePathAsModuleName) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - writeLine(); - write("define("); - writeModuleName(node, emitRelativePathAsModuleName); - emitAMDDependencies(node, true, emitRelativePathAsModuleName); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(true); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, false, !compilerOptions.noImplicitUseStrict); - emitEmitHelpers(node); - collectExternalModuleInfo(node); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(false); - emitTempDeclarations(true); - } - function emitUMDModule(node) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - var dependencyNames = getAMDDependencyNames(node, false); - writeLines("(function (factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define("); - emitAMDDependencyList(dependencyNames); - write(", factory);"); - writeLines(" }\n})("); - emitAMDFactoryHeader(dependencyNames); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(true); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitES6Module(node) { - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - var startIndex = emitDirectivePrologues(node.statements, false); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - } - function emitExportEquals(emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - writeLine(); - emitStart(exportEquals); - write(emitAsReturn ? "return " : "module.exports = "); - emit(exportEquals.expression); - write(";"); - emitEnd(exportEquals); - } - } - function emitJsxElement(node) { - switch (compilerOptions.jsx) { - case 2: - jsxEmitReact(node); - break; - case 1: - default: - jsxEmitPreserve(node); - break; - } - } - function trimReactWhitespaceAndApplyEntities(node) { - var result = undefined; - var text = ts.getTextOfNode(node, true); - var firstNonWhitespace = 0; - var lastNonWhitespace = -1; - for (var i = 0; i < text.length; i++) { - var c = text.charCodeAt(i); - if (ts.isLineBreak(c)) { - if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { - var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - firstNonWhitespace = -1; - } - else if (!ts.isWhiteSpaceSingleLine(c)) { - lastNonWhitespace = i; - if (firstNonWhitespace === -1) { - firstNonWhitespace = i; - } - } - } - if (firstNonWhitespace !== -1) { - var part = text.substr(firstNonWhitespace); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - if (result) { - result = result.replace(/&(\w+);/g, function (s, m) { - if (entities[m] !== undefined) { - var ch = String.fromCharCode(entities[m]); - return ch === '"' ? "\\\"" : ch; - } - else { - return s; - } - }); - } - return result; - } - function isJsxChildEmittable(child) { - if (child.kind === 248) { - return !!child.expression; - } - else if (child.kind === 244) { - return !!getTextToEmit(child); - } - return true; - } - ; - function getTextToEmit(node) { - switch (compilerOptions.jsx) { - case 2: - var text = trimReactWhitespaceAndApplyEntities(node); - if (text === undefined || text.length === 0) { - return undefined; - } - else { - return text; - } - case 1: - default: - return ts.getTextOfNode(node, true); - } - } - function emitJsxText(node) { - switch (compilerOptions.jsx) { - case 2: - write('"'); - write(trimReactWhitespaceAndApplyEntities(node)); - write('"'); - break; - case 1: - default: - writer.writeLiteral(ts.getTextOfNode(node, true)); - break; - } - } - function emitJsxExpression(node) { - if (node.expression) { - switch (compilerOptions.jsx) { - case 1: - default: - write("{"); - emit(node.expression); - write("}"); - break; - case 2: - emit(node.expression); - break; - } - } - } - function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; - } - function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { - if (writeUseStrict) { - if (startWithNewLine) { - writeLine(); - } - write("\"use strict\";"); - } - } - function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { - var foundUseStrict = false; - for (var i = 0; i < statements.length; i++) { - if (ts.isPrologueDirective(statements[i])) { - if (isUseStrictPrologue(statements[i])) { - foundUseStrict = true; - } - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); - return i; - } - } - ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); - return statements.length; - } - function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line.length) { - writeLine(); - write(line); - } - } - } - function emitEmitHelpers(node) { - if (!compilerOptions.noEmitHelpers) { - if (languageVersion < 2 && !extendsEmitted && node.flags & 262144) { - writeLines(extendsHelper); - extendsEmitted = true; - } - if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 1073741824)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 524288) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); - } - decorateEmitted = true; - } - if (!paramEmitted && node.flags & 1048576) { - writeLines(paramHelper); - paramEmitted = true; - } - if (!awaiterEmitted && node.flags & 2097152) { - writeLines(awaiterHelper); - awaiterEmitted = true; - } - } - } - function emitSourceFileNode(node) { - writeLine(); - emitShebang(); - emitDetachedCommentsAndUpdateCommentsInfo(node); - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; - emitModule(node); - } - else { - bundleEmitDelegates[modulekind](node, true); - } - } - else { - var startIndex = emitDirectivePrologues(node.statements, false); - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - } - emitLeadingComments(node.endOfFileToken); - } - function emit(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - function emitNodeWithCommentsAndWithoutSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); - } - function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { - if (node) { - if (node.flags & 2) { - return emitCommentsOnNotEmittedNode(node); - } - if (isSpecializedCommentHandling(node)) { - return emitNodeWithoutSourceMap(node); - } - var emitComments_1 = shouldEmitLeadingAndTrailingComments(node); - if (emitComments_1) { - emitLeadingComments(node); - } - emitNodeConsideringSourcemap(node); - if (emitComments_1) { - emitTrailingComments(node); - } - } - } - function emitNodeWithSourceMap(node) { - if (node) { - emitStart(node); - emitNodeWithoutSourceMap(node); - emitEnd(node); - } - } - function emitNodeWithoutSourceMap(node) { - if (node) { - emitJavaScriptWorker(node); - } - } - function changeSourceMapEmit(writer) { - sourceMap = writer; - emitStart = writer.emitStart; - emitEnd = writer.emitEnd; - emitPos = writer.emitPos; - setSourceFile = writer.setSourceFile; - } - function withTemporaryNoSourceMap(callback) { - var prevSourceMap = sourceMap; - setSourceMapWriterEmit(ts.getNullSourceMapWriter()); - callback(); - setSourceMapWriterEmit(prevSourceMap); - } - function isSpecializedCommentHandling(node) { - switch (node.kind) { - case 222: - case 220: - case 230: - case 229: - case 223: - case 235: - return true; - } - } - function shouldEmitLeadingAndTrailingComments(node) { - switch (node.kind) { - case 200: - return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 225: - return shouldEmitModuleDeclaration(node); - case 224: - return shouldEmitEnumDeclaration(node); - } - ts.Debug.assert(!isSpecializedCommentHandling(node)); - if (node.kind !== 199 && - node.parent && - node.parent.kind === 180 && - node.parent.body === node && - languageVersion <= 1) { - return false; - } - return true; - } - function emitJavaScriptWorker(node) { - switch (node.kind) { - case 69: - return emitIdentifier(node); - case 142: - return emitParameter(node); - case 147: - case 146: - return emitMethod(node); - case 149: - case 150: - return emitAccessor(node); - case 97: - return emitThis(node); - case 95: - return emitSuper(node); - case 93: - return write("null"); - case 99: - return write("true"); - case 84: - return write("false"); - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - return emitLiteral(node); - case 189: - return emitTemplateExpression(node); - case 197: - return emitTemplateSpan(node); - case 241: - case 242: - return emitJsxElement(node); - case 244: - return emitJsxText(node); - case 248: - return emitJsxExpression(node); - case 139: - return emitQualifiedName(node); - case 167: - return emitObjectBindingPattern(node); - case 168: - return emitArrayBindingPattern(node); - case 169: - return emitBindingElement(node); - case 170: - return emitArrayLiteral(node); - case 171: - return emitObjectLiteral(node); - case 253: - return emitPropertyAssignment(node); - case 254: - return emitShorthandPropertyAssignment(node); - case 140: - return emitComputedPropertyName(node); - case 172: - return emitPropertyAccess(node); - case 173: - return emitIndexedAccess(node); - case 174: - return emitCallExpression(node); - case 175: - return emitNewExpression(node); - case 176: - return emitTaggedTemplateExpression(node); - case 177: - case 195: - case 196: - return emit(node.expression); - case 178: - return emitParenExpression(node); - case 220: - case 179: - case 180: - return emitFunctionDeclaration(node); - case 181: - return emitDeleteExpression(node); - case 182: - return emitTypeOfExpression(node); - case 183: - return emitVoidExpression(node); - case 184: - return emitAwaitExpression(node); - case 185: - return emitPrefixUnaryExpression(node); - case 186: - return emitPostfixUnaryExpression(node); - case 187: - return emitBinaryExpression(node); - case 188: - return emitConditionalExpression(node); - case 191: - return emitSpreadElementExpression(node); - case 190: - return emitYieldExpression(node); - case 193: - return; - case 199: - case 226: - return emitBlock(node); - case 200: - return emitVariableStatement(node); - case 201: - return write(";"); - case 202: - return emitExpressionStatement(node); - case 203: - return emitIfStatement(node); - case 204: - return emitDoStatement(node); - case 205: - return emitWhileStatement(node); - case 206: - return emitForStatement(node); - case 208: - case 207: - return emitForInOrForOfStatement(node); - case 209: - case 210: - return emitBreakOrContinueStatement(node); - case 211: - return emitReturnStatement(node); - case 212: - return emitWithStatement(node); - case 213: - return emitSwitchStatement(node); - case 249: - case 250: - return emitCaseOrDefaultClause(node); - case 214: - return emitLabeledStatement(node); - case 215: - return emitThrowStatement(node); - case 216: - return emitTryStatement(node); - case 252: - return emitCatchClause(node); - case 217: - return emitDebuggerStatement(node); - case 218: - return emitVariableDeclaration(node); - case 192: - return emitClassExpression(node); - case 221: - return emitClassDeclaration(node); - case 222: - return emitInterfaceDeclaration(node); - case 224: - return emitEnumDeclaration(node); - case 255: - return emitEnumMember(node); - case 225: - return emitModuleDeclaration(node); - case 230: - return emitImportDeclaration(node); - case 229: - return emitImportEqualsDeclaration(node); - case 236: - return emitExportDeclaration(node); - case 235: - return emitExportAssignment(node); - case 256: - return emitSourceFileNode(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - function isTripleSlashComment(comment) { - if (currentText.charCodeAt(comment.pos + 1) === 47 && - comment.pos + 2 < comment.end && - currentText.charCodeAt(comment.pos + 2) === 47) { - var textSubStr = currentText.substring(comment.pos, comment.end); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; - } - function getLeadingCommentsToEmit(node) { - if (node.parent) { - if (node.parent.kind === 256 || node.pos !== node.parent.pos) { - if (hasDetachedComments(node.pos)) { - return getLeadingCommentsWithoutDetachedComments(); - } - else { - return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); - } - } - } - } - function getTrailingCommentsToEmit(node) { - if (node.parent) { - if (node.parent.kind === 256 || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentText, node.end); - } - } - } - function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, false); - } - function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, true); - } - function emitLeadingCommentsWorker(node, isEmittedNode) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (isEmittedNode) { - leadingComments = getLeadingCommentsToEmit(node); - } - else { - if (node.pos === 0) { - leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); - } - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); - ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); - } - function emitTrailingComments(node) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = getTrailingCommentsToEmit(node); - ts.emitComments(currentText, currentLineMap, writer, trailingComments, false, newLine, writeComment); - } - function emitTrailingCommentsOfPosition(pos) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = ts.getTrailingCommentRanges(currentText, pos); - ts.emitComments(currentText, currentLineMap, writer, trailingComments, true, newLine, writeComment); - } - function emitLeadingCommentsOfPositionWorker(pos) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (hasDetachedComments(pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - leadingComments = ts.getLeadingCommentRanges(currentText, pos); - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); - ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); - } - function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, comment, newLine) { - emitPos(comment.pos); - ts.writeCommentRange(text, lineMap, writer, comment, newLine); - emitPos(comment.end); - } - function emitShebang() { - var shebang = ts.getShebang(currentText); - if (shebang) { - write(shebang); - writeLine(); - } - } - var _a, _b; - } - function emitFile(_a, sourceFiles, isBundledEmit) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { emittedFilesList.push(jsFilePath); @@ -36705,21 +44387,2015 @@ var ts; } } } + function printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNameSet = ts.createMap(); + isOwnFileEmit = !isBundledEmit; + if (isBundledEmit && moduleKind) { + for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { + var sourceFile = sourceFiles_4[_a]; + emitEmitHelpers(sourceFile); + } + } + ts.forEach(sourceFiles, printSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + } + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); + } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); + } + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + sourceMap.reset(); + comments.reset(); + writer.reset(); + tempFlags = 0; + currentSourceFile = undefined; + currentText = undefined; + extendsEmitted = false; + assignEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + isOwnFileEmit = false; + } + function printSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + currentFileIdentifiers = node.identifiers; + sourceMap.setSourceFile(node); + comments.setSourceFile(node); + emitNodeWithNotification(node, emitWorker); + } + function emit(node) { + emitNodeWithNotification(node, emitWithComments); + } + function emitWithComments(node) { + emitNodeWithComments(node, emitWithSourceMap); + } + function emitWithSourceMap(node) { + emitNodeWithSourceMap(node, emitWorker); + } + function emitIdentifierName(node) { + if (node) { + emitNodeWithNotification(node, emitIdentifierNameWithComments); + } + } + function emitIdentifierNameWithComments(node) { + emitNodeWithComments(node, emitWorker); + } + function emitExpression(node) { + emitNodeWithNotification(node, emitExpressionWithComments); + } + function emitExpressionWithComments(node) { + emitNodeWithComments(node, emitExpressionWithSourceMap); + } + function emitExpressionWithSourceMap(node) { + emitNodeWithSourceMap(node, emitExpressionWorker); + } + function emitNodeWithNotification(node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(node, emitCallback); + } + else { + emitCallback(node); + } + } + } + function emitNodeWithSourceMap(node, emitCallback) { + if (node) { + emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + emitCallback(node); + emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + function shouldSkipLeadingCommentsForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 16384) !== 0; + } + function shouldSkipLeadingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 512) !== 0; + } + function shouldSkipTrailingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 1024) !== 0; + } + function shouldSkipSourceMapForChildren(node) { + return (node.emitFlags & 2048) !== 0; + } + function emitWorker(node) { + if (tryEmitSubstitute(node, emitWorker, false)) { + return; + } + var kind = node.kind; + switch (kind) { + case 12: + case 13: + case 14: + return emitLiteral(node); + case 69: + return emitIdentifier(node); + case 74: + case 77: + case 82: + case 103: + case 110: + case 111: + case 112: + case 113: + case 115: + case 117: + case 118: + case 120: + case 122: + case 130: + case 128: + case 132: + case 133: + case 137: + return writeTokenNode(node); + case 139: + return emitQualifiedName(node); + case 140: + return emitComputedPropertyName(node); + case 141: + return emitTypeParameter(node); + case 142: + return emitParameter(node); + case 143: + return emitDecorator(node); + case 144: + return emitPropertySignature(node); + case 145: + return emitPropertyDeclaration(node); + case 146: + return emitMethodSignature(node); + case 147: + return emitMethodDeclaration(node); + case 148: + return emitConstructor(node); + case 149: + case 150: + return emitAccessorDeclaration(node); + case 151: + return emitCallSignature(node); + case 152: + return emitConstructSignature(node); + case 153: + return emitIndexSignature(node); + case 154: + return emitTypePredicate(node); + case 155: + return emitTypeReference(node); + case 156: + return emitFunctionType(node); + case 157: + return emitConstructorType(node); + case 158: + return emitTypeQuery(node); + case 159: + return emitTypeLiteral(node); + case 160: + return emitArrayType(node); + case 161: + return emitTupleType(node); + case 162: + return emitUnionType(node); + case 163: + return emitIntersectionType(node); + case 164: + return emitParenthesizedType(node); + case 194: + return emitExpressionWithTypeArguments(node); + case 165: + return emitThisType(node); + case 166: + return emitLiteralType(node); + case 167: + return emitObjectBindingPattern(node); + case 168: + return emitArrayBindingPattern(node); + case 169: + return emitBindingElement(node); + case 197: + return emitTemplateSpan(node); + case 198: + return emitSemicolonClassElement(node); + case 199: + return emitBlock(node); + case 200: + return emitVariableStatement(node); + case 201: + return emitEmptyStatement(node); + case 202: + return emitExpressionStatement(node); + case 203: + return emitIfStatement(node); + case 204: + return emitDoStatement(node); + case 205: + return emitWhileStatement(node); + case 206: + return emitForStatement(node); + case 207: + return emitForInStatement(node); + case 208: + return emitForOfStatement(node); + case 209: + return emitContinueStatement(node); + case 210: + return emitBreakStatement(node); + case 211: + return emitReturnStatement(node); + case 212: + return emitWithStatement(node); + case 213: + return emitSwitchStatement(node); + case 214: + return emitLabeledStatement(node); + case 215: + return emitThrowStatement(node); + case 216: + return emitTryStatement(node); + case 217: + return emitDebuggerStatement(node); + case 218: + return emitVariableDeclaration(node); + case 219: + return emitVariableDeclarationList(node); + case 220: + return emitFunctionDeclaration(node); + case 221: + return emitClassDeclaration(node); + case 222: + return emitInterfaceDeclaration(node); + case 223: + return emitTypeAliasDeclaration(node); + case 224: + return emitEnumDeclaration(node); + case 225: + return emitModuleDeclaration(node); + case 226: + return emitModuleBlock(node); + case 227: + return emitCaseBlock(node); + case 229: + return emitImportEqualsDeclaration(node); + case 230: + return emitImportDeclaration(node); + case 231: + return emitImportClause(node); + case 232: + return emitNamespaceImport(node); + case 233: + return emitNamedImports(node); + case 234: + return emitImportSpecifier(node); + case 235: + return emitExportAssignment(node); + case 236: + return emitExportDeclaration(node); + case 237: + return emitNamedExports(node); + case 238: + return emitExportSpecifier(node); + case 239: + return; + case 240: + return emitExternalModuleReference(node); + case 244: + return emitJsxText(node); + case 243: + return emitJsxOpeningElement(node); + case 245: + return emitJsxClosingElement(node); + case 246: + return emitJsxAttribute(node); + case 247: + return emitJsxSpreadAttribute(node); + case 248: + return emitJsxExpression(node); + case 249: + return emitCaseClause(node); + case 250: + return emitDefaultClause(node); + case 251: + return emitHeritageClause(node); + case 252: + return emitCatchClause(node); + case 253: + return emitPropertyAssignment(node); + case 254: + return emitShorthandPropertyAssignment(node); + case 255: + return emitEnumMember(node); + case 256: + return emitSourceFile(node); + } + if (ts.isExpression(node)) { + return emitExpressionWorker(node); + } + } + function emitExpressionWorker(node) { + if (tryEmitSubstitute(node, emitExpressionWorker, true)) { + return; + } + var kind = node.kind; + switch (kind) { + case 8: + return emitNumericLiteral(node); + case 9: + case 10: + case 11: + return emitLiteral(node); + case 69: + return emitIdentifier(node); + case 84: + case 93: + case 95: + case 99: + case 97: + return writeTokenNode(node); + case 170: + return emitArrayLiteralExpression(node); + case 171: + return emitObjectLiteralExpression(node); + case 172: + return emitPropertyAccessExpression(node); + case 173: + return emitElementAccessExpression(node); + case 174: + return emitCallExpression(node); + case 175: + return emitNewExpression(node); + case 176: + return emitTaggedTemplateExpression(node); + case 177: + return emitTypeAssertionExpression(node); + case 178: + return emitParenthesizedExpression(node); + case 179: + return emitFunctionExpression(node); + case 180: + return emitArrowFunction(node); + case 181: + return emitDeleteExpression(node); + case 182: + return emitTypeOfExpression(node); + case 183: + return emitVoidExpression(node); + case 184: + return emitAwaitExpression(node); + case 185: + return emitPrefixUnaryExpression(node); + case 186: + return emitPostfixUnaryExpression(node); + case 187: + return emitBinaryExpression(node); + case 188: + return emitConditionalExpression(node); + case 189: + return emitTemplateExpression(node); + case 190: + return emitYieldExpression(node); + case 191: + return emitSpreadElementExpression(node); + case 192: + return emitClassExpression(node); + case 193: + return; + case 195: + return emitAsExpression(node); + case 196: + return emitNonNullExpression(node); + case 241: + return emitJsxElement(node); + case 242: + return emitJsxSelfClosingElement(node); + case 288: + return emitPartiallyEmittedExpression(node); + } + } + function emitNumericLiteral(node) { + emitLiteral(node); + if (node.trailingComment) { + write(" /*" + node.trailingComment + "*/"); + } + } + function emitLiteral(node) { + var text = getLiteralTextOfNode(node); + if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) + && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else { + write(text); + } + } + function emitIdentifier(node) { + if (node.emitFlags & 16) { + writeLines(umdHelper); + } + else { + write(getTextOfNode(node, false)); + } + } + function emitQualifiedName(node) { + emitEntityName(node.left); + write("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + write("["); + emitExpression(node.expression); + write("]"); + } + function emitTypeParameter(node) { + emit(node.name); + emitWithPrefix(" extends ", node.constraint); + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitExpressionWithPrefix(" = ", node.initializer); + emitWithPrefix(": ", node.type); + } + function emitDecorator(decorator) { + write("@"); + emitExpression(decorator.expression); + } + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emitWithPrefix(": ", node.type); + emitExpressionWithPrefix(" = ", node.initializer); + write(";"); + } + function emitMethodSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.asteriskToken, "*"); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + write("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.kind === 149 ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitConstructSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitSemicolonClassElement(node) { + write(";"); + } + function emitTypePredicate(node) { + emit(node.parameterName); + write(" is "); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitConstructorType(node) { + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitTypeQuery(node) { + write("typeof "); + emit(node.exprName); + } + function emitTypeLiteral(node) { + write("{"); + emitList(node, node.members, 65); + write("}"); + } + function emitArrayType(node) { + emit(node.elementType); + write("[]"); + } + function emitTupleType(node) { + write("["); + emitList(node, node.elementTypes, 336); + write("]"); + } + function emitUnionType(node) { + emitList(node, node.types, 260); + } + function emitIntersectionType(node) { + emitList(node, node.types, 264); + } + function emitParenthesizedType(node) { + write("("); + emit(node.type); + write(")"); + } + function emitThisType(node) { + write("this"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitObjectBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("{}"); + } + else { + write("{"); + emitList(node, elements, 432); + write("}"); + } + } + function emitArrayBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + write("["); + emitList(node, node.elements, 304); + write("]"); + } + } + function emitBindingElement(node) { + emitWithSuffix(node.propertyName, ": "); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitArrayLiteralExpression(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + var preferNewLine = node.multiLine ? 32768 : 0; + emitExpressionList(node, elements, 4466 | preferNewLine); + } + } + function emitObjectLiteralExpression(node) { + var properties = node.properties; + if (properties.length === 0) { + write("{}"); + } + else { + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 32768 : 0; + var allowTrailingComma = languageVersion >= 1 ? 32 : 0; + emitList(node, properties, 978 | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + } + function emitPropertyAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(node.emitFlags & 1048576)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot); + write(shouldEmitDotDot ? ".." : "."); + increaseIndentIf(indentAfterDot); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + function needsDotDotForPropertyAccess(expression) { + if (expression.kind === 8) { + var text = getLiteralTextOfNode(expression); + return text.indexOf(ts.tokenToString(21)) < 0; + } + else { + var constantValue = tryGetConstEnumValue(expression); + return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + function emitElementAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + emitExpression(node.expression); + write("["); + emitExpression(node.argumentExpression); + write("]"); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 1296); + } + function emitNewExpression(node) { + write("new "); + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 9488); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + write(" "); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + if (node.type) { + write("<"); + emit(node.type); + write(">"); + } + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + write("("); + emitExpression(node.expression); + write(")"); + } + function emitFunctionExpression(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitWithPrefix(": ", node.type); + write(" =>"); + } + function emitDeleteExpression(node) { + write("delete "); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + write("typeof "); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + write("void "); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + write("await "); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + write(" "); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + var operand = node.operand; + return operand.kind === 185 + && ((node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) + || (node.operator === 36 && (operand.operator === 36 || operand.operator === 42))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 24; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + writeTokenText(node.operatorToken.kind); + increaseIndentIf(indentAfterOperator, " "); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, " "); + write("?"); + increaseIndentIf(indentAfterQuestion, " "); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, " "); + write(":"); + increaseIndentIf(indentAfterColon, " "); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 131072); + } + function emitYieldExpression(node) { + write(node.asteriskToken ? "yield*" : "yield"); + emitExpressionWithPrefix(" ", node.expression); + } + function emitSpreadElementExpression(node) { + write("..."); + emitExpression(node.expression); + } + function emitClassExpression(node) { + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + write(" as "); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + write("!"); + } + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + function emitBlock(node, format) { + if (isSingleLineEmptyBlock(node)) { + writeToken(15, node.pos, node); + write(" "); + writeToken(16, node.statements.end, node); + } + else { + writeToken(15, node.pos, node); + emitBlockStatements(node); + writeToken(16, node.statements.end, node); + } + } + function emitBlockStatements(node) { + if (node.emitFlags & 32) { + emitList(node, node.statements, 384); + } + else { + emitList(node, node.statements, 65); + } + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + write(";"); + } + function emitEmptyStatement(node) { + write(";"); + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + write(";"); + } + function emitIfStatement(node) { + var openParenPos = writeToken(88, node.pos, node); + write(" "); + writeToken(17, openParenPos, node); + emitExpression(node.expression); + writeToken(18, node.expression.end, node); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + writeToken(80, node.thenStatement.end, node); + if (node.elseStatement.kind === 203) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (ts.isBlock(node.statement)) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emitExpression(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos, node); + emitForBinding(node.initializer); + write(";"); + emitExpressionWithPrefix(" ", node.condition); + write(";"); + emitExpressionWithPrefix(" ", node.incrementor); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos); + emitForBinding(node.initializer); + write(" in "); + emitExpression(node.expression); + writeToken(18, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForOfStatement(node) { + var openParenPos = writeToken(86, node.pos); + write(" "); + writeToken(17, openParenPos); + emitForBinding(node.initializer); + write(" of "); + emitExpression(node.expression); + writeToken(18, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 219) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + writeToken(75, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitBreakStatement(node) { + writeToken(70, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + writeToken(94, node.pos, node); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitWithStatement(node) { + write("with ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = writeToken(96, node.pos); + write(" "); + writeToken(17, openParenPos); + emitExpression(node.expression); + writeToken(18, node.expression.end); + write(" "); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function emitThrowStatement(node) { + write("throw"); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(76, node.pos); + write(";"); + } + function emitVariableDeclaration(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitVariableDeclarationList(node) { + write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + emitList(node, node.declarations, 272); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.asteriskToken ? "function* " : "function "); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + if (node.emitFlags & 4194304) { + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + tempFlags = savedTempFlags; + } + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + write(" "); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + write(";"); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { + if (body.emitFlags & 32) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2) + || shouldWriteClosingLineTerminator(body, body.statements, 2)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(parentNode, body) { + write(" {"); + increaseIndent(); + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker); + decreaseIndent(); + writeToken(16, body.statements.end, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + var statementOffset = emitPrologueDirectives(body.statements, true); + var helpersEmitted = emitHelpers(body); + if (statementOffset === 0 && !helpersEmitted && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 384); + increaseIndent(); + } + else { + emitList(body, body.statements, 1, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("class"); + emitNodeWithPrefix(" ", node.name, emitIdentifierName); + var indentedFlag = node.emitFlags & 524288; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 65); + write("}"); + if (indentedFlag) { + decreaseIndent(); + } + tempFlags = savedTempFlags; + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("interface "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256); + write(" {"); + emitList(node, node.members, 65); + write("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("type "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + write(" = "); + emit(node.type); + write(";"); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + write("enum "); + emit(node.name); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 81); + write("}"); + tempFlags = savedTempFlags; + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + write(node.flags & 16 ? "namespace " : "module "); + emit(node.name); + var body = node.body; + while (body.kind === 225) { + write("."); + emit(body.name); + body = body.body; + } + write(" "); + emit(body); + } + function emitModuleBlock(node) { + if (isSingleLineEmptyBlock(node)) { + write("{ }"); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + write("{"); + increaseIndent(); + emitBlockStatements(node); + write("}"); + tempFlags = savedTempFlags; + } + } + function emitCaseBlock(node) { + writeToken(15, node.pos); + emitList(node, node.clauses, 65); + writeToken(16, node.clauses.end); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + emit(node.name); + write(" = "); + emitModuleReference(node.moduleReference); + write(";"); + } + function emitModuleReference(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + if (node.importClause) { + emit(node.importClause); + write(" from "); + } + emitExpression(node.moduleSpecifier); + write(";"); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + write(", "); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + write("* as "); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + write(node.isExportEquals ? "export = " : "export default "); + emitExpression(node.expression); + write(";"); + } + function emitExportDeclaration(node) { + write("export "); + if (node.exportClause) { + emit(node.exportClause); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + emitExpression(node.moduleSpecifier); + } + write(";"); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + write("{"); + emitList(node, node.elements, 432); + write("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + write(" as "); + } + emit(node.name); + } + function emitExternalModuleReference(node) { + write("require("); + emitExpression(node.expression); + write(")"); + } + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 131072); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + write("<"); + emitJsxTagName(node.tagName); + write(" "); + emitList(node, node.attributes, 131328); + write("/>"); + } + function emitJsxOpeningElement(node) { + write("<"); + emitJsxTagName(node.tagName); + writeIfAny(node.attributes, " "); + emitList(node, node.attributes, 131328); + write(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, true)); + } + function emitJsxClosingElement(node) { + write(""); + } + function emitJsxAttribute(node) { + emit(node.name); + emitWithPrefix("=", node.initializer); + } + function emitJsxSpreadAttribute(node) { + write("{..."); + emitExpression(node.expression); + write("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + write("{"); + emitExpression(node.expression); + write("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 69) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitCaseClause(node) { + write("case "); + emitExpression(node.expression); + write(":"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitDefaultClause(node) { + write("default:"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitCaseOrDefaultClauseStatements(parentNode, statements) { + var emitAsSingleStatement = statements.length === 1 && + (ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (emitAsSingleStatement) { + write(" "); + emit(statements[0]); + } + else { + emitList(parentNode, statements, 81985); + } + } + function emitHeritageClause(node) { + write(" "); + writeTokenText(node.token); + write(" "); + emitList(node, node.types, 272); + } + function emitCatchClause(node) { + writeLine(); + var openParenPos = writeToken(72, node.pos); + write(" "); + writeToken(17, openParenPos); + emit(node.variableDeclaration); + writeToken(18, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + write(" "); + emit(node.block); + } + function emitPropertyAssignment(node) { + emit(node.name); + write(": "); + var initializer = node.initializer; + if (!shouldSkipLeadingCommentsForNode(initializer)) { + var commentRange = initializer.commentRange || initializer; + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + write(" = "); + emitExpression(node.objectAssignmentInitializer); + } + } + function emitEnumMember(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitSourceFile(node) { + writeLine(); + emitShebang(); + emitBodyWithDetachedComments(node, node.statements, emitSourceFileWorker); + } + function emitSourceFileWorker(node) { + var statements = node.statements; + var statementOffset = emitPrologueDirectives(statements); + var savedTempFlags = tempFlags; + tempFlags = 0; + emitHelpers(node); + emitList(node, statements, 1, statementOffset); + tempFlags = savedTempFlags; + } + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + function emitPrologueDirectives(statements, startWithNewLine) { + for (var i = 0; i < statements.length; i++) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + return i; + } + } + return statements.length; + } + function emitHelpers(node) { + var emitFlags = node.emitFlags; + var helpersEmitted = false; + if (emitFlags & 1) { + helpersEmitted = emitEmitHelpers(currentSourceFile); + } + if (emitFlags & 2) { + writeLines(exportStarHelper); + helpersEmitted = true; + } + if (emitFlags & 4) { + writeLines(superHelper); + helpersEmitted = true; + } + if (emitFlags & 8) { + writeLines(advancedSuperHelper); + helpersEmitted = true; + } + return helpersEmitted; + } + function emitEmitHelpers(node) { + if (compilerOptions.noEmitHelpers) { + return false; + } + if (compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + return false; + } + var helpersEmitted = false; + if ((languageVersion < 2) && (!extendsEmitted && node.flags & 1024)) { + writeLines(extendsHelper); + extendsEmitted = true; + helpersEmitted = true; + } + if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 16384)) { + writeLines(assignHelper); + assignEmitted = true; + } + if (!decorateEmitted && node.flags & 2048) { + writeLines(decorateHelper); + if (compilerOptions.emitDecoratorMetadata) { + writeLines(metadataHelper); + } + decorateEmitted = true; + helpersEmitted = true; + } + if (!paramEmitted && node.flags & 4096) { + writeLines(paramHelper); + paramEmitted = true; + helpersEmitted = true; + } + if (!awaiterEmitted && node.flags & 8192) { + writeLines(awaiterHelper); + if (languageVersion < 2) { + writeLines(generatorHelper); + } + awaiterEmitted = true; + helpersEmitted = true; + } + if (helpersEmitted) { + writeLine(); + } + return helpersEmitted; + } + function writeLines(text) { + var lines = text.split(/\r\n|\r|\n/g); + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line.length) { + if (i > 0) { + writeLine(); + } + write(line); + } + } + } + function emitShebang() { + var shebang = ts.getShebang(currentText); + if (shebang) { + write(shebang); + writeLine(); + } + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 256); + write(" "); + } + } + function emitWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emit); + } + function emitExpressionWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emitExpression); + } + function emitNodeWithPrefix(prefix, node, emit) { + if (node) { + write(prefix); + emit(node); + } + } + function emitWithSuffix(node, suffix) { + if (node) { + emit(node); + write(suffix); + } + } + function tryEmitSubstitute(node, emitNode, isExpression) { + if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { + var substitute = onSubstituteNode(node, isExpression); + if (substitute !== node) { + substitute.emitFlags |= 128; + emitNode(substitute); + return true; + } + } + return false; + } + function tryEmitConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + write(String(constantValue)); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : getTextOfNode(node.argumentExpression); + write(" /* " + propertyName + " */"); + } + return true; + } + return false; + } + function emitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + write(" "); + emit(node); + } + else { + writeLine(); + increaseIndent(); + emit(node); + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 24577); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 26960); + } + function emitTypeParameters(parentNode, typeParameters) { + emitList(parentNode, typeParameters, 26960); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 1360); + } + function emitParametersForArrow(parentNode, parameters) { + if (parameters && + parameters.length === 1 && + parameters[0].type === undefined && + parameters[0].pos === parentNode.pos) { + emit(parameters[0]); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 4432); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 8192) { + return; + } + var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + if (isEmpty && format & 16384) { + return; + } + if (format & 7680) { + write(getOpeningBracket(format)); + } + if (isEmpty) { + if (format & 1) { + writeLine(); + } + else if (format & 128) { + write(" "); + } + } + else { + var mayEmitInterveningComments = (format & 131072) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 128) { + write(" "); + } + if (format & 64) { + increaseIndent(); + } + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = void 0; + var delimiter = getDelimiter(format); + for (var i = 0; i < count; i++) { + var child = children[start + i]; + if (previousSibling) { + write(delimiter); + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + if ((format & (3 | 64)) === 0) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 256) { + write(" "); + } + } + if (shouldEmitInterveningComments) { + var commentRange = child.commentRange || child; + emitTrailingCommentsOfPosition(commentRange.pos); + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + var hasTrailingComma = (format & 32) && children.hasTrailingComma; + if (format & 16 && hasTrailingComma) { + write(","); + } + if (format & 64) { + decreaseIndent(); + } + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 128) { + write(" "); + } + } + if (format & 7680) { + write(getClosingBracket(format)); + } + } + function writeIfAny(nodes, text) { + if (nodes && nodes.length > 0) { + write(text); + } + } + function writeIfPresent(node, text) { + if (node !== undefined) { + write(text); + } + } + function writeToken(token, pos, contextNode) { + var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); + var tokenEndPos = writeTokenText(token, tokenStartPos); + return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); + } + function shouldSkipLeadingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 4096) !== 0; + } + function shouldSkipTrailingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 8192) !== 0; + } + function writeTokenText(token, pos) { + var tokenString = ts.tokenToString(token); + write(tokenString); + return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; + } + function writeTokenNode(node) { + if (node) { + emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + writeTokenText(node.kind); + emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (valueToWriteWhenNotIndenting) { + write(valueToWriteWhenNotIndenting); + } + } + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1) { + return true; + } + if (format & 2) { + if (format & 32768) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1) { + return true; + } + else if (format & 2) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return nextNode.startsOnNewLine; + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1) { + return (format & 65536) === 0; + } + else if (format & 2) { + if (format & 32768) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = node.startsOnNewLine; + if (startsOnNewLine === undefined) { + return (format & 32768) !== 0; + } + return startsOnNewLine; + } + return (format & 32768) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + if (node2.startsOnNewLine) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 178 && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return getGeneratedIdentifier(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return ts.unescapeIdentifier(node.text); + } + else if (node.kind === 9 && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node) { + if (node.kind === 9 && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode); + } + } + return ts.getLiteralText(node, currentSourceFile, languageVersion); + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } + function isSingleLineEmptyBlock(block) { + return !block.multiLine + && block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function isUniqueName(name) { + return !resolver.hasGlobalName(name) && + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); + } + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals && ts.hasProperty(node.locals, name)) { + if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { + return false; + } + } + } + return true; + } + function makeTempVariableName(flags) { + if (flags && !(tempFlags & flags)) { + var name_43 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_43)) { + tempFlags |= flags; + return name_43; + } + } + while (true) { + var count = tempFlags & 268435455; + tempFlags++; + if (count !== 8 && count !== 13) { + var name_44 = count < 26 + ? "_" + String.fromCharCode(97 + count) + : "_" + (count - 26); + if (isUniqueName(name_44)) { + return name_44; + } + } + } + } + function makeUniqueName(baseName) { + if (baseName.charCodeAt(baseName.length - 1) !== 95) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (isUniqueName(generatedName)) { + return generatedNameSet[generatedName] = generatedName; + } + i++; + } + } + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); + var baseName = expr.kind === 9 ? + ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + return makeUniqueName(baseName); + } + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForNode(node) { + switch (node.kind) { + case 69: + return makeUniqueName(getTextOfNode(node)); + case 225: + case 224: + return generateNameForModuleOrEnum(node); + case 230: + case 236: + return generateNameForImportOrExportDeclaration(node); + case 220: + case 221: + case 235: + return generateNameForExportDefault(); + case 192: + return generateNameForClassExpression(); + default: + return makeTempVariableName(0); + } + } + function generateName(name) { + switch (name.autoGenerateKind) { + case 1: + return makeTempVariableName(0); + case 2: + return makeTempVariableName(268435456); + case 3: + return makeUniqueName(name.text); + } + ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + if (ts.isIdentifier(node) + && node.autoGenerateKind === 4 + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + return node; + } + function getGeneratedIdentifier(name) { + if (name.autoGenerateKind === 4) { + var node = getNodeForGeneratedName(name); + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + } + else { + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(generateName(name))); + } + } + function createDelimiterMap() { + var delimiters = []; + delimiters[0] = ""; + delimiters[16] = ","; + delimiters[4] = " |"; + delimiters[8] = " &"; + return delimiters; + } + function getDelimiter(format) { + return delimiters[format & 28]; + } + function createBracketsMap() { + var brackets = []; + brackets[512] = ["{", "}"]; + brackets[1024] = ["(", ")"]; + brackets[2048] = ["<", ">"]; + brackets[4096] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 7680][0]; + } + function getClosingBracket(format) { + return brackets[format & 7680][1]; + } } ts.emitFiles = emitFiles; })(ts || (ts = {})); var ts; (function (ts) { - ts.programTime = 0; - ts.emitTime = 0; - ts.ioReadTime = 0; - ts.ioWriteTime = 0; - ts.version = "2.0.0"; + ts.version = "2.1.0"; var emptyArray = []; - var defaultTypeRoots = ["node_modules/@types"]; - function findConfigFile(searchPath, fileExists) { + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } while (true) { - var fileName = ts.combinePaths(searchPath, "tsconfig.json"); + var fileName = ts.combinePaths(searchPath, configName); if (fileExists(fileName)) { return fileName; } @@ -36794,51 +46470,29 @@ var ts; return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; } function moduleHasNonRelativeName(moduleName) { - if (ts.isRootedDiskPath(moduleName)) { - return false; - } - var i = moduleName.lastIndexOf("./", 1); - var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); - return !startsWithDotSlashOrDotDotSlash; + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent; - try { - var jsonText = state.host.readFile(packageJsonPath); - jsonContent = jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - jsonContent = {}; - } - var typesFile; - var fieldName; - if (jsonContent.typings) { - if (typeof jsonContent.typings === "string") { - fieldName = "typings"; - typesFile = jsonContent.typings; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } } } } - if (!typesFile && jsonContent.types) { - if (typeof jsonContent.types === "string") { - fieldName = "types"; - typesFile = jsonContent.types; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); - } - } - } - if (typesFile) { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { return typesFilePath; } if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { @@ -36850,6 +46504,15 @@ var ts; } return undefined; } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -36862,11 +46525,28 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - if (!currentDirectory) { - return undefined; - } - return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); + return currentDirectory && getDefaultTypeRoots(currentDirectory, host); } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_15 = ts.getDirectoryPath(currentDirectory); + if (parent_15 === currentDirectory) { + break; + } + currentDirectory = parent_15; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -37072,7 +46752,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); @@ -37188,7 +46868,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } function directoryProbablyExists(directoryName, host) { @@ -37196,9 +46876,9 @@ var ts; } ts.directoryProbablyExists = directoryProbablyExists; function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingOrKeepingExtension) { - return resolvedByAddingOrKeepingExtension; + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; } if (ts.hasJavaScriptFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); @@ -37206,39 +46886,37 @@ var ts; var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); } } - function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } - return ts.forEach(extensions, tryLoad); - function tryLoad(ext) { - if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { - return undefined; + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } - var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } + failedLookupLocation.push(fileName); + return undefined; } } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var packageJsonPath = pathToPackageJson(candidate); var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { @@ -37246,7 +46924,9 @@ var ts; } var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); if (typesFile) { - var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); if (result) { return result; } @@ -37265,6 +46945,9 @@ var ts; } return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); @@ -37337,14 +47020,8 @@ var ts; : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } ts.classicNameResolver = classicNameResolver; - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1, - noImplicitAny: false, - sourceMap: false - }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = {}; + var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } @@ -37352,9 +47029,10 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - var start = new Date().getTime(); + ts.performance.mark("beforeIORead"); text = ts.sys.readFile(fileName, options.charset); - ts.ioReadTime += new Date().getTime() - start; + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } catch (e) { if (onError) { @@ -37367,7 +47045,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (ts.hasProperty(existingDirectories, directoryPath)) { + if (directoryPath in existingDirectories) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -37386,11 +47064,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = {}; + outputFingerprints = ts.createMap(); } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { + if (mtimeBefore && fileName in outputFingerprints) { var fingerprint = outputFingerprints[fileName]; if (fingerprint.byteOrderMark === writeByteOrderMark && fingerprint.hash === hash && @@ -37408,7 +47086,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - var start = new Date().getTime(); + ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -37416,7 +47094,8 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.ioWriteTime += new Date().getTime() - start; + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } catch (e) { if (onError) { @@ -37442,6 +47121,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -37455,6 +47135,22 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; + } + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -37483,25 +47179,17 @@ var ts; return []; } var resolutions = []; - var cache = {}; - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_35 = names_1[_i]; - var result = void 0; - if (ts.hasProperty(cache, name_35)) { - result = cache[name_35]; - } - else { - result = loader(name_35, containingFile); - cache[name_35] = result; - } + var cache = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_45 = names_2[_i]; + var result = name_45 in cache + ? cache[name_45] + : cache[name_45] = loader(name_45, containingFile); resolutions.push(result); } return resolutions; } - function getInferredTypesRoot(options, rootFiles, host) { - return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - } - function getAutomaticTypeDirectiveNames(options, rootFiles, host) { + function getAutomaticTypeDirectiveNames(options, host) { if (options.types) { return options.types; } @@ -37512,7 +47200,15 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - result = result.concat(host.getDirectories(root)); + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } } } } @@ -37527,13 +47223,13 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; - var currentNodeModulesJsDepth = 0; - var modulesWithElidedImports = {}; - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + var modulesWithElidedImports = ts.createMap(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -37560,10 +47256,9 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, host); if (typeReferences) { - var inferredRoot = getInferredTypesRoot(options, rootNames, host); - var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -37607,7 +47302,8 @@ var ts; getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.programTime += new Date().getTime() - start; + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -37626,10 +47322,10 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = {}; + classifiableNames = ts.createMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyMap(sourceFile.classifiableNames, classifiableNames); + ts.copyProperties(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -37652,7 +47348,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { + !ts.equalOwnProperties(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -37742,7 +47438,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, + isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -37754,8 +47450,7 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } function emit(sourceFile, writeFileCallback, cancellationToken) { - var _this = this; - return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); @@ -37780,9 +47475,10 @@ var ts; } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - var start = new Date().getTime(); + ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); - ts.emitTime += new Date().getTime() - start; + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; } function getSourceFile(fileName) { @@ -37921,16 +47617,16 @@ var ts; case 175: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start_2 = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142: var parameter = node; if (parameter.modifiers) { - var start_3 = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -37974,8 +47670,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start_4 = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -38055,6 +47751,14 @@ var ts; var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + var externalHelpersModuleReference = ts.createNode(9); + externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; + externalHelpersModuleReference.parent = file; + imports = [externalHelpersModuleReference]; + } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, false); @@ -38082,7 +47786,7 @@ var ts; } break; case 225: - if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); @@ -38162,8 +47866,17 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { - if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { + sourceFilesFoundSearchingNodeModules[file_1.path] = false; + if (!options.noResolve) { + processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processTypeReferenceDirectives(file_1); + } + modulesWithElidedImports[file_1.path] = false; + processImportedModules(file_1, ts.getDirectoryPath(fileName)); + } + else if (file_1 && modulesWithElidedImports[file_1.path]) { + if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -38180,6 +47893,7 @@ var ts; }); filesByName.set(path, file); if (file) { + sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -38213,13 +47927,14 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; - ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -38236,7 +47951,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } saveResolution = false; } @@ -38270,7 +47985,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = {}; + file.resolvedModules = ts.createMap(); var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -38280,12 +47995,9 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - sourceFilesFoundSearchingNodeModules[resolvedPath] = true; + currentNodeModulesDepth++; } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth++; - } - var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -38293,8 +48005,8 @@ var ts; else if (shouldAddFile) { findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth--; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; } } } @@ -38305,8 +48017,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var file = sourceFiles_5[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -38317,8 +48029,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -38365,6 +48077,9 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { + if (options.paths[key].length === 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; @@ -38410,28 +48125,28 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -38449,7 +48164,7 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } if (!options.noEmit && !options.suppressOutputPathCheck) { @@ -38483,6 +48198,1310 @@ var ts; ts.createProgram = createProgram; })(ts || (ts = {})); var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + var TextChange = (function () { + function TextChange() { + } + return TextChange; + }()); + ts.TextChange = TextChange; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind.none = "none"; + HighlightSpanKind.definition = "definition"; + HighlightSpanKind.reference = "reference"; + HighlightSpanKind.writtenReference = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(ts.IndentStyle || (ts.IndentStyle = {})); + var IndentStyle = ts.IndentStyle; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + })(ts.TokenClass || (ts.TokenClass = {})); + var TokenClass = ts.TokenClass; + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind.unknown = ""; + ScriptElementKind.warning = "warning"; + ScriptElementKind.keyword = "keyword"; + ScriptElementKind.scriptElement = "script"; + ScriptElementKind.moduleElement = "module"; + ScriptElementKind.classElement = "class"; + ScriptElementKind.localClassElement = "local class"; + ScriptElementKind.interfaceElement = "interface"; + ScriptElementKind.typeElement = "type"; + ScriptElementKind.enumElement = "enum"; + ScriptElementKind.enumMemberElement = "const"; + ScriptElementKind.variableElement = "var"; + ScriptElementKind.localVariableElement = "local var"; + ScriptElementKind.functionElement = "function"; + ScriptElementKind.localFunctionElement = "local function"; + ScriptElementKind.memberFunctionElement = "method"; + ScriptElementKind.memberGetAccessorElement = "getter"; + ScriptElementKind.memberSetAccessorElement = "setter"; + ScriptElementKind.memberVariableElement = "property"; + ScriptElementKind.constructorImplementationElement = "constructor"; + ScriptElementKind.callSignatureElement = "call"; + ScriptElementKind.indexSignatureElement = "index"; + ScriptElementKind.constructSignatureElement = "construct"; + ScriptElementKind.parameterElement = "parameter"; + ScriptElementKind.typeParameterElement = "type parameter"; + ScriptElementKind.primitiveType = "primitive type"; + ScriptElementKind.label = "label"; + ScriptElementKind.alias = "alias"; + ScriptElementKind.constElement = "const"; + ScriptElementKind.letElement = "let"; + ScriptElementKind.directory = "directory"; + ScriptElementKind.externalModuleName = "external module name"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier.none = ""; + ScriptElementKindModifier.publicMemberModifier = "public"; + ScriptElementKindModifier.privateMemberModifier = "private"; + ScriptElementKindModifier.protectedMemberModifier = "protected"; + ScriptElementKindModifier.exportedModifier = "export"; + ScriptElementKindModifier.ambientModifier = "declare"; + ScriptElementKindModifier.staticModifier = "static"; + ScriptElementKindModifier.abstractModifier = "abstract"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames = (function () { + function ClassificationTypeNames() { + } + return ClassificationTypeNames; + }()); + ClassificationTypeNames.comment = "comment"; + ClassificationTypeNames.identifier = "identifier"; + ClassificationTypeNames.keyword = "keyword"; + ClassificationTypeNames.numericLiteral = "number"; + ClassificationTypeNames.operator = "operator"; + ClassificationTypeNames.stringLiteral = "string"; + ClassificationTypeNames.whiteSpace = "whitespace"; + ClassificationTypeNames.text = "text"; + ClassificationTypeNames.punctuation = "punctuation"; + ClassificationTypeNames.className = "class name"; + ClassificationTypeNames.enumName = "enum name"; + ClassificationTypeNames.interfaceName = "interface name"; + ClassificationTypeNames.moduleName = "module name"; + ClassificationTypeNames.typeParameterName = "type parameter name"; + ClassificationTypeNames.typeAliasName = "type alias name"; + ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; + ts.ClassificationTypeNames = ClassificationTypeNames; +})(ts || (ts = {})); +var ts; +(function (ts) { + ts.scanner = ts.createScanner(2, true); + ts.emptyArray = []; + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 142: + case 218: + case 169: + case 145: + case 144: + case 253: + case 254: + case 255: + case 147: + case 146: + case 148: + case 149: + case 150: + case 220: + case 179: + case 180: + case 252: + return 1; + case 141: + case 222: + case 223: + case 159: + return 2; + case 221: + case 224: + return 1 | 2; + case 225: + if (ts.isAmbientModule(node)) { + return 4 | 1; + } + else if (ts.getModuleInstanceState(node) === 1) { + return 4 | 1; + } + else { + return 4; + } + case 233: + case 234: + case 229: + case 230: + case 235: + case 236: + return 1 | 2 | 4; + case 256: + return 4 | 1; + } + return 1 | 2 | 4; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.parent.kind === 235) { + return 1 | 2 | 4; + } + else if (isInRightSideOfImport(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2; + } + else if (isNamespaceReference(node)) { + return 4; + } + else { + return 1; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + ts.Debug.assert(node.kind === 69); + if (node.parent.kind === 139 && + node.parent.right === node && + node.parent.parent.kind === 229) { + return 1 | 2 | 4; + } + return 4; + } + function isInRightSideOfImport(node) { + while (node.parent.kind === 139) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 139) { + while (root.parent && root.parent.kind === 139) { + root = root.parent; + } + isLastClause = root.right === node; + } + return root.parent.kind === 155 && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 172) { + while (root.parent && root.parent.kind === 172) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 194 && root.parent.parent.kind === 251) { + var decl = root.parent.parent.parent; + return (decl.kind === 221 && root.parent.parent.token === 106) || + (decl.kind === 222 && root.parent.parent.token === 83); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + return node.parent.kind === 155 || + (node.parent.kind === 194 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 && !ts.isPartOfExpression(node)) || + node.kind === 165; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 174); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 175); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node, kind) { + var target = climbPastPropertyAccess(node); + return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 214 && referenceNode.label.text === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function isJumpStatementTarget(node) { + return node.kind === 69 && + (node.parent.kind === 210 || node.parent.kind === 209) && + node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 69 && + node.parent.kind === 214 && + node.parent.label === node; + } + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 139 && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 172 && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 225 && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 69 && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + if (node.kind === 9 || node.kind === 8) { + switch (node.parent.kind) { + case 145: + case 144: + case 253: + case 255: + case 147: + case 146: + case 149: + case 150: + case 225: + return node.parent.name === node; + case 173: + return node.parent.argumentExpression === node; + case 140: + return true; + } + } + return false; + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + function isInsideComment(sourceFile, token, position) { + return position <= token.getStart(sourceFile) && + (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || + isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); + function isInsideCommentRange(comments) { + return ts.forEach(comments, function (comment) { + if (comment.pos < position && position < comment.end) { + return true; + } + else if (position === comment.end) { + var text = sourceFile.text; + var width = comment.end - comment.pos; + if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { + return true; + } + else { + return !(text.charCodeAt(comment.end - 1) === 47 && + text.charCodeAt(comment.end - 2) === 42); + } + } + return false; + }); + } + } + ts.isInsideComment = isInsideComment; + function getContainerNode(node) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 256: + case 147: + case 146: + case 220: + case 179: + case 149: + case 150: + case 221: + case 222: + case 224: + case 225: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 256: + return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + case 225: + return ts.ScriptElementKind.moduleElement; + case 221: + case 192: + return ts.ScriptElementKind.classElement; + case 222: return ts.ScriptElementKind.interfaceElement; + case 223: return ts.ScriptElementKind.typeElement; + case 224: return ts.ScriptElementKind.enumElement; + case 218: + return getKindOfVariableDeclaration(node); + case 169: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180: + case 220: + case 179: + return ts.ScriptElementKind.functionElement; + case 149: return ts.ScriptElementKind.memberGetAccessorElement; + case 150: return ts.ScriptElementKind.memberSetAccessorElement; + case 147: + case 146: + return ts.ScriptElementKind.memberFunctionElement; + case 145: + case 144: + return ts.ScriptElementKind.memberVariableElement; + case 153: return ts.ScriptElementKind.indexSignatureElement; + case 152: return ts.ScriptElementKind.constructSignatureElement; + case 151: return ts.ScriptElementKind.callSignatureElement; + case 148: return ts.ScriptElementKind.constructorImplementationElement; + case 141: return ts.ScriptElementKind.typeParameterElement; + case 255: return ts.ScriptElementKind.enumMemberElement; + case 142: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + case 229: + case 234: + case 231: + case 238: + case 232: + return ts.ScriptElementKind.alias; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ts.ScriptElementKind.constElement + : ts.isLet(v) + ? ts.ScriptElementKind.letElement + : ts.ScriptElementKind.variableElement; + } + } + ts.getNodeKind = getNodeKind; + function getStringLiteralTypeForNode(node, typeChecker) { + var searchNode = node.parent.kind === 166 ? node.parent : node; + var type = typeChecker.getTypeAtLocation(searchNode); + if (type && type.flags & 32) { + return type; + } + return undefined; + } + ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; + function isThis(node) { + switch (node.kind) { + case 97: + return true; + case 69: + return node.originalKeywordKind === 97 && node.parent.kind === 142; + default: + return false; + } + } + ts.isThis = isThis; + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + function positionBelongsToNode(candidate, position, sourceFile) { + return candidate.end > position || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 221: + case 222: + case 224: + case 171: + case 167: + case 159: + case 199: + case 226: + case 227: + case 233: + case 237: + return nodeEndsWith(n, 16, sourceFile); + case 252: + return isCompletedNode(n.block, sourceFile); + case 175: + if (!n.arguments) { + return true; + } + case 174: + case 178: + case 164: + return nodeEndsWith(n, 18, sourceFile); + case 156: + case 157: + return isCompletedNode(n.type, sourceFile); + case 148: + case 149: + case 150: + case 220: + case 179: + case 147: + case 146: + case 152: + case 151: + case 180: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 18, sourceFile); + case 225: + return n.body && isCompletedNode(n.body, sourceFile); + case 203: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 202: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 23); + case 170: + case 168: + case 173: + case 140: + case 161: + return nodeEndsWith(n, 20, sourceFile); + case 153: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 20, sourceFile); + case 249: + case 250: + return false; + case 206: + case 207: + case 208: + case 205: + return isCompletedNode(n.statement, sourceFile); + case 204: + var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); + if (hasWhileKeyword) { + return nodeEndsWith(n, 18, sourceFile); + } + return isCompletedNode(n.statement, sourceFile); + case 158: + return isCompletedNode(n.exprName, sourceFile); + case 182: + case 181: + case 183: + case 190: + case 191: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 176: + return isCompletedNode(n.template, sourceFile); + case 189: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 197: + return ts.nodeIsPresent(n.literal); + case 236: + case 230: + return ts.nodeIsPresent(n.moduleSpecifier); + case 185: + return isCompletedNode(n.operand, sourceFile); + case 187: + return isCompletedNode(n.right, sourceFile); + case 188: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + ts.isCompletedNode = isCompletedNode; + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var last = ts.lastOrUndefined(children); + if (last.kind === expectedLastToken) { + return true; + } + else if (last.kind === 23 && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOf(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { + if (c.kind === 286 && c.pos <= node.pos && c.end >= node.end) { + return c; + } + }); + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + function getTouchingWord(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + } + ts.getTouchingWord = getTouchingWord; + function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); + } + ts.getTouchingToken = getTouchingToken; + function getTokenAtPosition(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); + } + ts.getTokenAtPosition = getTokenAtPosition; + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + var current = sourceFile; + outer: while (true) { + if (isToken(current)) { + return current; + } + if (includeJsDocComment) { + var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); + for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { + var jsDocChild = jsDocChildren_1[_i]; + var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = jsDocChild.getEnd(); + if (position < end || (position === end && jsDocChild.kind === 1)) { + current = jsDocChild; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } + } + } + } + } + for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { + var child = current.getChildAt(i); + if (ts.isJSDocNode(child)) { + continue; + } + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } + } + } + } + return current; + } + } + function findTokenOnLeftOfPosition(file, position) { + var tokenAtPosition = getTokenAtPosition(file, position); + if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent) { + return find(parent); + function find(n) { + if (isToken(n) && n.pos === previousToken.end) { + return n; + } + var children = n.getChildren(); + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || + (child.pos === previousToken.end); + if (shouldDiveInChildNode && nodeHasTokens(child)) { + return find(child); + } + } + return undefined; + } + } + ts.findNextToken = findNextToken; + function findPrecedingToken(position, sourceFile, startNode) { + return find(startNode || sourceFile); + function findRightmostToken(n) { + if (isToken(n) || n.kind === 244) { + return n; + } + var children = n.getChildren(); + var candidate = findRightmostChildNodeWithTokens(children, children.length); + return candidate && findRightmostToken(candidate); + } + function find(n) { + if (isToken(n) || n.kind === 244) { + return n; + } + var children = n.getChildren(); + for (var i = 0, len = children.length; i < len; i++) { + var child = children[i]; + if (position < child.end && (nodeHasTokens(child) || child.kind === 244)) { + var start = child.getStart(sourceFile); + var lookInPreviousChild = (start >= position) || + (child.kind === 244 && start === child.end); + if (lookInPreviousChild) { + var candidate = findRightmostChildNodeWithTokens(children, i); + return candidate && findRightmostToken(candidate); + } + else { + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 256); + if (children.length) { + var candidate = findRightmostChildNodeWithTokens(children, children.length); + return candidate && findRightmostToken(candidate); + } + } + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + if (nodeHasTokens(children[i])) { + return children[i]; + } + } + } + } + ts.findPrecedingToken = findPrecedingToken; + function isInString(sourceFile, position) { + var previousToken = findPrecedingToken(position, sourceFile); + if (previousToken && previousToken.kind === 9) { + var start = previousToken.getStart(); + var end = previousToken.getEnd(); + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + function isInComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, undefined); + } + ts.isInComment = isInComment; + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 244) { + return true; + } + if (token.kind === 25 && token.parent.kind === 244) { + return true; + } + if (token.kind === 25 && token.parent.kind === 248) { + return true; + } + if (token && token.kind === 16 && token.parent.kind === 248) { + return true; + } + if (token.kind === 25 && token.parent.kind === 245) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + function isInCommentHelper(sourceFile, position, predicate) { + var token = getTokenAtPosition(sourceFile, position); + if (token && position <= token.getStart(sourceFile)) { + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + return predicate ? + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 ? position <= c.end : position < c.end) && + predicate(c); }) : + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 ? position <= c.end : position < c.end); }); + } + return false; + } + ts.isInCommentHelper = isInCommentHelper; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + return ts.forEach(commentRanges, jsDocPrefix); + function jsDocPrefix(c) { + var text = sourceFile.text; + return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; + } + } + ts.hasDocComment = hasDocComment; + function getJsDocTagAtPosition(sourceFile, position) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (isToken(node)) { + switch (node.kind) { + case 102: + case 108: + case 74: + node = node.parent === undefined ? undefined : node.parent.parent; + break; + default: + node = node.parent; + break; + } + } + if (node) { + if (node.jsDocComments) { + for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + if (jsDocComment.tags) { + for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.pos <= position && position <= tag.end) { + return tag; + } + } + } + } + } + } + return undefined; + } + ts.getJsDocTagAtPosition = getJsDocTagAtPosition; + function nodeHasTokens(n) { + return n.getWidth() !== 0; + } + function getNodeModifiers(node) { + var flags = ts.getCombinedModifierFlags(node); + var result = []; + if (flags & 8) + result.push(ts.ScriptElementKindModifier.privateMemberModifier); + if (flags & 16) + result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + if (flags & 4) + result.push(ts.ScriptElementKindModifier.publicMemberModifier); + if (flags & 32) + result.push(ts.ScriptElementKindModifier.staticModifier); + if (flags & 128) + result.push(ts.ScriptElementKindModifier.abstractModifier); + if (flags & 1) + result.push(ts.ScriptElementKindModifier.exportedModifier); + if (ts.isInAmbientContext(node)) + result.push(ts.ScriptElementKindModifier.ambientModifier); + return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 155 || node.kind === 174) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 221 || node.kind === 222) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isToken(n) { + return n.kind >= 0 && n.kind <= 138; + } + ts.isToken = isToken; + function isWord(kind) { + return kind === 69 || ts.isKeyword(kind); + } + ts.isWord = isWord; + function isPropertyName(kind) { + return kind === 9 || kind === 8 || isWord(kind); + } + function isComment(kind) { + return kind === 2 || kind === 3; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 9 + || kind === 10 + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 15 <= kind && kind <= 68; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 112: + case 110: + case 111: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 170 || + node.kind === 171) { + if (node.parent.kind === 187 && + node.parent.left === node && + node.parent.operatorToken.kind === 56) { + return true; + } + if (node.parent.kind === 208 && + node.parent.initializer === node) { + return true; + } + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function hasTrailingDirectorySeparator(path) { + var lastCharacter = path.charAt(path.length - 1); + return lastCharacter === "/" || lastCharacter === "\\"; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function isInReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isReferenceComment); + function isReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isNonReferenceComment); + function isNonReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return !tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInNonReferenceComment = isInNonReferenceComment; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var displayParts; + var lineStart; + var indent; + resetWriter(); + return { + displayParts: function () { return displayParts; }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: function () { }, + reportInaccessibleThisError: function () { } + }; + function writeIndent() { + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + writeIndent(); + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + writeIndent(); + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol), symbol); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 8388608) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind, symbol) { + return { + text: text, + kind: ts.SymbolDisplayPartKind[kind] + }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + function getNewLineOrDefaultFromHost(host) { + return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + writeDisplayParts(displayPartWriter); + var result = displayPartWriter.displayParts(); + displayPartWriter.clear(); + return result; + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + return mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function getDeclaredName(typeChecker, symbol, location) { + if (isImportOrExportSpecifierName(location)) { + return location.getText(); + } + else if (ts.isStringOrNumericLiteral(location.kind) && + location.parent.kind === 140) { + return location.text; + } + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); + return name; + } + ts.getDeclaredName = getDeclaredName; + function isImportOrExportSpecifierName(location) { + return location.parent && + (location.parent.kind === 234 || location.parent.kind === 238) && + location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && + name.charCodeAt(0) === name.charCodeAt(length - 1) && + (name.charCodeAt(0) === 34 || name.charCodeAt(0) === 39)) { + return name.substring(1, length - 1); + } + ; + return name; + } + ts.stripQuotes = stripQuotes; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + var scriptKind; + if (host && host.getScriptKind) { + scriptKind = host.getScriptKind(fileName); + } + if (!scriptKind) { + scriptKind = ts.getScriptKindFromFileName(fileName); + } + return ts.ensureScriptKind(fileName, scriptKind); + } + ts.getScriptKind = getScriptKind; + function parseAndReEmitConfigJSONFile(content) { + var options = { + fileName: "config.js", + compilerOptions: { + target: 2, + removeComments: true + }, + reportDiagnostics: true + }; + var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; + var trimmedOutput = outputText.trim(); + var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; +})(ts || (ts = {})); +var ts; (function (ts) { var BreakpointResolver; (function (BreakpointResolver) { @@ -38665,7 +49684,7 @@ var ts; return spanInNode(binaryExpression.left); } } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { case 204: return spanInPreviousNode(node); @@ -38734,7 +49753,7 @@ var ts; return spanInBindingPattern(variableDeclaration.name); } if (variableDeclaration.initializer || - (variableDeclaration.flags & 1) || + ts.hasModifier(variableDeclaration, 1) || variableDeclaration.parent.parent.kind === 208) { return textSpanFromVariableDeclaration(variableDeclaration); } @@ -38745,7 +49764,7 @@ var ts; } function canHaveSpanInParameterDeclaration(parameter) { return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 4) || !!(parameter.flags & 8); + ts.hasModifier(parameter, 4 | 8); } function spanInParameterDeclaration(parameter) { if (ts.isBindingPattern(parameter.name)) { @@ -38766,7 +49785,7 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1) || + return ts.hasModifier(functionDeclaration, 1) || (functionDeclaration.parent.kind === 221 && functionDeclaration.kind !== 148); } function spanInFunctionDeclaration(functionDeclaration) { @@ -38969,188 +49988,4154 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var OutliningElementsCollector; - (function (OutliningElementsCollector) { - function collectElements(sourceFile) { - var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { - if (hintSpanNode && startElement && endElement) { - var span = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), - hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + function createClassifier() { + var scanner = ts.createScanner(2, false); + var noRegexTable = []; + noRegexTable[69] = true; + noRegexTable[9] = true; + noRegexTable[8] = true; + noRegexTable[10] = true; + noRegexTable[97] = true; + noRegexTable[41] = true; + noRegexTable[42] = true; + noRegexTable[18] = true; + noRegexTable[20] = true; + noRegexTable[16] = true; + noRegexTable[99] = true; + noRegexTable[84] = true; + var templateStack = []; + function canFollow(keyword1, keyword2) { + if (ts.isAccessibilityModifier(keyword1)) { + if (keyword2 === 123 || + keyword2 === 131 || + keyword2 === 121 || + keyword2 === 113) { + return true; } + return false; } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + return true; + } + function convertClassifications(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0, n = dense.length; i < n; i += 3) { + var start = dense[i]; + var length_4 = dense[i + 1]; + var type = dense[i + 2]; + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } } + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var currentComment = comments_2[_i]; - if (currentComment.kind === 2) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; - } - else if (currentComment.kind === 3) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1: return ts.TokenClass.Comment; + case 3: return ts.TokenClass.Keyword; + case 4: return ts.TokenClass.NumberLiteral; + case 5: return ts.TokenClass.Operator; + case 6: return ts.TokenClass.StringLiteral; + case 8: return ts.TokenClass.Whitespace; + case 10: return ts.TokenClass.Punctuation; + case 2: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 9: + case 17: + default: + return ts.TokenClass.Identifier; + } + } + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + } + function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var offset = 0; + var token = 0; + var lastNonTriviaToken = 0; + while (templateStack.length > 0) { + templateStack.pop(); + } + switch (lexState) { + case 3: + text = "\"\\\n" + text; + offset = 3; + break; + case 2: + text = "'\\\n" + text; + offset = 3; + break; + case 1: + text = "/*\n" + text; + offset = 3; + break; + case 4: + text = "`\n" + text; + offset = 2; + break; + case 5: + text = "}\n" + text; + offset = 2; + case 6: + templateStack.push(12); + break; + } + scanner.setText(text); + var result = { + endOfLineState: 0, + spans: [] + }; + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + if ((token === 39 || token === 61) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 10) { + token = 10; } } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + else if (lastNonTriviaToken === 21 && isKeyword(token)) { + token = 69; + } + else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + token = 69; + } + else if (lastNonTriviaToken === 69 && + token === 25) { + angleBracketStack++; + } + else if (token === 27 && angleBracketStack > 0) { + angleBracketStack--; + } + else if (token === 117 || + token === 132 || + token === 130 || + token === 120 || + token === 133) { + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + token = 69; + } + } + else if (token === 12) { + templateStack.push(token); + } + else if (token === 15) { + if (templateStack.length > 0) { + templateStack.push(token); + } + } + else if (token === 16) { + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 12) { + token = scanner.reScanTemplateToken(); + if (token === 14) { + templateStack.pop(); + } + else { + ts.Debug.assert(token === 13, "Should have been a template middle. Was " + token); + } + } + else { + ts.Debug.assert(lastTemplateStackToken === 15, "Should have been an open brace. Was: " + token); + templateStack.pop(); + } + } + } + lastNonTriviaToken = token; + } + processToken(); + } while (token !== 1); + return result; + function processToken() { + var start = scanner.getTokenPos(); + var end = scanner.getTextPos(); + addResult(start, end, classFromKind(token)); + if (end >= text.length) { + if (token === 9) { + var tokenText = scanner.getTokenText(); + if (scanner.isUnterminated()) { + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92) { + numBackslashes++; + } + if (numBackslashes & 1) { + var quoteChar = tokenText.charCodeAt(0); + result.endOfLineState = quoteChar === 34 + ? 3 + : 2; + } + } + } + else if (token === 3) { + if (scanner.isUnterminated()) { + result.endOfLineState = 1; + } + } + else if (ts.isTemplateLiteralKind(token)) { + if (scanner.isUnterminated()) { + if (token === 14) { + result.endOfLineState = 5; + } + else if (token === 11) { + result.endOfLineState = 4; + } + else { + ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + } + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12) { + result.endOfLineState = 6; + } } } - function combineAndAddMultipleSingleLineComments(count, start, end) { - if (count > 1) { - var multipleSingleLineComments = { - pos: start, - end: end, - kind: 2 - }; - addOutliningSpanComments(multipleSingleLineComments, false); - } - } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180; - } - var depth = 0; - var maxDepth = 20; - function walk(n) { - if (depth > maxDepth) { + function addResult(start, end, classification) { + if (classification === 8) { return; } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); + if (start === 0 && offset > 0) { + start += offset; } - switch (n.kind) { - case 199: - if (!ts.isFunctionBlock(n)) { - var parent_15 = n.parent; - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_15.kind === 204 || - parent_15.kind === 207 || - parent_15.kind === 208 || - parent_15.kind === 206 || - parent_15.kind === 203 || - parent_15.kind === 205 || - parent_15.kind === 212 || - parent_15.kind === 252) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + start -= offset; + end -= offset; + var length = end - start; + if (length > 0) { + result.spans.push(start); + result.spans.push(length); + result.spans.push(classification); + } + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 37: + case 39: + case 40: + case 35: + case 36: + case 43: + case 44: + case 45: + case 25: + case 27: + case 28: + case 29: + case 91: + case 90: + case 116: + case 30: + case 31: + case 32: + case 33: + case 46: + case 48: + case 47: + case 51: + case 52: + case 67: + case 66: + case 68: + case 63: + case 64: + case 65: + case 57: + case 58: + case 59: + case 61: + case 62: + case 56: + case 24: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 35: + case 36: + case 50: + case 49: + case 41: + case 42: + return true; + default: + return false; + } + } + function isKeyword(token) { + return token >= 70 && token <= 138; + } + function classFromKind(token) { + if (isKeyword(token)) { + return 3; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5; + } + else if (token >= 15 && token <= 68) { + return 10; + } + switch (token) { + case 8: + return 4; + case 9: + return 6; + case 10: + return 7; + case 7: + case 3: + case 2: + return 1; + case 5: + case 4: + return 8; + case 69: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6; + } + return 2; + } + } + return { + getClassificationsForLine: getClassificationsForLine, + getEncodedLexicalClassifications: getEncodedLexicalClassifications + }; + } + ts.createClassifier = createClassifier; + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + switch (kind) { + case 225: + case 221: + case 222: + case 220: + cancellationToken.throwIfCancellationRequested(); + } + } + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var result = []; + processNode(sourceFile); + return { spans: result, endOfLineState: 0 }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifySymbol(symbol, meaningAtPosition) { + var flags = symbol.getFlags(); + if ((flags & 788448) === 0) { + return; + } + if (flags & 32) { + return 11; + } + else if (flags & 384) { + return 12; + } + else if (flags & 524288) { + return 16; + } + else if (meaningAtPosition & 2) { + if (flags & 64) { + return 13; + } + else if (flags & 262144) { + return 15; + } + } + else if (flags & 1536) { + if (meaningAtPosition & 4 || + (meaningAtPosition & 1 && hasValueSideModule(symbol))) { + return 14; + } + } + return undefined; + function hasValueSideModule(symbol) { + return ts.forEach(symbol.declarations, function (declaration) { + return declaration.kind === 225 && + ts.getModuleInstanceState(declaration) === 1; + }); + } + } + function processNode(node) { + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + var kind = node.kind; + checkForClassificationCancellation(cancellationToken, kind); + if (kind === 69 && !ts.nodeIsMissing(node)) { + var identifier = node; + if (classifiableNames[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); } - if (parent_15.kind === 216) { - var tryStatement = parent_15; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + } + } + } + ts.forEachChild(node, processNode); + } + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function getClassificationTypeName(type) { + switch (type) { + case 1: return ts.ClassificationTypeNames.comment; + case 2: return ts.ClassificationTypeNames.identifier; + case 3: return ts.ClassificationTypeNames.keyword; + case 4: return ts.ClassificationTypeNames.numericLiteral; + case 5: return ts.ClassificationTypeNames.operator; + case 6: return ts.ClassificationTypeNames.stringLiteral; + case 8: return ts.ClassificationTypeNames.whiteSpace; + case 9: return ts.ClassificationTypeNames.text; + case 10: return ts.ClassificationTypeNames.punctuation; + case 11: return ts.ClassificationTypeNames.className; + case 12: return ts.ClassificationTypeNames.enumName; + case 13: return ts.ClassificationTypeNames.interfaceName; + case 14: return ts.ClassificationTypeNames.moduleName; + case 15: return ts.ClassificationTypeNames.typeParameterName; + case 16: return ts.ClassificationTypeNames.typeAliasName; + case 17: return ts.ClassificationTypeNames.parameterName; + case 18: return ts.ClassificationTypeNames.docCommentTagName; + case 19: return ts.ClassificationTypeNames.jsxOpenTagName; + case 20: return ts.ClassificationTypeNames.jsxCloseTagName; + case 21: return ts.ClassificationTypeNames.jsxSelfClosingTagName; + case 22: return ts.ClassificationTypeNames.jsxAttribute; + case 23: return ts.ClassificationTypeNames.jsxText; + case 24: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + } + } + function convertClassifications(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0, n = dense.length; i < n; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + var triviaScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + if (!ts.isTrivia(kind)) { + return start; + } + if (kind === 4 || kind === 5) { + continue; + } + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + triviaScanner.setTextPos(end); + continue; + } + if (kind === 7) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + if (ch === 60 || ch === 62) { + pushClassification(start, width, 1); + continue; + } + ts.Debug.assert(ch === 61); + classifyDisabledMergeCode(text, start, end); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3) { + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10); + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); + pos = tag.tagName.end; + switch (tag.kind) { + case 275: + processJSDocParameterTag(tag); + break; + case 278: + processJSDocTemplateTag(tag); + break; + case 277: + processElement(tag.typeExpression); + break; + case 276: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.preParameterName) { + pushCommentRange(pos, tag.preParameterName.pos - pos); + pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17); + pos = tag.preParameterName.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (tag.postParameterName) { + pushCommentRange(pos, tag.postParameterName.pos - pos); + pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17); + pos = tag.postParameterName.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + function tryClassifyNode(node) { + if (ts.isJSDocTag(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 244 && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 244 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 243: + if (token.parent.tagName === token) { + return 19; + } + break; + case 245: + if (token.parent.tagName === token) { + return 20; + } + break; + case 242: + if (token.parent.tagName === token) { + return 21; + } + break; + case 246: + if (token.parent.name === token) { + return 22; + } + break; + } + return undefined; + } + function classifyTokenType(tokenKind, token) { + if (ts.isKeyword(tokenKind)) { + return 3; + } + if (tokenKind === 25 || tokenKind === 27) { + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + if (tokenKind === 56) { + if (token.parent.kind === 218 || + token.parent.kind === 145 || + token.parent.kind === 142 || + token.parent.kind === 246) { + return 5; + } + } + if (token.parent.kind === 187 || + token.parent.kind === 185 || + token.parent.kind === 186 || + token.parent.kind === 188) { + return 5; + } + } + return 10; + } + else if (tokenKind === 8) { + return 4; + } + else if (tokenKind === 9) { + return token.parent.kind === 246 ? 24 : 6; + } + else if (tokenKind === 10) { + return 6; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + return 6; + } + else if (tokenKind === 244) { + return 23; + } + else if (tokenKind === 69) { + if (token) { + switch (token.parent.kind) { + case 221: + if (token.parent.name === token) { + return 11; + } + return; + case 141: + if (token.parent.name === token) { + return 15; + } + return; + case 222: + if (token.parent.name === token) { + return 13; + } + return; + case 224: + if (token.parent.name === token) { + return 12; + } + return; + case 225: + if (token.parent.name === token) { + return 14; + } + return; + case 142: + if (token.parent.name === token) { + var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; + return isThis_1 ? 3 : 17; + } + return; + } + } + return 2; + } + } + function processElement(element) { + if (!element) { + return; + } + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; + if (!tryClassifyNode(child)) { + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +var ts; +(function (ts) { + var Completions; + (function (Completions) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + if (ts.isInReferenceComment(sourceFile, position)) { + return getTripleSlashReferenceCompletion(sourceFile, position); + } + if (ts.isInString(sourceFile, position)) { + return getStringLiteralCompletionEntries(sourceFile, position); + } + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + if (isJsDocTagName) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + } + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); + } + else { + if (!symbols || symbols.length === 0) { + if (sourceFile.languageVariant === 1 && + location.parent && location.parent.kind === 245) { + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } + } + getCompletionEntriesFromSymbols(symbols, entries, location, true); + } + if (!isMemberCompletion && !isJsDocTagName) { + ts.addRange(entries, keywordCompletions); + } + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { + var entries = []; + var nameTable = ts.getNameTable(sourceFile); + for (var name_46 in nameTable) { + if (nameTable[name_46] === position) { + continue; + } + if (!uniqueNames[name_46]) { + uniqueNames[name_46] = name_46; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (displayName) { + var entry = { + name: displayName, + kind: ts.ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); + } + } + } + return entries; + } + function createCompletionEntry(symbol, location, performCharacterChecks) { + var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, compilerOptions.target, performCharacterChecks, location); + if (!displayName) { + return undefined; + } + return { + name: displayName, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0" + }; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { + var start = ts.timestamp(); + var uniqueNames = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var entry = createCompletionEntry(symbol, location, performCharacterChecks); + if (entry) { + var id = ts.escapeIdentifier(entry.name); + if (!uniqueNames[id]) { + entries.push(entry); + uniqueNames[id] = id; + } + } + } + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniqueNames; + } + function getStringLiteralCompletionEntries(sourceFile, position) { + var node = ts.findPrecedingToken(position, sourceFile); + if (!node || node.kind !== 9) { + return undefined; + } + if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); + } + else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { + return getStringLiteralCompletionEntriesFromElementAccess(node.parent); + } + else if (node.parent.kind === 230 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + return getStringLiteralCompletionEntriesFromModuleNames(node); + } + else { + var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); + if (argumentInfo) { + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + } + return getStringLiteralCompletionEntriesFromContextualType(node); + } + } + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var type = typeChecker.getContextualType(element.parent); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + } + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + var candidates = []; + var entries = []; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); + for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { + var candidate = candidates_3[_i]; + if (candidate.parameters.length > argumentInfo.argumentIndex) { + var parameter = candidate.parameters[argumentInfo.argumentIndex]; + addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); + } + } + if (entries.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + } + return undefined; + } + function getStringLiteralCompletionEntriesFromElementAccess(node) { + var type = typeChecker.getTypeAtLocation(node.expression); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + return undefined; + } + function getStringLiteralCompletionEntriesFromContextualType(node) { + var type = typeChecker.getContextualType(node); + if (type) { + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + } + } + return undefined; + } + function addStringLiteralCompletionsFromType(type, result) { + if (!type) { + return; + } + if (type.flags & 524288) { + ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); + } + else { + if (type.flags & 32) { + result.push({ + name: type.text, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } + } + } + function getStringLiteralCompletionEntriesFromModuleNames(node) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = node.getSourceFile().path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var entries; + if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { + if (compilerOptions.rootDirs) { + entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), false, span, scriptPath); + } + else { + entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), false, span, scriptPath); + } + } + else { + entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries + }; + } + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + var relativeDirectory; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDirectory = rootDirs_1[_i]; + if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { + relativeDirectory = scriptPath.substr(rootDirectory.length); + break; + } + } + return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); + var result = []; + for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { + var baseDirectory = baseDirectories_1[_i]; + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, exclude, result); + } + return result; + } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { + if (result === void 0) { result = []; } + fragment = ts.getDirectoryPath(fragment); + if (!fragment) { + fragment = "./"; + } + else { + fragment = ts.ensureTrailingDirectorySeparator(fragment); + } + var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); + var baseDirectory = ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (tryDirectoryExists(host, baseDirectory)) { + var files = tryReadDirectory(host, baseDirectory, extensions, undefined, ["./*"]); + if (files) { + var foundFiles = ts.createMap(); + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0) { + continue; + } + var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + if (!foundFiles[foundFileName]) { + foundFiles[foundFileName] = true; + } + } + for (var foundFile in foundFiles) { + result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + } + } + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { + var directory = directories_2[_a]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + } + } + } + return result; + } + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result; + if (baseUrl) { + var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); + result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span); + if (paths) { + for (var path in paths) { + if (paths.hasOwnProperty(path)) { + if (path === "*") { + if (paths[path]) { + for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { + var pattern = _a[_i]; + for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions); _b < _c.length; _b++) { + var match = _c[_b]; + result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + } + } + } } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); - break; + else if (ts.startsWith(path, fragment)) { + var entry = paths[path] && paths[path].length === 1 && paths[path][0]; + if (entry) { + result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); } } } - var span = ts.createTextSpanFromBounds(n.getStart(), n.end); - elements.push({ - textSpan: span, - hintSpan: span, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); + } + } + } + else { + result = []; + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions); _d < _e.length; _d++) { + var moduleName = _e[_d]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + return result; + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions) { + if (host.readDirectory) { + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (parsed) { + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); + if (matches) { + var result = []; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + continue; + } + var start = completePrefix.length; + var length_5 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_5))); + } + return result; + } + } + } + return undefined; + } + function enumeratePotentialNonRelativeModules(fragment, scriptPath, options) { + var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; + var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + if (isNestedModule) { + var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); + nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { + if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { + return moduleName.substr(moduleNameWithSeperator_1.length); + } + return moduleName; + }); + } + if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { + var visibleModule = _a[_i]; + if (!isNestedModule) { + nonRelativeModules.push(visibleModule.moduleName); + } + else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { + var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, undefined, ["./*"]); + if (nestedFiles) { + for (var _b = 0, nestedFiles_1 = nestedFiles; _b < nestedFiles_1.length; _b++) { + var f = nestedFiles_1[_b]; + f = ts.normalizePath(f); + var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); + nonRelativeModules.push(nestedModule); + } + } + } + } + } + return ts.deduplicate(nonRelativeModules); + } + function getTripleSlashReferenceCompletion(sourceFile, position) { + var token = ts.getTokenAtPosition(sourceFile, position); + if (!token) { + return undefined; + } + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + if (!commentRanges || !commentRanges.length) { + return undefined; + } + var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.substr(range.pos, position - range.pos); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (match) { + var prefix = match[1]; + var kind = match[2]; + var toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var entries_3; + if (kind === "path") { + var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); + entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + } + else { + var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; + entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries_3 + }; + } + return undefined; + } + function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + if (result === void 0) { result = []; } + if (options.types) { + for (var _i = 0, _a = options.types; _i < _a.length; _i++) { + var moduleName = _a[_i]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + } + else if (host.getDirectories) { + var typeRoots = void 0; + try { + typeRoots = ts.getEffectiveTypeRoots(options, host); + } + catch (e) { } + if (typeRoots) { + for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { + var root = typeRoots_2[_b]; + getCompletionEntriesFromDirectories(host, options, root, span, result); + } + } + } + if (host.getDirectories) { + for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { + var packageJson = _d[_c]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + } + } + return result; + } + function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + if (host.getDirectories && tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { + var typeDirectory = directories_3[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + } + } + } + } + function findPackageJsons(currentDir) { + var paths = []; + var currentConfigPath; + while (true) { + currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); + if (currentConfigPath) { + paths.push(currentConfigPath); + currentDir = ts.getDirectoryPath(currentConfigPath); + var parent_16 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_16) { break; } - case 226: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + currentDir = parent_16; + } + else { break; } - case 221: - case 222: - case 224: - case 171: - case 227: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); - break; - } - case 170: - var openBracket = ts.findChildOfKind(n, 19, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); - break; } - depth++; - ts.forEachChild(n, walk); - depth--; + return paths; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + var result = []; + if (host.readFile && host.fileExists) { + for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = tryReadingPackageJson(packageJson); + if (!contents) { + return; + } + var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); + var foundModuleNames = []; + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + addPotentialPackageNames(contents[key], foundModuleNames); + } + for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { + var moduleName = foundModuleNames_1[_c]; + var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); + result.push({ + moduleName: moduleName, + moduleDir: moduleDir + }); + } + } + } + return result; + function tryReadingPackageJson(filePath) { + try { + var fileText = tryReadFile(host, filePath); + return fileText ? JSON.parse(fileText) : undefined; + } + catch (e) { + return undefined; + } + } + function addPotentialPackageNames(dependencies, result) { + if (dependencies) { + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + } + function createCompletionEntryForModule(name, kind, replacementSpan) { + return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + } + function getDirectoryFragmentTextSpan(text, textStart) { + var index = text.lastIndexOf(ts.directorySeparator); + var offset = index !== -1 ? index + 1 : 0; + return { start: textStart + offset, length: text.length - offset }; + } + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 || slashCharCode === 92; + } + return false; + } + function normalizeAndPreserveTrailingSlash(path) { + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); } - walk(sourceFile); - return elements; } - OutliningElementsCollector.collectElements = collectElements; - })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_2 = completionData.location; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_2) === entryName ? s : undefined; }); + if (symbol) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + return { + name: entryName, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + kind: symbolKind, + displayParts: displayParts, + documentation: documentation + }; + } + } + var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + if (keywordCompletion) { + return { + name: entryName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined + }; + } + return undefined; + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_3 = completionData.location; + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); + } + return undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + function getCompletionData(typeChecker, log, sourceFile, position) { + var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + var isJsDocTagName = false; + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + if (insideComment) { + if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64) { + isJsDocTagName = true; + } + var insideJsDocTagExpression = false; + var tag = ts.getJsDocTagAtPosition(sourceFile, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + isJsDocTagName = true; + } + switch (tag.kind) { + case 277: + case 275: + case 276: + var tagWithExpression = tag; + if (tagWithExpression.typeExpression) { + insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; + } + break; + } + } + if (isJsDocTagName) { + return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + } + if (!insideJsDocTagExpression) { + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile); + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + var contextToken = previousToken; + if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { + var start_2 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + } + var node = currentToken; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent_17 = contextToken.parent, kind = contextToken.kind; + if (kind === 21) { + if (parent_17.kind === 172) { + node = contextToken.parent.expression; + isRightOfDot = true; + } + else if (parent_17.kind === 139) { + node = contextToken.parent.left; + isRightOfDot = true; + } + else { + return undefined; + } + } + else if (sourceFile.languageVariant === 1) { + if (kind === 25) { + isRightOfOpenTag = true; + location = contextToken; + } + else if (kind === 39 && contextToken.parent.kind === 245) { + isStartingCloseTag = true; + location = contextToken; + } + } + } + var semanticStart = ts.timestamp(); + var isMemberCompletion; + var isNewIdentifierLocation; + var symbols = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); + if (tryGetGlobalSymbols()) { + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 8388608)); })); + } + else { + symbols = tagSymbols; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else { + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + function getTypeScriptMemberSymbols() { + isMemberCompletion = true; + isNewIdentifierLocation = false; + if (node.kind === 69 || node.kind === 139 || node.kind === 172) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol && symbol.flags & 8388608) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol && symbol.flags & 1952) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + ts.forEach(exportedSymbols, function (symbol) { + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + }); + } + } + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { + if (type) { + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + } + if (isJavaScriptFile && type.flags & 524288) { + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); + } + } + } + } + function tryGetGlobalSymbols() { + var objectLikeContainer; + var namedImportsOrExports; + var jsxContainer; + if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { + return tryGetObjectLikeCompletionSymbols(objectLikeContainer); + } + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); + } + if (jsxContainer = tryGetContainingJsxElement(contextToken)) { + var attrsType = void 0; + if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { + attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + if (attrsType) { + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); + isMemberCompletion = true; + isNewIdentifierLocation = false; + return true; + } + } + } + isMemberCompletion = false; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + var symbolMeanings = 793064 | 107455 | 1920 | 8388608; + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + return true; + } + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 244) { + return true; + } + if (contextToken.kind === 27 && contextToken.parent) { + if (contextToken.parent.kind === 243) { + return true; + } + if (contextToken.parent.kind === 245 || contextToken.parent.kind === 242) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 241; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + switch (previousToken.kind) { + case 24: + return containingNodeKind === 174 + || containingNodeKind === 148 + || containingNodeKind === 175 + || containingNodeKind === 170 + || containingNodeKind === 187 + || containingNodeKind === 156; + case 17: + return containingNodeKind === 174 + || containingNodeKind === 148 + || containingNodeKind === 175 + || containingNodeKind === 178 + || containingNodeKind === 164; + case 19: + return containingNodeKind === 170 + || containingNodeKind === 153 + || containingNodeKind === 140; + case 125: + case 126: + return true; + case 21: + return containingNodeKind === 225; + case 15: + return containingNodeKind === 221; + case 56: + return containingNodeKind === 218 + || containingNodeKind === 187; + case 12: + return containingNodeKind === 189; + case 13: + return containingNodeKind === 197; + case 112: + case 110: + case 111: + return containingNodeKind === 145; + } + switch (previousToken.getText()) { + case "public": + case "protected": + case "private": + return true; + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + if (contextToken.kind === 9 + || contextToken.kind === 10 + || ts.isTemplateLiteralKind(contextToken.kind)) { + var start_3 = contextToken.getStart(); + var end = contextToken.getEnd(); + if (start_3 < position && position < end) { + return true; + } + if (position === end) { + return !!contextToken.isUnterminated + || contextToken.kind === 10; + } + } + return false; + } + function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + isMemberCompletion = true; + var typeForObject; + var existingMembers; + if (objectLikeContainer.kind === 171) { + isNewIdentifierLocation = true; + typeForObject = typeChecker.getContextualType(objectLikeContainer); + typeForObject = typeForObject && typeForObject.getNonNullableType(); + existingMembers = objectLikeContainer.properties; + } + else if (objectLikeContainer.kind === 167) { + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (ts.isVariableLike(rootDeclaration)) { + var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); + if (!canGetType && rootDeclaration.kind === 142) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 147 || rootDeclaration.parent.kind === 150) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + existingMembers = objectLikeContainer.elements; + } + } + else { + ts.Debug.fail("Root declaration is not variable-like."); + } + } + else { + ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); + } + if (!typeForObject) { + return false; + } + var typeMembers = typeChecker.getPropertiesOfType(typeForObject); + if (typeMembers && typeMembers.length > 0) { + symbols = filterObjectMembersList(typeMembers, existingMembers); + } + return true; + } + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 233 ? + 230 : + 236; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); + } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : ts.emptyArray; + return true; + } + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15: + case 24: + var parent_18 = contextToken.parent; + if (parent_18 && (parent_18.kind === 171 || parent_18.kind === 167)) { + return parent_18; + } + break; + } + } + return undefined; + } + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15: + case 24: + switch (contextToken.parent.kind) { + case 233: + case 237: + return contextToken.parent; + } + } + } + return undefined; + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent_19 = contextToken.parent; + switch (contextToken.kind) { + case 26: + case 39: + case 69: + case 246: + case 247: + if (parent_19 && (parent_19.kind === 242 || parent_19.kind === 243)) { + return parent_19; + } + else if (parent_19.kind === 246) { + return parent_19.parent; + } + break; + case 9: + if (parent_19 && ((parent_19.kind === 246) || (parent_19.kind === 247))) { + return parent_19.parent; + } + break; + case 16: + if (parent_19 && + parent_19.kind === 248 && + parent_19.parent && + (parent_19.parent.kind === 246)) { + return parent_19.parent.parent; + } + if (parent_19 && parent_19.kind === 247) { + return parent_19.parent; + } + break; + } + } + return undefined; + } + function isFunction(kind) { + switch (kind) { + case 179: + case 180: + case 220: + case 147: + case 146: + case 149: + case 150: + case 151: + case 152: + case 153: + return true; + } + return false; + } + function isSolelyIdentifierDefinitionLocation(contextToken) { + var containingNodeKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 24: + return containingNodeKind === 218 || + containingNodeKind === 219 || + containingNodeKind === 200 || + containingNodeKind === 224 || + isFunction(containingNodeKind) || + containingNodeKind === 221 || + containingNodeKind === 192 || + containingNodeKind === 222 || + containingNodeKind === 168 || + containingNodeKind === 223; + case 21: + return containingNodeKind === 168; + case 54: + return containingNodeKind === 169; + case 19: + return containingNodeKind === 168; + case 17: + return containingNodeKind === 252 || + isFunction(containingNodeKind); + case 15: + return containingNodeKind === 224 || + containingNodeKind === 222 || + containingNodeKind === 159; + case 23: + return containingNodeKind === 144 && + contextToken.parent && contextToken.parent.parent && + (contextToken.parent.parent.kind === 222 || + contextToken.parent.parent.kind === 159); + case 25: + return containingNodeKind === 221 || + containingNodeKind === 192 || + containingNodeKind === 222 || + containingNodeKind === 223 || + isFunction(containingNodeKind); + case 113: + return containingNodeKind === 145; + case 22: + return containingNodeKind === 142 || + (contextToken.parent && contextToken.parent.parent && + contextToken.parent.parent.kind === 168); + case 112: + case 110: + case 111: + return containingNodeKind === 142; + case 116: + return containingNodeKind === 234 || + containingNodeKind === 238 || + containingNodeKind === 232; + case 73: + case 81: + case 107: + case 87: + case 102: + case 123: + case 131: + case 89: + case 108: + case 74: + case 114: + case 134: + return true; + } + switch (contextToken.getText()) { + case "abstract": + case "async": + case "class": + case "const": + case "declare": + case "enum": + case "function": + case "interface": + case "let": + case "private": + case "protected": + case "public": + case "static": + case "var": + case "yield": + return true; + } + return false; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var existingImportsOrExports = ts.createMap(); + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_i]; + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_47 = element.propertyName || element.name; + existingImportsOrExports[name_47.text] = true; + } + if (!ts.someProperties(existingImportsOrExports)) { + return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + } + return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); + } + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (!existingMembers || existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + if (m.kind !== 253 && + m.kind !== 254 && + m.kind !== 169 && + m.kind !== 147) { + continue; + } + if (m.getStart() <= position && position <= m.getEnd()) { + continue; + } + var existingName = void 0; + if (m.kind === 169 && m.propertyName) { + if (m.propertyName.kind === 69) { + existingName = m.propertyName.text; + } + } + else { + existingName = m.name.text; + } + existingMemberNames[existingName] = true; + } + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); + } + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + if (attr.getStart() <= position && position <= attr.getEnd()) { + continue; + } + if (attr.kind === 246) { + seenNames[attr.name.text] = true; + } + } + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); + } + } + function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { + var displayName = ts.getDeclaredName(typeChecker, symbol, location); + if (displayName) { + var firstCharCode = displayName.charCodeAt(0); + if ((symbol.flags & 1920) && (firstCharCode === 39 || firstCharCode === 34)) { + return undefined; + } + } + return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + } + function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + if (!name) { + return undefined; + } + name = ts.stripQuotes(name); + if (!name) { + return undefined; + } + if (performCharacterChecks) { + if (!ts.isIdentifierText(name, target)) { + return undefined; + } + } + return name; + } + var keywordCompletions = []; + for (var i = 70; i <= 138; i++) { + keywordCompletions.push({ + name: ts.tokenToString(i), + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + sortText: "0" + }); + } + var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*= 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 104)) { + break; + } + } + } + } + var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70, 75); + } + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 206: + case 207: + case 208: + case 204: + case 205: + return getLoopBreakContinueOccurrences(owner); + case 213: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 96); + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 71, 77); + var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70); + } + }); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getTryCatchFinallyOccurrences(tryStatement) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 100); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 85); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getThrowOccurrences(throwStatement) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + }); + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + }); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getReturnOccurrences(returnStatement) { + var func = ts.getContainingFunction(returnStatement); + if (!(func && hasKind(func.body, 199))) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(func.body, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + }); + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getIfElseOccurrences(ifStatement) { + var keywords = []; + while (hasKind(ifStatement.parent, 203) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + while (ifStatement) { + var children = ifStatement.getChildren(); + pushKeywordIf(keywords, children[0], 88); + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 80)) { + break; + } + } + if (!hasKind(ifStatement.elseStatement, 203)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + var result = []; + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 80 && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; + var shouldCombindElseAndIf = true; + for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombindElseAndIf = false; + break; + } + } + if (shouldCombindElseAndIf) { + result.push({ + fileName: fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: ts.HighlightSpanKind.reference + }); + i++; + continue; + } + } + result.push(getHighlightSpanForNode(keywords[i])); + } + return result; + } + } + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + function isLabeledBy(node, labelName) { + for (var owner = node.parent; owner.kind === 214; owner = owner.parent) { + if (owner.label.text === labelName) { + return true; + } + } + return false; + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function getKeyForCompilationSettings(settings) { + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); + } + function getBucketForCompilationSettings(key, createIfMissing) { + var bucket = buckets[key]; + if (!bucket && createIfMissing) { + buckets[key] = bucket = ts.createFileMap(); + } + return bucket; + } + function reportStats() { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets[name]; + var sourceFiles = []; + entries.forEachValue(function (key, entry) { + sourceFiles.push({ + name: key, + refCount: entry.languageServiceRefCount, + references: entry.owners.slice(0) + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = getBucketForCompilationSettings(key, true); + var entry = bucket.get(path); + if (!entry) { + ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0, + owners: [] + }; + bucket.set(path, entry); + } + else { + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + } + } + if (acquiring) { + entry.languageServiceRefCount++; + } + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = getBucketForCompilationSettings(key, false); + ts.Debug.assert(bucket !== undefined); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.remove(path); + } + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistry = createDocumentRegistry; +})(ts || (ts = {})); +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + function findReferencedSymbols(typeChecker, cancellationToken, sourceFiles, sourceFile, position, findInStrings, findInComments) { + var node = ts.getTouchingPropertyName(sourceFile, position, true); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 8: + if (!ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + break; + } + case 69: + case 97: + case 121: + case 9: + return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, false); + } + return undefined; + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, implementations) { + if (!implementations) { + if (ts.isLabelName(node)) { + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; + } + else { + return getLabelReferencesInNode(node.parent, node); + } + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles); + } + if (node.kind === 95) { + return getReferencesForSuperKeyword(node); + } + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!implementations && !symbol && node.kind === 9) { + return getReferencesForStringLiteral(node, sourceFiles); + } + if (!symbol) { + return undefined; + } + var declarations = symbol.declarations; + if (!declarations || !declarations.length) { + return undefined; + } + var result; + var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), declarations); + var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + var scope = getSymbolScope(symbol); + var symbolToIndex = []; + if (scope) { + result = []; + getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + else { + var internedName = getInternedName(symbol, node, declarations); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + cancellationToken.throwIfCancellationRequested(); + var nameTable = ts.getNameTable(sourceFile); + if (nameTable[internedName] !== undefined) { + result = result || []; + getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + } + } + return result; + function getDefinition(symbol) { + var info = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, node.getSourceFile(), ts.getContainerNode(node), node); + var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) { + return undefined; + } + return { + containerKind: "", + containerName: "", + name: name, + kind: info.symbolKind, + fileName: declarations[0].getSourceFile().fileName, + textSpan: ts.createTextSpan(declarations[0].getStart(), 0), + displayParts: info.displayParts + }; + } + function getAliasSymbolForPropertyNameSymbol(symbol, location) { + if (symbol.flags & 8388608) { + var defaultImport = ts.getDeclarationOfKind(symbol, 231); + if (defaultImport) { + return typeChecker.getAliasedSymbol(symbol); + } + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 || + declaration.kind === 238) ? declaration : undefined; }); + if (importOrExportSpecifier && + (!importOrExportSpecifier.propertyName || + importOrExportSpecifier.propertyName === location)) { + return importOrExportSpecifier.kind === 234 ? + typeChecker.getAliasedSymbol(symbol) : + typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); + } + } + return undefined; + } + function followAliasIfNecessary(symbol, location) { + return getAliasSymbolForPropertyNameSymbol(symbol, location) || symbol; + } + function getPropertySymbolOfDestructuringAssignment(location) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && + typeChecker.getPropertySymbolOfDestructuringAssignment(location); + } + function isObjectBindingPatternElementWithoutPropertyName(symbol) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169); + return bindingElement && + bindingElement.parent.kind === 167 && + !bindingElement.propertyName; + } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169); + var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + return undefined; + } + function getInternedName(symbol, location, declarations) { + if (ts.isImportOrExportSpecifierName(location)) { + return location.getText(); + } + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + symbol = localExportDefaultSymbol || symbol; + return ts.stripQuotes(symbol.name); + } + function getSymbolScope(symbol) { + var valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 179 || valueDeclaration.kind === 192)) { + return valueDeclaration; + } + if (symbol.flags & (4 | 8192)) { + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8) ? d : undefined; }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 221); + } + } + if (symbol.flags & 8388608) { + return undefined; + } + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + return undefined; + } + if (symbol.parent || (symbol.flags & 268435456)) { + return undefined; + } + var scope; + var declarations = symbol.getDeclarations(); + if (declarations) { + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var container = ts.getContainerNode(declaration); + if (!container) { + return undefined; + } + if (scope && scope !== container) { + return undefined; + } + if (container.kind === 256 && !ts.isExternalModule(container)) { + return undefined; + } + scope = container; + } + } + return scope; + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + var positions = []; + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, start); + while (position >= 0) { + cancellationToken.throwIfCancellationRequested(); + if (position > end) + break; + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2))) { + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var references = []; + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.getWidth() !== labelName.length) { + return; + } + if (node === targetLabel || + (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = { + containerKind: "", + containerName: "", + fileName: targetLabel.getSourceFile().fileName, + kind: ts.ScriptElementKind.label, + name: labelName, + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), + displayParts: [ts.displayPart(labelName, ts.SymbolDisplayPartKind.text)] + }; + return [{ definition: definition, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + if (node) { + switch (node.kind) { + case 69: + return node.getWidth() === searchSymbolName.length; + case 9: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isNameOfExternalModuleImportOrDeclaration(node)) { + return node.getWidth() === searchSymbolName.length + 2; + } + break; + case 8: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + return node.getWidth() === searchSymbolName.length; + } + break; + } + } + return false; + } + function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { + var sourceFile = container.getSourceFile(); + var start = findInComments ? container.getFullStart() : container.getStart(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, start, container.getEnd()); + var parents = getParentSymbolsOfPropertyAccess(); + var inheritsFromCache = ts.createMap(); + if (possiblePositions.length) { + var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, searchText)) { + if (!implementations && ((findInStrings && ts.isInString(sourceFile, position)) || + (findInComments && ts.isInNonReferenceComment(sourceFile, position)))) { + result.push({ + definition: undefined, + references: [{ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpan(position, searchText.length), + isWriteAccess: false, + isDefinition: false + }] + }); + } + return; + } + if (!(ts.getMeaningFromLocation(referenceLocation) & searchMeaning)) { + return; + } + var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation); + if (referenceSymbol) { + var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, searchLocation.kind === 121, parents, inheritsFromCache); + if (relatedSymbol) { + addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); + } + else if (!(referenceSymbol.flags & 67108864) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { + addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); + } + else if (searchLocation.kind === 121) { + findAdditionalConstructorReferences(referenceSymbol, referenceLocation); + } + } + }); + } + return; + function getParentSymbolsOfPropertyAccess() { + if (implementations) { + var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(searchLocation); + if (propertyAccessExpression) { + var localParentType = typeChecker.getTypeAtLocation(propertyAccessExpression.expression); + if (localParentType) { + if (localParentType.symbol && localParentType.symbol.flags & (32 | 64) && localParentType.symbol !== searchSymbol.parent) { + return [localParentType.symbol]; + } + else if (localParentType.flags & 1572864) { + return getSymbolsForClassAndInterfaceComponents(localParentType); + } + } + } + } + } + function getPropertyAccessExpressionFromRightHandSide(node) { + return ts.isRightSideOfPropertyAccess(node) && node.parent; + } + function findAdditionalConstructorReferences(referenceSymbol, referenceLocation) { + ts.Debug.assert(ts.isClassLike(searchSymbol.valueDeclaration)); + var referenceClass = referenceLocation.parent; + if (referenceSymbol === searchSymbol && ts.isClassLike(referenceClass)) { + ts.Debug.assert(referenceClass.name === referenceLocation); + addReferences(findOwnConstructorCalls(searchSymbol)); + } + else { + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending && ts.isClassLike(classExtending) && followAliasIfNecessary(referenceSymbol, referenceLocation) === searchSymbol) { + addReferences(superConstructorAccesses(classExtending)); + } + } + } + function addReferences(references) { + if (references.length) { + var referencedSymbol = getReferencedSymbol(searchSymbol); + ts.addRange(referencedSymbol.references, ts.map(references, getReferenceEntryFromNode)); + } + } + function findOwnConstructorCalls(classSymbol) { + var result = []; + for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148); + var ctrKeyword = decl.getChildAt(0); + ts.Debug.assert(ctrKeyword.kind === 121); + result.push(ctrKeyword); + } + ts.forEachProperty(classSymbol.exports, function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 147) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 97, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + result.push(thisKeyword); + } + }); + } + } + }); + return result; + } + function superConstructorAccesses(cls) { + var symbol = cls.symbol; + var ctr = symbol.members["__constructor"]; + if (!ctr) { + return []; + } + var result = []; + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 95, function (node) { + if (ts.isCallExpressionTarget(node)) { + result.push(node); + } + }); + } + } + ; + return result; + } + function getReferencedSymbol(symbol) { + var symbolId = ts.getSymbolId(symbol); + var index = symbolToIndex[symbolId]; + if (index === undefined) { + index = result.length; + symbolToIndex[symbolId] = index; + result.push({ + definition: getDefinition(symbol), + references: [] + }); + } + return result[index]; + } + function addReferenceToRelatedSymbol(node, relatedSymbol) { + var references = getReferencedSymbol(relatedSymbol).references; + if (implementations) { + getImplementationReferenceEntryForNode(node, references); + } + else { + references.push(getReferenceEntryFromNode(node)); + } + } + } + function getImplementationReferenceEntryForNode(refNode, result) { + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + result.push(getReferenceEntryFromNode(refNode.parent)); + } + else if (refNode.kind === 69) { + if (refNode.parent.kind === 254) { + getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); + } + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + result.push(getReferenceEntryFromNode(containingClass)); + return; + } + var containingTypeReference = getContainingTypeReference(refNode); + if (containingTypeReference) { + var parent_21 = containingTypeReference.parent; + if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + } + else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { + if (parent_21.body.kind === 199) { + ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { + maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); + } + }); + } + else if (isImplementationExpression(parent_21.body)) { + maybeAdd(getReferenceEntryFromNode(parent_21.body)); + } + } + else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + } + } + } + function maybeAdd(a) { + if (!ts.forEach(result, function (b) { return a.fileName === b.fileName && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; })) { + result.push(a); + } + } + } + function getSymbolsForClassAndInterfaceComponents(type, result) { + if (result === void 0) { result = []; } + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var componentType = _a[_i]; + if (componentType.symbol && componentType.symbol.getFlags() & (32 | 64)) { + result.push(componentType.symbol); + } + if (componentType.getFlags() & 1572864) { + getSymbolsForClassAndInterfaceComponents(componentType, result); + } + } + return result; + } + function getContainingTypeReference(node) { + var topLevelTypeReference = undefined; + while (node) { + if (ts.isTypeNode(node)) { + topLevelTypeReference = node; + } + node = node.parent; + } + return topLevelTypeReference; + } + function getContainingClassIfInHeritageClause(node) { + if (node && node.parent) { + if (node.kind === 194 + && node.parent.kind === 251 + && ts.isClassLike(node.parent.parent)) { + return node.parent.parent; + } + else if (node.kind === 69 || node.kind === 172) { + return getContainingClassIfInHeritageClause(node.parent); + } + } + return undefined; + } + function isImplementationExpression(node) { + if (node.kind === 178) { + return isImplementationExpression(node.expression); + } + return node.kind === 180 || + node.kind === 179 || + node.kind === 171 || + node.kind === 192 || + node.kind === 170; + } + function explicitlyInheritsFrom(child, parent, cachedResults) { + var parentIsInterface = parent.getFlags() & 64; + return searchHierarchy(child); + function searchHierarchy(symbol) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + if (key in cachedResults) { + return cachedResults[key]; + } + cachedResults[key] = false; + var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + if (parentIsInterface) { + var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); + if (interfaceReferences) { + for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { + var typeReference = interfaceReferences_1[_i]; + if (searchTypeReference(typeReference)) { + return true; + } + } + } + } + return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + } + else if (declaration.kind === 222) { + if (parentIsInterface) { + return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); + } + } + return false; + }); + cachedResults[key] = inherits; + return inherits; + } + function searchTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type && type.symbol) { + return searchHierarchy(type.symbol); + } + } + return false; + } + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, false); + if (!searchSpaceNode) { + return undefined; + } + var staticFlag = 32; + switch (searchSpaceNode.kind) { + case 145: + case 144: + case 147: + case 146: + case 148: + case 149: + case 150: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; + break; + default: + return undefined; + } + var references = []; + var sourceFile = searchSpaceNode.getSourceFile(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.kind !== 95) { + return; + } + var container = ts.getSuperContainer(node, false); + if (container && (32 & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = getDefinition(searchSpaceNode.symbol); + return [{ definition: definition, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); + var staticFlag = 32; + switch (searchSpaceNode.kind) { + case 147: + case 146: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + case 145: + case 144: + case 148: + case 149: + case 150: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; + break; + case 256: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + case 220: + case 179: + break; + default: + return undefined; + } + var references = []; + var possiblePositions; + if (searchSpaceNode.kind === 256) { + ts.forEach(sourceFiles, function (sourceFile) { + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); + }); + } + else { + var sourceFile = searchSpaceNode.getSourceFile(); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); + } + var thisOrSuperSymbol = typeChecker.getSymbolAtLocation(thisOrSuperKeyword); + var displayParts = thisOrSuperSymbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, thisOrSuperSymbol, thisOrSuperKeyword.getSourceFile(), ts.getContainerNode(thisOrSuperKeyword), thisOrSuperKeyword).displayParts; + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: "this", + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: displayParts + }, + references: references + }]; + function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || !ts.isThis(node)) { + return; + } + var container = ts.getThisContainer(node, false); + switch (searchSpaceNode.kind) { + case 179: + case 220: + if (searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 147: + case 146: + if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 192: + case 221: + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32) === staticFlag) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 256: + if (container.kind === 256 && !ts.isExternalModule(container)) { + result.push(getReferenceEntryFromNode(node)); + } + break; + } + }); + } + } + function getReferencesForStringLiteral(node, sourceFiles) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (!type) { + return undefined; + } + var references = []; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); + getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); + } + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: type.text, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: [ts.displayPart(ts.getTextOfNode(node), ts.SymbolDisplayPartKind.stringLiteral)] + }, + references: references + }]; + function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { + for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { + var position = possiblePositions_1[_i]; + cancellationToken.throwIfCancellationRequested(); + var node_2 = ts.getTouchingWord(sourceFile, position); + if (!node_2 || node_2.kind !== 9) { + return; + } + var type_1 = ts.getStringLiteralTypeForNode(node_2, typeChecker); + if (type_1 === searchType) { + references.push(getReferenceEntryFromNode(node_2)); + } + } + } + } + function populateSearchSymbolSet(symbol, location) { + var result = [symbol]; + var containingObjectLiteralElement = getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254) { + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); + if (propertySymbol) { + result.push(propertySymbol); + } + } + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); + if (aliasSymbol) { + result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); + } + if (containingObjectLiteralElement) { + ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); + }); + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); + if (shorthandValueSymbol) { + result.push(shorthandValueSymbol); + } + } + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); + if (bindingElementPropertySymbol) { + result.push(bindingElementPropertySymbol); + } + ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + if (rootSymbol !== symbol) { + result.push(rootSymbol); + } + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap()); + } + }); + return result; + } + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + if (symbol.name in previousIterationSymbolsCache) { + return; + } + if (symbol.flags & (32 | 64)) { + ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); + } + else if (declaration.kind === 222) { + ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); + } + }); + } + return; + function getPropertySymbolFromTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type) { + var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); + if (propertySymbol) { + result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); + } + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); + } + } + } + } + function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation, searchLocationIsConstructor, parents, cache) { + if (ts.contains(searchSymbols, referenceSymbol)) { + return (!searchLocationIsConstructor || ts.isNewExpressionTarget(referenceLocation)) && referenceSymbol; + } + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); + if (aliasSymbol) { + return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation, searchLocationIsConstructor, parents, cache); + } + var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); + if (containingObjectLiteralElement) { + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + }); + if (contextualSymbol) { + return contextualSymbol; + } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); + if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { + return propertySymbol; + } + } + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); + if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { + return bindingElementPropertySymbol; + } + return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { + if (searchSymbols.indexOf(rootSymbol) >= 0) { + return rootSymbol; + } + if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + if (parents) { + if (!ts.forEach(parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, cache); })) { + return undefined; + } + } + var result_3 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, ts.createMap()); + return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + } + return undefined; + }); + } + function getNameFromObjectLiteralElement(node) { + if (node.name.kind === 140) { + var nameExpression = node.name.expression; + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } + return undefined; + } + return node.name.text; + } + function getPropertySymbolsFromContextualType(node) { + var objectLiteral = node.parent; + var contextualType = typeChecker.getContextualType(objectLiteral); + var name = getNameFromObjectLiteralElement(node); + if (name && contextualType) { + var result_4 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_4.push(symbol_2); + } + if (contextualType.flags & 524288) { + ts.forEach(contextualType.types, function (t) { + var symbol = t.getProperty(name); + if (symbol) { + result_4.push(symbol); + } + }); + } + return result_4; + } + return undefined; + } + function getIntersectingMeaningFromDeclarations(meaning, declarations) { + if (declarations) { + var lastIterationMeaning = void 0; + do { + lastIterationMeaning = meaning; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + } + FindAllReferences.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function convertReferences(referenceSymbols) { + if (!referenceSymbols) { + return undefined; + } + var referenceEntries = []; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; + ts.addRange(referenceEntries, referenceSymbol.references); + } + return referenceEntries; + } + FindAllReferences.convertReferences = convertReferences; + function isImplementation(node) { + if (!node) { + return false; + } + else if (ts.isVariableLike(node)) { + if (node.initializer) { + return true; + } + else if (node.kind === 218) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2); + } + } + else if (ts.isFunctionLike(node)) { + return !!node.body || ts.hasModifier(node, 2); + } + else { + switch (node.kind) { + case 221: + case 192: + case 224: + case 225: + return true; + } + } + return false; + } + function getParentStatementOfVariableDeclaration(node) { + if (node.parent && node.parent.parent && node.parent.parent.kind === 200) { + ts.Debug.assert(node.parent.kind === 219); + return node.parent.parent; + } + } + function getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result) { + var refSymbol = typeChecker.getSymbolAtLocation(node); + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1) { + result.push(getReferenceEntryFromNode(declaration)); + } + } + } + } + FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function getReferenceEntryFromNode(node) { + var start = node.getStart(); + var end = node.getEnd(); + if (node.kind === 9) { + start += 1; + end -= 1; + } + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(start, end), + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) + }; + } + FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; + function isWriteAccess(node) { + if (node.kind === 69 && ts.isDeclarationName(node)) { + return true; + } + var parent = node.parent; + if (parent) { + if (parent.kind === 186 || parent.kind === 185) { + return true; + } + else if (parent.kind === 187 && parent.left === node) { + var operator = parent.operatorToken.kind; + return 56 <= operator && operator <= 68; + } + } + return false; + } + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + function getContainingObjectLiteralElement(node) { + switch (node.kind) { + case 9: + case 8: + if (node.parent.kind === 140) { + return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; + } + case 69: + return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function isObjectLiteralPropertyDeclaration(node) { + switch (node.kind) { + case 253: + case 254: + case 147: + case 149: + case 150: + return true; + } + return false; + } + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + function isNameOfExternalModuleImportOrDeclaration(node) { + if (node.kind === 9) { + return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); + } + return false; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + var comment = findReferenceInPosition(sourceFile.referencedFiles, position); + if (comment) { + var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); + if (referenceFile) { + return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; + } + return undefined; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + if (referenceFile && referenceFile.resolvedFileName) { + return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + } + return undefined; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + if (ts.isJumpStatementTarget(node)) { + var labelName = node.text; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfo(label, ts.ScriptElementKind.label, labelName, undefined)] : undefined; + } + var typeChecker = program.getTypeChecker(); + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + if (calledDeclaration) { + return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + if (symbol.flags & 8388608) { + var declaration = symbol.declarations[0]; + if (node.kind === 69 && + (node.parent === declaration || + (declaration.kind === 234 && declaration.parent && declaration.parent.kind === 233))) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + } + if (node.parent.kind === 254) { + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + if (!shorthandSymbol) { + return []; + } + var shorthandDeclarations = shorthandSymbol.getDeclarations(); + var shorthandSymbolKind_1 = ts.SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; + } + if (type.flags & 524288 && !(type.flags & 16)) { + var result_5 = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + ts.addRange(result_5, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + } + }); + return result_5; + } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(typeChecker, type.symbol, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionFromSymbol(typeChecker, symbol, node) { + var result = []; + var declarations = symbol.getDeclarations(); + var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (ts.isNewExpressionTarget(location) || location.kind === 121) { + if (symbol.flags & 32) { + for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isClassLike(declaration)) { + return tryAddSignature(declaration.members, true, symbolKind, symbolName, containerName, result); + } + } + ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 148) || + (!selectConstructors && (d.kind === 220 || d.kind === 147 || d.kind === 146))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } + function createDefinitionInfo(node, symbolKind, symbolName, containerName) { + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function getSymbolInfo(typeChecker, symbol, node) { + return { + symbolName: typeChecker.symbolToString(symbol), + symbolKind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node), + containerName: symbol.parent ? typeChecker.symbolToString(symbol.parent, node) : "" + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + var _a = getSymbolInfo(typeChecker, decl.symbol, decl), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + return createDefinitionInfo(decl, symbolKind, symbolName, containerName); + } + function findReferenceInPosition(refs, pos) { + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + if (ref.pos <= pos && pos < ref.end) { + return ref; + } + } + return undefined; + } + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: ts.ScriptElementKind.scriptElement, + name: name, + containerName: undefined, + containerKind: undefined + }; + } + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + return callLike && typeChecker.getResolvedSignature(callLike).declaration; + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var GoToImplementation; + (function (GoToImplementation) { + function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { + if (node.parent.kind === 254) { + var result = []; + ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); + return result.length > 0 ? result : undefined; + } + else if (node.kind === 95 || ts.isSuperProperty(node.parent)) { + var symbol = typeChecker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)]; + } + else { + var referencedSymbols = ts.FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, false, false, true); + var result = ts.flatMap(referencedSymbols, function (symbol) { + return ts.map(symbol.references, function (_a) { + var textSpan = _a.textSpan, fileName = _a.fileName; + return ({ textSpan: textSpan, fileName: fileName }); + }); + }); + return result && result.length > 0 ? result : undefined; + } + } + GoToImplementation.getImplementationAtPosition = getImplementationAtPosition; + })(GoToImplementation = ts.GoToImplementation || (ts.GoToImplementation = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "augments", + "author", + "argument", + "borrows", + "class", + "constant", + "constructor", + "constructs", + "default", + "deprecated", + "description", + "event", + "example", + "extends", + "field", + "fileOverview", + "function", + "ignore", + "inner", + "lends", + "link", + "memberOf", + "name", + "namespace", + "param", + "private", + "property", + "public", + "requires", + "returns", + "see", + "since", + "static", + "throws", + "type", + "typedef", + "property", + "prop", + "version" + ]; + var jsDocCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + var comments = ts.getJSDocComments(declaration, true); + if (!comments) { + return; + } + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var comment = comments_3[_i]; + if (comment) { + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function forEachUnique(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (ts.indexOf(array, array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getAllJsDocCompletionEntries() { + return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getAllJsDocCompletionEntries = getAllJsDocCompletionEntries; + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + return undefined; + } + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenStart = tokenAtPos.getStart(); + if (!tokenAtPos || tokenStart < position) { + return undefined; + } + var commentOwner; + findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 220: + case 147: + case 148: + case 221: + case 200: + break findOwner; + case 256: + return undefined; + case 225: + if (commentOwner.parent.kind === 225) { + return undefined; + } + break findOwner; + } + } + if (!commentOwner || commentOwner.getStart() < position) { + return undefined; + } + var parameters = getParametersForJsDocOwningNode(commentOwner); + var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); + var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; + var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var docParams = ""; + for (var i = 0, numParams = parameters.length; i < numParams; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 69 ? + currentName.text : + "param" + i; + docParams += indentationStr + " * @param " + paramName + newLine; + } + var preamble = "/**" + newLine + + indentationStr + " * "; + var result = preamble + newLine + + docParams + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getParametersForJsDocOwningNode(commentOwner) { + if (ts.isFunctionLike(commentOwner)) { + return commentOwner.parameters; + } + if (commentOwner.kind === 200) { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + if (varDeclarations.length === 1 && varDeclarations[0].initializer) { + return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + } + } + return ts.emptyArray; + } + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 178) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 179: + case 180: + return rightHandSide.parameters; + case 192: + for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + return member.parameters; + } + } + break; + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = ts.createMap(result.config); + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_48 in packageNameToTypingLocation) { + if (name_48 in inferredTypings && !inferredTypings[name_48]) { + inferredTypings[name_48] = packageNameToTypingLocation[name_48]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); + } + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; var baseSensitivity = { sensitivity: "base" }; - ts.forEach(program.getSourceFiles(), function (sourceFile) { + ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_49 in nameToDeclarations) { + var declarations = nameToDeclarations[name_49]; if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_49); if (!matches) { continue; } - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (patternMatcher.patternContainsDots) { var containers = getContainers(declaration); if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_49); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -39174,8 +54159,8 @@ var ts; return items; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; if (!match.isCaseSensitive) { return false; } @@ -39243,8 +54228,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -39396,9 +54381,9 @@ var ts; case 169: case 218: var decl = node; - var name_37 = decl.name; - if (ts.isBindingPattern(name_37)) { - addChildrenRecursively(name_37); + var name_50 = decl.name; + if (ts.isBindingPattern(name_50)) { + addChildrenRecursively(name_50); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -39444,29 +54429,25 @@ var ts; addLeafNode(node); break; default: - if (node.jsDocComments) { - for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { - var jsDocComment = _j[_h]; - for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { - var tag = _l[_k]; - if (tag.kind === 279) { - addLeafNode(tag); - } + ts.forEach(node.jsDocComments, function (jsDocComment) { + ts.forEach(jsDocComment.tags, function (tag) { + if (tag.kind === 279) { + addLeafNode(tag); } - } - } + }); + }); ts.forEachChild(node, addChildrenRecursively); } } function mergeChildren(children) { - var nameToItems = {}; + var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); if (!name) { return true; } - var itemsWithSameName = ts.getProperty(nameToItems, name); + var itemsWithSameName = nameToItems[name]; if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -39595,7 +54576,7 @@ var ts; case 179: case 221: case 192: - if (node.flags & 512) { + if (ts.getModifierFlags(node) & 512) { return "default"; } return getFunctionOrClassName(node); @@ -39660,6 +54641,7 @@ var ts; case 147: case 149: case 150: + case 218: return hasSomeImportantChild(item); case 180: case 220: @@ -39694,7 +54676,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -39705,7 +54687,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -39725,46 +54707,6 @@ var ts; return spans; } } - function nodeKind(node) { - switch (node.kind) { - case 256: - return ts.ScriptElementKind.moduleElement; - case 255: - return ts.ScriptElementKind.memberVariableElement; - case 218: - case 169: - var variableDeclarationNode = void 0; - var name_38; - if (node.kind === 169) { - name_38 = node.name; - variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(!!variableDeclarationNode); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_38 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return ts.ScriptElementKind.constElement; - } - else if (ts.isLet(variableDeclarationNode)) { - return ts.ScriptElementKind.letElement; - } - else { - return ts.ScriptElementKind.variableElement; - } - case 180: - return ts.ScriptElementKind.functionElement; - case 279: - return ts.ScriptElementKind.typeElement; - default: - return ts.getNodeKind(node); - } - } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); @@ -39802,7 +54744,7 @@ var ts; else if (node.parent.kind === 253 && node.parent.name) { return nodeText(node.parent.name); } - else if (node.flags & 512) { + else if (ts.getModifierFlags(node) & 512) { return "default"; } else { @@ -39815,6 +54757,157 @@ var ts; })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile) { + var elements = []; + var collapseText = "..."; + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + if (hintSpanNode && startElement && endElement) { + var span_12 = { + textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_12); + } + } + function addOutliningSpanComments(commentSpan, autoCollapse) { + if (commentSpan) { + var span_13 = { + textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_13); + } + } + function addOutliningForLeadingCommentsForNode(n) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (comments) { + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var isFirstSingleLineComment = true; + var singleLineCommentCount = 0; + for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { + var currentComment = comments_4[_i]; + if (currentComment.kind === 2) { + if (isFirstSingleLineComment) { + firstSingleLineCommentStart = currentComment.pos; + } + isFirstSingleLineComment = false; + lastSingleLineCommentEnd = currentComment.end; + singleLineCommentCount++; + } + else if (currentComment.kind === 3) { + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + addOutliningSpanComments(currentComment, false); + singleLineCommentCount = 0; + lastSingleLineCommentEnd = -1; + isFirstSingleLineComment = true; + } + } + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + } + } + function combineAndAddMultipleSingleLineComments(count, start, end) { + if (count > 1) { + var multipleSingleLineComments = { + pos: start, + end: end, + kind: 2 + }; + addOutliningSpanComments(multipleSingleLineComments, false); + } + } + function autoCollapse(node) { + return ts.isFunctionBlock(node) && node.parent.kind !== 180; + } + var depth = 0; + var maxDepth = 20; + function walk(n) { + if (depth > maxDepth) { + return; + } + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n); + } + switch (n.kind) { + case 199: + if (!ts.isFunctionBlock(n)) { + var parent_22 = n.parent; + var openBrace = ts.findChildOfKind(n, 15, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + if (parent_22.kind === 204 || + parent_22.kind === 207 || + parent_22.kind === 208 || + parent_22.kind === 206 || + parent_22.kind === 203 || + parent_22.kind === 205 || + parent_22.kind === 212 || + parent_22.kind === 252) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + if (parent_22.kind === 216) { + var tryStatement = parent_22; + if (tryStatement.tryBlock === n) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + else if (tryStatement.finallyBlock === n) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); + if (finallyKeyword) { + addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + break; + } + } + } + var span_14 = ts.createTextSpanFromBounds(n.getStart(), n.end); + elements.push({ + textSpan: span_14, + hintSpan: span_14, + bannerText: collapseText, + autoCollapse: autoCollapse(n) + }); + break; + } + case 226: { + var openBrace = ts.findChildOfKind(n, 15, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 221: + case 222: + case 224: + case 171: + case 227: { + var openBrace = ts.findChildOfKind(n, 15, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 170: + var openBracket = ts.findChildOfKind(n, 19, sourceFile); + var closeBracket = ts.findChildOfKind(n, 20, sourceFile); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + break; + } + depth++; + ts.forEachChild(n, walk); + depth--; + } + walk(sourceFile); + return elements; + } + OutliningElementsCollector.collectElements = collectElements; + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +var ts; (function (ts) { (function (PatternMatchKind) { PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; @@ -39832,7 +54925,7 @@ var ts; }; } function createPatternMatcher(pattern) { - var stringToWordSpans = {}; + var stringToWordSpans = ts.createMap(); pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -39875,7 +54968,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -39887,7 +54980,7 @@ var ts; return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text); } else { - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -39895,9 +54988,9 @@ var ts; if (index > 0) { var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span = wordSpans_1[_i]; - if (partStartsWith(candidate, span, chunk.text, true)) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span, chunk.text, false)); + var span_15 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_15, chunk.text, true)) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span_15, chunk.text, false)); } } } @@ -40059,14 +55152,6 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function startsWith(string, search) { - for (var i = 0, n = search.length; i < n; i++) { - if (string.charCodeAt(i) !== search.charCodeAt(i)) { - return false; - } - } - return true; - } function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { if (startsWithIgnoringCase(string, value, i)) { @@ -40231,6 +55316,383 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var referencedFiles = []; + var typeReferenceDirectives = []; + var importedFiles = []; + var ambientExternalModules; + var isNoDefaultLib = false; + var braceNesting = 0; + var externalModule = false; + function nextToken() { + var token = ts.scanner.scan(); + if (token === 15) { + braceNesting++; + } + else if (token === 16) { + braceNesting--; + } + return token; + } + function processTripleSlashDirectives() { + var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); + ts.forEach(commentRanges, function (commentRange) { + var comment = sourceText.substring(commentRange.pos, commentRange.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); + if (referencePathMatchResult) { + isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var fileReference = referencePathMatchResult.fileReference; + if (fileReference) { + var collection = referencePathMatchResult.isTypeReferenceDirective + ? typeReferenceDirectives + : referencedFiles; + collection.push(fileReference); + } + } + }); + } + function getFileReference() { + var file = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { + fileName: file, + pos: pos, + end: pos + file.length + }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 122) { + token = nextToken(); + if (token === 125) { + token = nextToken(); + if (token === 9) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + function tryConsumeImport() { + var token = ts.scanner.getToken(); + if (token === 89) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + return true; + } + else { + if (token === 69 || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + return true; + } + } + else if (token === 56) { + if (tryConsumeRequireCall(true)) { + return true; + } + } + else if (token === 24) { + token = nextToken(); + } + else { + return true; + } + } + if (token === 15) { + token = nextToken(); + while (token !== 16 && token !== 1) { + token = nextToken(); + } + if (token === 16) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + } + else if (token === 37) { + token = nextToken(); + if (token === 116) { + token = nextToken(); + if (token === 69 || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 82) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 15) { + token = nextToken(); + while (token !== 16 && token !== 1) { + token = nextToken(); + } + if (token === 16) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + } + else if (token === 37) { + token = nextToken(); + if (token === 136) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + } + else if (token === 89) { + token = nextToken(); + if (token === 69 || ts.isKeyword(token)) { + token = nextToken(); + if (token === 56) { + if (tryConsumeRequireCall(true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 129) { + token = nextToken(); + if (token === 17) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 69 && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 17) { + return true; + } + token = nextToken(); + if (token === 9) { + token = nextToken(); + if (token === 24) { + token = nextToken(); + } + else { + return true; + } + } + if (token !== 19) { + return true; + } + token = nextToken(); + var i = 0; + while (token !== 20 && token !== 1) { + if (token === 9) { + recordModuleName(); + i++; + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + while (true) { + if (ts.scanner.getToken() === 1) { + break; + } + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + processTripleSlashDirectives(); + if (externalModule) { + if (ambientExternalModules) { + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + } + else { + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); + var node = ts.getTouchingWord(sourceFile, position, true); + if (node) { + if (node.kind === 69 || + node.kind === 9 || + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + ts.isThis(node)) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + if (ts.forEach(declarations, isDefinedInLibraryFile)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + if (kind) { + return { + canRename: true, + kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + else if (node.kind === 9) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (type) { + if (isDefinedInLibraryFile(node)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + else { + var displayName = ts.stripQuotes(type.text); + return { + canRename: true, + kind: ts.ScriptElementKind.variableElement, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: displayName, + kindModifiers: ts.ScriptElementKindModifier.none, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + } + } + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); + function getRenameInfoError(localizedErrorMessage) { + return { + canRename: false, + localizedErrorMessage: localizedErrorMessage, + displayName: undefined, + fullDisplayName: undefined, + kind: undefined, + kindModifiers: undefined, + triggerSpan: undefined + }; + } + function isDefinedInLibraryFile(declaration) { + if (defaultLibFileName) { + var sourceFile_1 = declaration.getSourceFile(); + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_1.fileName)); + if (canonicalName === canonicalDefaultLibName) { + return true; + } + } + return false; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 9) { + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + } + Rename.getRenameInfo = getRenameInfo; + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { @@ -40277,10 +55739,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = ts.getProperty(nameToDeclarations, name.text); + var declarations = nameToDeclarations[name.text]; if (declarations) { - for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { - var declaration = declarations_8[_b]; + for (var _b = 0, declarations_10 = declarations; _b < declarations_10.length; _b++) { + var declaration = declarations_10[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -40541,920 +56003,569 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getLineStartPositionForPosition(position, sourceFile) { - var lineStarts = sourceFile.getLineStarts(); - var line = sourceFile.getLineAndCharacterOfPosition(position).line; - return lineStarts[line]; - } - ts.getLineStartPositionForPosition = getLineStartPositionForPosition; - function rangeContainsRange(r1, r2) { - return startEndContainsRange(r1.pos, r1.end, r2); - } - ts.rangeContainsRange = rangeContainsRange; - function startEndContainsRange(start, end, range) { - return start <= range.pos && end >= range.end; - } - ts.startEndContainsRange = startEndContainsRange; - function rangeContainsStartEnd(range, start, end) { - return range.pos <= start && range.end >= end; - } - ts.rangeContainsStartEnd = rangeContainsStartEnd; - function rangeOverlapsWithStartEnd(r1, start, end) { - return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); - } - ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; - function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { - var start = Math.max(start1, start2); - var end = Math.min(end1, end2); - return start < end; - } - ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; - function positionBelongsToNode(candidate, position, sourceFile) { - return candidate.end > position || !isCompletedNode(candidate, sourceFile); - } - ts.positionBelongsToNode = positionBelongsToNode; - function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { - return false; - } - switch (n.kind) { - case 221: - case 222: - case 224: - case 171: - case 167: - case 159: - case 199: - case 226: - case 227: - case 233: - case 237: - return nodeEndsWith(n, 16, sourceFile); - case 252: - return isCompletedNode(n.block, sourceFile); - case 175: - if (!n.arguments) { - return true; - } - case 174: - case 178: - case 164: - return nodeEndsWith(n, 18, sourceFile); - case 156: - case 157: - return isCompletedNode(n.type, sourceFile); - case 148: - case 149: - case 150: - case 220: - case 179: - case 147: - case 146: - case 152: - case 151: - case 180: - if (n.body) { - return isCompletedNode(n.body, sourceFile); - } - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - return hasChildOfKind(n, 18, sourceFile); - case 225: - return n.body && isCompletedNode(n.body, sourceFile); - case 203: - if (n.elseStatement) { - return isCompletedNode(n.elseStatement, sourceFile); - } - return isCompletedNode(n.thenStatement, sourceFile); - case 202: - return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23); - case 170: - case 168: - case 173: - case 140: - case 161: - return nodeEndsWith(n, 20, sourceFile); - case 153: - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - return hasChildOfKind(n, 20, sourceFile); - case 249: - case 250: - return false; - case 206: - case 207: - case 208: - case 205: - return isCompletedNode(n.statement, sourceFile); - case 204: - var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 18, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); - case 158: - return isCompletedNode(n.exprName, sourceFile); - case 182: - case 181: - case 183: - case 190: - case 191: - var unaryWordExpression = n; - return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176: - return isCompletedNode(n.template, sourceFile); - case 189: - var lastSpan = ts.lastOrUndefined(n.templateSpans); - return isCompletedNode(lastSpan, sourceFile); - case 197: - return ts.nodeIsPresent(n.literal); - case 236: - case 230: - return ts.nodeIsPresent(n.moduleSpecifier); - case 185: - return isCompletedNode(n.operand, sourceFile); - case 187: - return isCompletedNode(n.right, sourceFile); - case 188: - return isCompletedNode(n.whenFalse, sourceFile); - default: - return true; - } - } - ts.isCompletedNode = isCompletedNode; - function nodeEndsWith(n, expectedLastToken, sourceFile) { - var children = n.getChildren(sourceFile); - if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { - return true; - } - else if (last.kind === 23 && children.length !== 1) { - return children[children.length - 2].kind === expectedLastToken; + var SymbolDisplay; + (function (SymbolDisplay) { + function getSymbolKind(typeChecker, symbol, location) { + var flags = symbol.getFlags(); + if (flags & 32) + return ts.getDeclarationOfKind(symbol, 192) ? + ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + if (flags & 384) + return ts.ScriptElementKind.enumElement; + if (flags & 524288) + return ts.ScriptElementKind.typeElement; + if (flags & 64) + return ts.ScriptElementKind.interfaceElement; + if (flags & 262144) + return ts.ScriptElementKind.typeParameterElement; + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location); + if (result === ts.ScriptElementKind.unknown) { + if (flags & 262144) + return ts.ScriptElementKind.typeParameterElement; + if (flags & 8) + return ts.ScriptElementKind.variableElement; + if (flags & 8388608) + return ts.ScriptElementKind.alias; + if (flags & 1536) + return ts.ScriptElementKind.moduleElement; } + return result; } - return false; - } - function findListItemInfo(node) { - var list = findContainingList(node); - if (!list) { - return undefined; - } - var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); - return { - listItemIndex: listItemIndex, - list: list - }; - } - ts.findListItemInfo = findListItemInfo; - function hasChildOfKind(n, kind, sourceFile) { - return !!findChildOfKind(n, kind, sourceFile); - } - ts.hasChildOfKind = hasChildOfKind; - function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); - } - ts.findChildOfKind = findChildOfKind; - function findContainingList(node) { - var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 282 && c.pos <= node.pos && c.end >= node.end) { - return c; + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location) { + if (typeChecker.isUndefinedSymbol(symbol)) { + return ts.ScriptElementKind.variableElement; } - }); - ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); - return syntaxList; - } - ts.findContainingList = findContainingList; - function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); - } - ts.getTouchingWord = getTouchingWord; - function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); - } - ts.getTouchingPropertyName = getTouchingPropertyName; - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); - } - ts.getTouchingToken = getTouchingToken; - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); - } - ts.getTokenAtPosition = getTokenAtPosition; - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - var current = sourceFile; - outer: while (true) { - if (isToken(current)) { - return current; + if (typeChecker.isArgumentsSymbol(symbol)) { + return ts.ScriptElementKind.localVariableElement; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1)) { - current = jsDocChild; - continue outer; + if (location.kind === 97 && ts.isExpression(location)) { + return ts.ScriptElementKind.parameterElement; + } + if (flags & 3) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return ts.ScriptElementKind.parameterElement; + } + else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return ts.ScriptElementKind.letElement; + } + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + } + if (flags & 16) + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + if (flags & 32768) + return ts.ScriptElementKind.memberGetAccessorElement; + if (flags & 65536) + return ts.ScriptElementKind.memberSetAccessorElement; + if (flags & 8192) + return ts.ScriptElementKind.memberFunctionElement; + if (flags & 16384) + return ts.ScriptElementKind.constructorImplementationElement; + if (flags & 4) { + if (flags & 268435456) { + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 | 3)) { + return ts.ScriptElementKind.memberVariableElement; } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; + ts.Debug.assert(!!(rootSymbolFlags & 8192)); + }); + if (!unionPropertyKind) { + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return ts.ScriptElementKind.memberFunctionElement; + } + return ts.ScriptElementKind.memberVariableElement; + } + return unionPropertyKind; + } + return ts.ScriptElementKind.memberVariableElement; + } + return ts.ScriptElementKind.unknown; + } + function getSymbolModifiers(symbol) { + return symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : ts.ScriptElementKindModifier.none; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var symbolFlags = symbol.flags; + var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); + var hasAddedSymbolInfo; + var isThisExpression = location.kind === 97 && ts.isExpression(location); + var type; + if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { + if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { + symbolKind = ts.ScriptElementKind.memberVariableElement; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (type) { + if (location.parent && location.parent.kind === 172) { + var right = location.parent.name; + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + var callExpression = void 0; + if (location.kind === 174 || location.kind === 175) { + callExpression = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpression = location.parent; + } + if (callExpression) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); + if (!signature && candidateSignatures.length) { + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpression.kind === 175 || callExpression.expression.kind === 95; + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32)) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 8388608) { + symbolKind = ts.ScriptElementKind.alias; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case ts.ScriptElementKind.memberVariableElement: + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.parameterElement: + case ts.ScriptElementKind.localVariableElement: + displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + if (!(type.flags & 2097152) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); + } + addSignatureDisplayParts(signature, allSignatures, 8); + break; + default: + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || + (location.kind === 121 && location.parent.kind === 148)) { + var functionDeclaration = location.parent; + var allSignatures = functionDeclaration.kind === 148 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration.kind === 148) { + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 && + !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { + if (ts.getDeclarationOfKind(symbol, 192)) { + pushTypePart(ts.ScriptElementKind.localClassElement); + } + else { + displayParts.push(ts.keywordPart(73)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64) && (semanticMeaning & 2)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(107)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if (symbolFlags & 524288) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(134)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); + } + if (symbolFlags & 384) { + addNewLineIfDisplayPartsExist(); + if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + displayParts.push(ts.keywordPart(74)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(81)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536) { + addNewLineIfDisplayPartsExist(); + var declaration = ts.getDeclarationOfKind(symbol, 225); + var isNamespace = declaration && declaration.name && declaration.name.kind === 69; + displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144) && (semanticMeaning & 2)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(90)); + displayParts.push(ts.spacePart()); + if (symbol.parent) { + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + var declaration = ts.getDeclarationOfKind(symbol, 141); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 152) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 151 && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); + } + else { + displayParts.push(ts.keywordPart(134)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8) { + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 255) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + } + } + } + if (symbolFlags & 8388608) { + addNewLineIfDisplayPartsExist(); + if (symbol.declarations[0].kind === 228) { + displayParts.push(ts.keywordPart(82)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(126)); + } + else { + displayParts.push(ts.keywordPart(89)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 229) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129)); + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(18)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== ts.ScriptElementKind.unknown) { + if (type) { + if (isThisExpression) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(97)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + if (symbolKind === ts.ScriptElementKind.memberVariableElement || + symbolFlags & 3 || + symbolKind === ts.ScriptElementKind.localVariableElement || + isThisExpression) { + displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.spacePart()); + if (type.symbol && type.symbol.flags & 262144) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 || + symbolFlags & 8192 || + symbolFlags & 16384 || + symbolFlags & 131072 || + symbolFlags & 98304 || + symbolKind === ts.ScriptElementKind.memberFunctionElement) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(); + if (documentation.length === 0 && symbol.flags & 4) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 187) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; } } } } } - for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { - var child = current.getChildAt(i); - if (ts.isJSDocNode(child)) { - continue; - } - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + function addNewLineIfDisplayPartsExist() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); } } - return current; - } - } - function findTokenOnLeftOfPosition(file, position) { - var tokenAtPosition = getTokenAtPosition(file, position); - if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { - return tokenAtPosition; - } - return findPrecedingToken(position, file); - } - ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { - return find(parent); - function find(n) { - if (isToken(n) && n.pos === previousToken.end) { - return n; + function addFullSymbolName(symbol, enclosingDeclaration) { + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); + ts.addRange(displayParts, fullSymbolDisplayParts); } - var children = n.getChildren(); - for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { - var child = children_1[_i]; - var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || - (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { - return find(child); + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + addNewLineIfDisplayPartsExist(); + if (symbolKind) { + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); } } - return undefined; - } - } - ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { - return find(startNode || sourceFile); - function findRightmostToken(n) { - if (isToken(n) || n.kind === 244) { - return n; - } - var children = n.getChildren(); - var candidate = findRightmostChildNodeWithTokens(children, children.length); - return candidate && findRightmostToken(candidate); - } - function find(n) { - if (isToken(n) || n.kind === 244) { - return n; - } - var children = n.getChildren(); - for (var i = 0, len = children.length; i < len; i++) { - var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 244)) { - var start = child.getStart(sourceFile); - var lookInPreviousChild = (start >= position) || - (child.kind === 244 && start === child.end); - if (lookInPreviousChild) { - var candidate = findRightmostChildNodeWithTokens(children, i); - return candidate && findRightmostToken(candidate); - } - else { - return find(child); - } + function pushTypePart(symbolKind) { + switch (symbolKind) { + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.functionElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.constructorImplementationElement: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(18)); + return; } } - ts.Debug.assert(startNode !== undefined || n.kind === 256); - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, children.length); - return candidate && findRightmostToken(candidate); - } - } - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { - for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { - return children[i]; + function addSignatureDisplayParts(signature, allSignatures, flags) { + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(17)); + displayParts.push(ts.operatorPart(35)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(18)); } + documentation = signature.getDocumentationComment(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); } } - } - ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 || previousToken.kind === 166)) { - var start = previousToken.getStart(); - var end = previousToken.getEnd(); - if (start < position && position < end) { - return true; + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; } - if (position === end) { - return !!previousToken.isUnterminated; - } - } - return false; - } - ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, undefined); - } - ts.isInComment = isInComment; - function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - if (!token) { - return false; - } - if (token.kind === 244) { - return true; - } - if (token.kind === 25 && token.parent.kind === 244) { - return true; - } - if (token.kind === 25 && token.parent.kind === 248) { - return true; - } - if (token && token.kind === 16 && token.parent.kind === 248) { - return true; - } - if (token.kind === 25 && token.parent.kind === 245) { - return true; - } - return false; - } - ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; - function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); - } - ts.isInTemplateString = isInTemplateString; - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 ? position <= c.end : position < c.end); }); - } - return false; - } - ts.isInCommentHelper = isInCommentHelper; - function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return ts.forEach(commentRanges, jsDocPrefix); - function jsDocPrefix(c) { - var text = sourceFile.text; - return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; - } - } - ts.hasDocComment = hasDocComment; - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (isToken(node)) { - switch (node.kind) { - case 102: - case 108: - case 74: - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } + return ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 179) { + return true; } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; - function nodeHasTokens(n) { - return n.getWidth() !== 0; - } - function getNodeModifiers(node) { - var flags = ts.getCombinedNodeFlags(node); - var result = []; - if (flags & 8) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 16) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 4) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 32) - result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 128) - result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1) - result.push(ts.ScriptElementKindModifier.exportedModifier); - if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; - } - ts.getNodeModifiers = getNodeModifiers; - function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 || node.kind === 174) { - return node.typeArguments; - } - if (ts.isFunctionLike(node) || node.kind === 221 || node.kind === 222) { - return node.typeParameters; - } - return undefined; - } - ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; - function isToken(n) { - return n.kind >= 0 && n.kind <= 138; - } - ts.isToken = isToken; - function isWord(kind) { - return kind === 69 || ts.isKeyword(kind); - } - ts.isWord = isWord; - function isPropertyName(kind) { - return kind === 9 || kind === 8 || isWord(kind); - } - function isComment(kind) { - return kind === 2 || kind === 3; - } - ts.isComment = isComment; - function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 - || kind === 166 - || kind === 10 - || ts.isTemplateLiteralKind(kind)) { - return true; - } - return false; - } - ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; - function isPunctuation(kind) { - return 15 <= kind && kind <= 68; - } - ts.isPunctuation = isPunctuation; - function isInsideTemplateLiteral(node, position) { - return ts.isTemplateLiteralKind(node.kind) - && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); - } - ts.isInsideTemplateLiteral = isInsideTemplateLiteral; - function isAccessibilityModifier(kind) { - switch (kind) { - case 112: - case 110: - case 111: - return true; - } - return false; - } - ts.isAccessibilityModifier = isAccessibilityModifier; - function compareDataObjects(dst, src) { - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { + if (declaration.kind !== 218 && declaration.kind !== 220) { return false; } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; + for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { + if (parent_23.kind === 256 || parent_23.kind === 226) { + return false; + } } - } + return true; + }); } - return true; - } - ts.compareDataObjects = compareDataObjects; - function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 || - node.kind === 171) { - if (node.parent.kind === 187 && - node.parent.left === node && - node.parent.operatorToken.kind === 56) { - return true; - } - if (node.parent.kind === 208 && - node.parent.initializer === node) { - return true; - } - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 ? node.parent.parent : node.parent)) { - return true; - } - } - return false; - } - ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); })(ts || (ts = {})); var ts; (function (ts) { - function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; - } - ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; - var displayPartWriter = getDisplayPartWriter(); - function getDisplayPartWriter() { - var displayParts; - var lineStart; - var indent; - resetWriter(); - return { - displayParts: function () { return displayParts; }, - writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, - writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, - writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, - writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, - writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, - writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, - writeSymbol: writeSymbol, - writeLine: writeLine, - increaseIndent: function () { indent++; }, - decreaseIndent: function () { indent--; }, - clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + options.suppressOutputPathCheck = true; + options.allowNonTsExtensions = true; + options.noLib = true; + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + options.noResolve = true; + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; + } + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); + } + var newLine = ts.getNewLineCharacter(options); + var outputText; + var sourceMapText; + var compilerHost = { + getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text, writeByteOrderMark) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + sourceMapText = text; + } + else { + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; - function writeIndent() { - if (lineStart) { - var indentString = ts.getIndentString(indent); - if (indentString) { - displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + } + program.emit(); + ts.Debug.assert(outputText !== undefined, "Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; + } + ts.transpileModule = transpileModule; + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; + } + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + function fixupCompilerOptions(options, diagnostics) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.clone(options); + var _loop_2 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + if (typeof value === "string") { + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); } - lineStart = false; } - } - function writeKind(text, kind) { - writeIndent(); - displayParts.push(displayPart(text, kind)); - } - function writeSymbol(text, symbol) { - writeIndent(); - displayParts.push(symbolPart(text, symbol)); - } - function writeLine() { - displayParts.push(lineBreakPart()); - lineStart = true; - } - function resetWriter() { - displayParts = []; - lineStart = true; - indent = 0; - } - } - function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); - function displayPartKind(symbol) { - var flags = symbol.flags; - if (flags & 3) { - return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; - } - else if (flags & 4) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 32768) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 65536) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 8) { - return ts.SymbolDisplayPartKind.enumMemberName; - } - else if (flags & 16) { - return ts.SymbolDisplayPartKind.functionName; - } - else if (flags & 32) { - return ts.SymbolDisplayPartKind.className; - } - else if (flags & 64) { - return ts.SymbolDisplayPartKind.interfaceName; - } - else if (flags & 384) { - return ts.SymbolDisplayPartKind.enumName; - } - else if (flags & 1536) { - return ts.SymbolDisplayPartKind.moduleName; - } - else if (flags & 8192) { - return ts.SymbolDisplayPartKind.methodName; - } - else if (flags & 262144) { - return ts.SymbolDisplayPartKind.typeParameterName; - } - else if (flags & 524288) { - return ts.SymbolDisplayPartKind.aliasName; - } - else if (flags & 8388608) { - return ts.SymbolDisplayPartKind.aliasName; - } - return ts.SymbolDisplayPartKind.text; - } - } - ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] }; - } - ts.displayPart = displayPart; - function spacePart() { - return displayPart(" ", ts.SymbolDisplayPartKind.space); - } - ts.spacePart = spacePart; - function keywordPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); - } - ts.keywordPart = keywordPart; - function punctuationPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); - } - ts.punctuationPart = punctuationPart; - function operatorPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); - } - ts.operatorPart = operatorPart; - function textOrKeywordPart(text) { - var kind = ts.stringToToken(text); - return kind === undefined - ? textPart(text) - : keywordPart(kind); - } - ts.textOrKeywordPart = textOrKeywordPart; - function textPart(text) { - return displayPart(text, ts.SymbolDisplayPartKind.text); - } - ts.textPart = textPart; - var carriageReturnLineFeed = "\r\n"; - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; - } - ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; - function lineBreakPart() { - return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); - } - ts.lineBreakPart = lineBreakPart; - function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; - } - ts.mapToDisplayParts = mapToDisplayParts; - function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - }); - } - ts.typeToDisplayParts = typeToDisplayParts; - function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { - return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); - }); - } - ts.symbolToDisplayParts = symbolToDisplayParts; - function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); - }); - } - ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - if (isImportOrExportSpecifierName(location)) { - return location.getText(); + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_2(opt); } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140) { - return location.text; - } - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); - return name; + return options; } - ts.getDeclaredName = getDeclaredName; - function isImportOrExportSpecifierName(location) { - return location.parent && - (location.parent.kind === 234 || location.parent.kind === 238) && - location.parent.propertyName === location; - } - ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; - function stripQuotes(name) { - var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 || name.charCodeAt(0) === 39)) { - return name.substring(1, length - 1); - } - ; - return name; - } - ts.stripQuotes = stripQuotes; - function scriptKindIs(fileName, host) { - var scriptKinds = []; - for (var _i = 2; _i < arguments.length; _i++) { - scriptKinds[_i - 2] = arguments[_i]; - } - var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); - } - ts.scriptKindIs = scriptKindIs; - function getScriptKind(fileName, host) { - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind || scriptKind === 0) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); - } - ts.getScriptKind = getScriptKind; -})(ts || (ts = {})); -var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - var safeList; - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = {}; - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - if (result.config) { - safeList = result.config; - } - else { - safeList = {}; - } - ; - } - var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - for (var name_39 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { - inferredTypings[name_39] = packageNameToTypingLocation[name_39]; - } - } - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { - inferredTypings[typing] = undefined; - } - } - } - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); - } - } - } - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; - var normalizedFileName = ts.normalizePath(fileName); - if (ts.getBaseFileName(normalizedFileName) !== "package.json") { - continue; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -41551,6 +56662,9 @@ var ts; } return false; } + function shouldRescanJsxText(node) { + return node && node.kind === 244; + } function shouldRescanSlashToken(container) { return container.kind === 10; } @@ -41578,7 +56692,9 @@ var ts; ? 3 : shouldRescanJsxIdentifier(n) ? 4 - : 0; + : shouldRescanJsxText(n) + ? 5 + : 0; if (lastTokenInfo && expectedScanAction === lastScanAction) { return fixTokenKind(lastTokenInfo, n); } @@ -41606,6 +56722,10 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4; } + else if (expectedScanAction === 5) { + currentToken = scanner.reScanJsxToken(); + lastScanAction = 5; + } else { lastScanAction = 0; } @@ -41848,9 +56968,9 @@ var ts; } return true; }; - RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); + RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41885,6 +57005,8 @@ var ts; this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); @@ -41907,7 +57029,7 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 131]), 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); @@ -41926,7 +57048,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.FromTokens([17, 19, 27, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); @@ -41938,6 +57059,11 @@ var ts; this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -41951,7 +57077,7 @@ var ts; this.SpaceAfterPostdecrementWhenFollowedBySubtract, this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, this.NoSpaceAfterCloseBrace, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, @@ -41964,6 +57090,8 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, + this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, + this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, this.SpaceAfterModuleName, @@ -41976,7 +57104,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket, this.NoSpaceBeforeCloseAngularBracket, this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, @@ -41991,8 +57118,8 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); @@ -42018,18 +57145,20 @@ var ts; this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_40 in o) { - if (o[name_40] === rule) { - return name_40; + for (var name_51 in o) { + if (o[name_51] === rule) { + return name_51; } } throw new Error("Unknown rule"); @@ -42196,12 +57325,21 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244; }; - Rules.isNonJsxElementContext = function (context) { + Rules.IsNonJsxElementContext = function (context) { return context.contextNode.kind !== 241; }; - Rules.isJsxExpressionContext = function (context) { + Rules.IsJsxExpressionContext = function (context) { return context.contextNode.kind === 248; }; + Rules.IsNextTokenParentJsxAttribute = function (context) { + return context.nextTokenParent.kind === 246; + }; + Rules.IsJsxAttributeContext = function (context) { + return context.contextNode.kind === 246; + }; + Rules.IsJsxSelfClosingElementContext = function (context) { + return context.contextNode.kind === 242; + }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -42212,7 +57350,7 @@ var ts; !Rules.NodeIsInDecoratorContext(context.nextTokenParent); }; Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isExpression(node)) { + while (ts.isPartOfExpression(node)) { node = node.parent; } return node.kind === 143; @@ -42504,21 +57642,21 @@ var ts; TokenRange.prototype.toString = function () { return this.tokenAccess.toString(); }; - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(70, 138); - TokenRange.BinaryOperators = TokenRange.FromRange(25, 68); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 138, 116, 124]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41, 42, 50, 49]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 69, 17, 19, 15, 97, 92]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([69, 130, 132, 120, 133, 103, 117]); return TokenRange; }()); + TokenRange.Any = TokenRange.AllTokens(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); + TokenRange.Keywords = TokenRange.FromRange(70, 138); + TokenRange.BinaryOperators = TokenRange.FromRange(25, 68); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 138, 116, 124]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41, 42, 50, 49]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 69, 17, 19, 15, 97, 92]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); + TokenRange.Comments = TokenRange.FromTokens([2, 3]); + TokenRange.TypeNames = TokenRange.FromTokens([69, 130, 132, 120, 133, 103, 117]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -42589,6 +57727,16 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + rules.push(this.globalRules.SpaceAfterOpenBrace); + rules.push(this.globalRules.SpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } + else { + rules.push(this.globalRules.NoSpaceAfterOpenBrace); + rules.push(this.globalRules.NoSpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); @@ -42626,6 +57774,12 @@ var ts; rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } + if (options.InsertSpaceAfterTypeAssertion) { + rules.push(this.globalRules.SpaceAfterTypeAssertion); + } + else { + rules.push(this.globalRules.NoSpaceAfterTypeAssertion); + } rules = rules.concat(this.globalRules.LowPriorityCommonRules); return rules; }; @@ -43535,7 +58689,7 @@ var ts; } } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { - var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && (parent.kind === 256 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; @@ -43788,85 +58942,22 @@ var ts; var ts; (function (ts) { ts.servicesVersion = "0.5"; - var ScriptSnapshot; - (function (ScriptSnapshot) { - var StringScriptSnapshot = (function () { - function StringScriptSnapshot(text) { - this.text = text; - } - StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringScriptSnapshot.prototype.getLength = function () { - return this.text.length; - }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { - return undefined; - }; - return StringScriptSnapshot; - }()); - function fromString(text) { - return new StringScriptSnapshot(text); - } - ScriptSnapshot.fromString = fromString; - })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - var scanner = ts.createScanner(2, true); - var emptyArray = []; - var jsDocTagNames = [ - "augments", - "author", - "argument", - "borrows", - "class", - "constant", - "constructor", - "constructs", - "default", - "deprecated", - "description", - "event", - "example", - "extends", - "field", - "fileOverview", - "function", - "ignore", - "inner", - "lends", - "link", - "memberOf", - "name", - "namespace", - "param", - "private", - "property", - "public", - "requires", - "returns", - "see", - "since", - "static", - "throws", - "type", - "typedef", - "property", - "prop", - "version" - ]; - var jsDocCompletionEntries; - function createNode(kind, pos, end, flags, parent) { - var node = new NodeObject(kind, pos, end); - node.flags = flags; + function createNode(kind, pos, end, parent) { + var node = kind >= 139 ? new NodeObject(kind, pos, end) : + kind === 69 ? new IdentifierObject(kind, pos, end) : + new TokenObject(kind, pos, end); node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { - this.kind = kind; this.pos = pos; this.end = end; this.flags = 0; + this.transformFlags = undefined; + this.excludeTransformFlags = undefined; this.parent = undefined; + this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -43893,22 +58984,25 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { - scanner.setTextPos(pos); + ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); - var textPos = scanner.getTextPos(); + var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, 0, this)); + nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282, nodes.pos, nodes.end, 0, this); + var list = createNode(286, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -43928,16 +59022,19 @@ var ts; var _this = this; var children; if (this.kind >= 139) { - scanner.setText((sourceFile || this.getSourceFile()).text); + ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 281; + var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 285; var processNode = function (node) { - if (pos_3 < node.pos) { + var isJSDocTagNode = ts.isJSDocTag(node); + if (!isJSDocTagNode && pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - pos_3 = node.end; + if (!isJSDocTagNode) { + pos_3 = node.end; + } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -43952,13 +59049,14 @@ var ts; processNode(jsDocComment); } } + pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { this.addSyntheticNodes(children, pos_3, this.end); } - scanner.setText(undefined); + ts.scanner.setText(undefined); } - this._children = children || emptyArray; + this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -43993,6 +59091,57 @@ var ts; }; return NodeObject; }()); + var TokenOrIdentifierObject = (function () { + function TokenOrIdentifierObject(pos, end) { + this.pos = pos; + this.end = end; + this.flags = 0; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + return ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + return undefined; + }; + return TokenOrIdentifierObject; + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -44009,259 +59158,28 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4)); } return this.documentationComment; }; return SymbolObject; }()); - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { - var documentationComment = []; - var docComments = getJsDocCommentsSeparatedByNewLines(); - ts.forEach(docComments, function (docComment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(docComment); - }); - return documentationComment; - function getJsDocCommentsSeparatedByNewLines() { - var paramTag = "@param"; - var jsDocCommentParts = []; - ts.forEach(declarations, function (declaration, indexOfDeclaration) { - if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); - if (canUseParsedParamTagComments && declaration.kind === 142) { - if ((declaration.parent.kind === 179 || declaration.parent.kind === 180) && - declaration.parent.parent.kind === 218) { - addCommentParts(declaration.parent.parent.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - if (declaration.kind === 225 && declaration.body && declaration.body.kind === 225) { - return; - } - if ((declaration.kind === 179 || declaration.kind === 180) && - declaration.parent.kind === 218) { - addCommentParts(declaration.parent.parent, sourceFileOfDeclaration, getCleanedJsDocComment); - } - while (declaration.kind === 225 && declaration.parent.kind === 225) { - declaration = declaration.parent; - } - addCommentParts(declaration.kind === 218 ? declaration.parent.parent : declaration, sourceFileOfDeclaration, getCleanedJsDocComment); - if (declaration.kind === 218) { - var init = declaration.initializer; - if (init && (init.kind === 179 || init.kind === 180)) { - addCommentParts(init, sourceFileOfDeclaration, getCleanedJsDocComment); - } - } - } - }); - return jsDocCommentParts; - function addCommentParts(commented, sourceFileOfDeclaration, getCommentPart) { - var ranges = getJsDocCommentTextRange(commented, sourceFileOfDeclaration); - ts.forEach(ranges, function (jsDocCommentTextRange) { - var cleanedComment = getCommentPart(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); - if (cleanedComment) { - ts.addRange(jsDocCommentParts, cleanedComment); - } - }); - } - function getJsDocCommentTextRange(node, sourceFile) { - return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { - return { - pos: jsDocComment.pos + "/*".length, - end: jsDocComment.end - "*/".length - }; - }); - } - function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { - if (maxSpacesToRemove !== undefined) { - end = Math.min(end, pos + maxSpacesToRemove); - } - for (; pos < end; pos++) { - var ch = sourceFile.text.charCodeAt(pos); - if (!ts.isWhiteSpaceSingleLine(ch)) { - return pos; - } - } - return end; - } - function consumeLineBreaks(pos, end, sourceFile) { - while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function isName(pos, end, sourceFile, name) { - return pos + name.length < end && - sourceFile.text.substr(pos, name.length) === name && - ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)); - } - function isParamTag(pos, end, sourceFile) { - return isName(pos, end, sourceFile, paramTag); - } - function pushDocCommentLineText(docComments, text, blankLineCount) { - while (blankLineCount) { - blankLineCount--; - docComments.push(ts.textPart("")); - } - docComments.push(ts.textPart(text)); - } - function getCleanedJsDocComment(pos, end, sourceFile) { - var spacesToRemoveAfterAsterisk; - var docComments = []; - var blankLineCount = 0; - var isInParamTag = false; - while (pos < end) { - var docCommentTextOfLine = ""; - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); - if (pos < end && sourceFile.text.charCodeAt(pos) === 42) { - var lineStartPos = pos + 1; - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); - if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - spacesToRemoveAfterAsterisk = pos - lineStartPos; - } - } - else if (spacesToRemoveAfterAsterisk === undefined) { - spacesToRemoveAfterAsterisk = 0; - } - while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - var ch = sourceFile.text.charAt(pos); - if (ch === "@") { - if (isParamTag(pos, end, sourceFile)) { - isInParamTag = true; - pos += paramTag.length; - continue; - } - else { - isInParamTag = false; - } - } - if (!isInParamTag) { - docCommentTextOfLine += ch; - } - pos++; - } - pos = consumeLineBreaks(pos, end, sourceFile); - if (docCommentTextOfLine) { - pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); - blankLineCount = 0; - } - else if (!isInParamTag && docComments.length) { - blankLineCount++; - } - } - return docComments; - } - function getCleanedParamJsDocComment(pos, end, sourceFile) { - var paramHelpStringMargin; - var paramDocComments = []; - while (pos < end) { - if (isParamTag(pos, end, sourceFile)) { - var blankLineCount = 0; - var recordedParamTag = false; - pos = consumeWhiteSpaces(pos + paramTag.length); - if (pos >= end) { - break; - } - if (sourceFile.text.charCodeAt(pos) === 123) { - pos++; - for (var curlies = 1; pos < end; pos++) { - var charCode = sourceFile.text.charCodeAt(pos); - if (charCode === 123) { - curlies++; - continue; - } - if (charCode === 125) { - curlies--; - if (curlies === 0) { - pos++; - break; - } - else { - continue; - } - } - if (charCode === 64) { - break; - } - } - pos = consumeWhiteSpaces(pos); - if (pos >= end) { - break; - } - } - if (isName(pos, end, sourceFile, name)) { - pos = consumeWhiteSpaces(pos + name.length); - if (pos >= end) { - break; - } - var paramHelpString = ""; - var firstLineParamHelpStringPos = pos; - while (pos < end) { - var ch = sourceFile.text.charCodeAt(pos); - if (ts.isLineBreak(ch)) { - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - paramHelpString = ""; - blankLineCount = 0; - recordedParamTag = true; - } - else if (recordedParamTag) { - blankLineCount++; - } - setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); - continue; - } - if (ch === 64) { - break; - } - paramHelpString += sourceFile.text.charAt(pos); - pos++; - } - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - } - paramHelpStringMargin = undefined; - } - if (sourceFile.text.charCodeAt(pos) === 64) { - continue; - } - } - pos++; - } - return paramDocComments; - function consumeWhiteSpaces(pos) { - while (pos < end && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { - pos = consumeLineBreaks(pos, end, sourceFile); - if (pos >= end) { - return; - } - if (paramHelpStringMargin === undefined) { - paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; - } - var startOfLinePos = pos; - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); - if (pos >= end) { - return; - } - var consumedSpaces = pos - startOfLinePos; - if (consumedSpaces < paramHelpStringMargin) { - var ch = sourceFile.text.charCodeAt(pos); - if (ch === 42) { - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); - } - } - } - } + var TokenObject = (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + _super.call(this, pos, end); + this.kind = kind; } - } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(kind, pos, end) { + _super.call(this, pos, end); + } + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 69; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -44295,7 +59213,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (1024 | 2048) + return this.flags & (32768 | 65536) ? this.checker.getBaseTypes(this) : undefined; }; @@ -44322,7 +59240,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? getJsDocCommentsFromDeclarations([this.declaration], undefined, false) : []; + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], undefined, false) : []; } return this.documentationComment; }; @@ -44352,24 +59270,23 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { var name = getDeclarationName(declaration); if (name) { - var declarations = getDeclarations(name); - declarations.push(declaration); + ts.multiMapAdd(result, name, declaration); } } function getDeclarations(name) { - return ts.getProperty(result, name) || (result[name] = []); + return result[name] || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_2 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_2 !== undefined) { - return result_2; + var result_6 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_6 !== undefined) { + return result_6; } if (declaration.name.kind === 140) { var expr = declaration.name.expression; @@ -44432,7 +59349,7 @@ var ts; ts.forEachChild(node, visit); break; case 142: - if (!(node.flags & 92)) { + if (!ts.hasModifier(node, 92)) { break; } case 218: @@ -44478,134 +59395,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); - var TextChange = (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; - var HighlightSpanKind; - (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; - })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); - (function (IndentStyle) { - IndentStyle[IndentStyle["None"] = 0] = "None"; - IndentStyle[IndentStyle["Block"] = 1] = "Block"; - IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; - (function (SymbolDisplayPartKind) { - SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; - SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; - SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; - SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; - SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; - SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; - SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; - (function (TokenClass) { - TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; - TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; - TokenClass[TokenClass["Operator"] = 2] = "Operator"; - TokenClass[TokenClass["Comment"] = 3] = "Comment"; - TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; - TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; - TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; - var ScriptElementKind; - (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; - ScriptElementKind.keyword = "keyword"; - ScriptElementKind.scriptElement = "script"; - ScriptElementKind.moduleElement = "module"; - ScriptElementKind.classElement = "class"; - ScriptElementKind.localClassElement = "local class"; - ScriptElementKind.interfaceElement = "interface"; - ScriptElementKind.typeElement = "type"; - ScriptElementKind.enumElement = "enum"; - ScriptElementKind.variableElement = "var"; - ScriptElementKind.localVariableElement = "local var"; - ScriptElementKind.functionElement = "function"; - ScriptElementKind.localFunctionElement = "local function"; - ScriptElementKind.memberFunctionElement = "method"; - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; - ScriptElementKind.memberVariableElement = "property"; - ScriptElementKind.constructorImplementationElement = "constructor"; - ScriptElementKind.callSignatureElement = "call"; - ScriptElementKind.indexSignatureElement = "index"; - ScriptElementKind.constructSignatureElement = "construct"; - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); - var ScriptElementKindModifier; - (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; - })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - return ClassificationTypeNames; - }()); - ts.ClassificationTypeNames = ClassificationTypeNames; + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; } + }; + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -44613,25 +59413,6 @@ var ts; return ""; } ts.displayPartsToString = displayPartsToString; - function isLocalVariableOrFunction(symbol) { - if (symbol.parent) { - return false; - } - return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 179) { - return true; - } - if (declaration.kind !== 218 && declaration.kind !== 220) { - return false; - } - for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { - if (parent_16.kind === 256 || parent_16.kind === 226) { - return false; - } - } - return true; - }); - } function getDefaultCompilerOptions() { return { target: 1, @@ -44736,97 +59517,6 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptionsStringToEnum; - function fixupCompilerOptions(options, diagnostics) { - commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { - return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); - }); - options = ts.clone(options); - var _loop_3 = function(opt) { - if (!ts.hasProperty(options, opt.name)) { - return "continue"; - } - var value = options[opt.name]; - if (typeof value === "string") { - options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); - } - else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { - diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); - } - } - }; - for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { - var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_3(opt); - } - return options; - } - function transpileModule(input, transpileOptions) { - var diagnostics = []; - var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : getDefaultCompilerOptions(); - options.isolatedModules = true; - options.suppressOutputPathCheck = true; - options.allowNonTsExtensions = true; - options.noLib = true; - options.lib = undefined; - options.types = undefined; - options.noEmit = undefined; - options.noEmitOnError = undefined; - options.paths = undefined; - options.rootDirs = undefined; - options.declaration = undefined; - options.declarationDir = undefined; - options.out = undefined; - options.outFile = undefined; - options.noResolve = true; - var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); - if (transpileOptions.moduleName) { - sourceFile.moduleName = transpileOptions.moduleName; - } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; - var newLine = ts.getNewLineCharacter(options); - var outputText; - var sourceMapText; - var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { - if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); - sourceMapText = text; - } - else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); - outputText = text; - } - }, - getDefaultLibFileName: function () { return "lib.d.ts"; }, - useCaseSensitiveFileNames: function () { return false; }, - getCanonicalFileName: function (fileName) { return fileName; }, - getCurrentDirectory: function () { return ""; }, - getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } - }; - var program = ts.createProgram([inputFileName], options, compilerHost); - if (transpileOptions.reportDiagnostics) { - ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); - ts.addRange(diagnostics, program.getOptionsDiagnostics()); - } - program.emit(); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); - return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; - } - ts.transpileModule = transpileModule; - function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { - var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); - ts.addRange(diagnostics, output.diagnostics); - return output.outputText; - } - ts.transpile = transpile; function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); @@ -44873,593 +59563,6 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - var buckets = {}; - var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = ts.lookUp(buckets, key); - if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(); - } - return bucket; - } - function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { - var entries = ts.lookUp(buckets, name); - var sourceFiles = []; - entries.forEachValue(function (key, entry) { - sourceFiles.push({ - name: key, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) - }); - }); - sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); - return { - bucket: name, - sourceFiles: sourceFiles - }; - }); - return JSON.stringify(bucketInfoArray, undefined, 2); - } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, true, scriptKind); - } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, false, scriptKind); - } - function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, true); - var entry = bucket.get(path); - if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); - var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); - entry = { - sourceFile: sourceFile, - languageServiceRefCount: 0, - owners: [] - }; - bucket.set(path, entry); - } - else { - if (entry.sourceFile.version !== version) { - entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); - } - } - if (acquiring) { - entry.languageServiceRefCount++; - } - return entry.sourceFile; - } - function releaseDocument(fileName, compilationSettings) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); - } - function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, false); - ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(path); - entry.languageServiceRefCount--; - ts.Debug.assert(entry.languageServiceRefCount >= 0); - if (entry.languageServiceRefCount === 0) { - bucket.remove(path); - } - } - return { - acquireDocument: acquireDocument, - acquireDocumentWithKey: acquireDocumentWithKey, - updateDocument: updateDocument, - updateDocumentWithKey: updateDocumentWithKey, - releaseDocument: releaseDocument, - releaseDocumentWithKey: releaseDocumentWithKey, - reportStats: reportStats, - getKeyForCompilationSettings: getKeyForCompilationSettings - }; - } - ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { - if (readImportFiles === void 0) { readImportFiles = true; } - if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; - var importedFiles = []; - var ambientExternalModules; - var isNoDefaultLib = false; - var braceNesting = 0; - var externalModule = false; - function nextToken() { - var token = scanner.scan(); - if (token === 15) { - braceNesting++; - } - else if (token === 16) { - braceNesting--; - } - return token; - } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } - function getFileReference() { - var file = scanner.getTokenValue(); - var pos = scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; - } - function recordAmbientExternalModule() { - if (!ambientExternalModules) { - ambientExternalModules = []; - } - ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); - } - function recordModuleName() { - importedFiles.push(getFileReference()); - markAsExternalModuleIfTopLevel(); - } - function markAsExternalModuleIfTopLevel() { - if (braceNesting === 0) { - externalModule = true; - } - } - function tryConsumeDeclare() { - var token = scanner.getToken(); - if (token === 122) { - token = nextToken(); - if (token === 125) { - token = nextToken(); - if (token === 9) { - recordAmbientExternalModule(); - } - } - return true; - } - return false; - } - function tryConsumeImport() { - var token = scanner.getToken(); - if (token === 89) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - return true; - } - else { - if (token === 69 || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - return true; - } - } - else if (token === 56) { - if (tryConsumeRequireCall(true)) { - return true; - } - } - else if (token === 24) { - token = nextToken(); - } - else { - return true; - } - } - if (token === 15) { - token = nextToken(); - while (token !== 16 && token !== 1) { - token = nextToken(); - } - if (token === 16) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - } - else if (token === 37) { - token = nextToken(); - if (token === 116) { - token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - } - } - } - return true; - } - return false; - } - function tryConsumeExport() { - var token = scanner.getToken(); - if (token === 82) { - markAsExternalModuleIfTopLevel(); - token = nextToken(); - if (token === 15) { - token = nextToken(); - while (token !== 16 && token !== 1) { - token = nextToken(); - } - if (token === 16) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - } - else if (token === 37) { - token = nextToken(); - if (token === 136) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - } - else if (token === 89) { - token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { - token = nextToken(); - if (token === 56) { - if (tryConsumeRequireCall(true)) { - return true; - } - } - } - } - return true; - } - return false; - } - function tryConsumeRequireCall(skipCurrentToken) { - var token = skipCurrentToken ? nextToken() : scanner.getToken(); - if (token === 129) { - token = nextToken(); - if (token === 17) { - token = nextToken(); - if (token === 9) { - recordModuleName(); - } - } - return true; - } - return false; - } - function tryConsumeDefine() { - var token = scanner.getToken(); - if (token === 69 && scanner.getTokenValue() === "define") { - token = nextToken(); - if (token !== 17) { - return true; - } - token = nextToken(); - if (token === 9) { - token = nextToken(); - if (token === 24) { - token = nextToken(); - } - else { - return true; - } - } - if (token !== 19) { - return true; - } - token = nextToken(); - var i = 0; - while (token !== 20 && token !== 1) { - if (token === 9) { - recordModuleName(); - i++; - } - token = nextToken(); - } - return true; - } - return false; - } - function processImports() { - scanner.setText(sourceText); - nextToken(); - while (true) { - if (scanner.getToken() === 1) { - break; - } - if (tryConsumeDeclare() || - tryConsumeImport() || - tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(false) || tryConsumeDefine()))) { - continue; - } - else { - nextToken(); - } - } - scanner.setText(undefined); - } - if (readImportFiles) { - processImports(); - } - processTripleSlashDirectives(); - if (externalModule) { - if (ambientExternalModules) { - for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { - var decl = ambientExternalModules_1[_i]; - importedFiles.push(decl.ref); - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; - } - else { - var ambientModuleNames = void 0; - if (ambientExternalModules) { - for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { - var decl = ambientExternalModules_2[_a]; - if (decl.depth === 0) { - if (!ambientModuleNames) { - ambientModuleNames = []; - } - ambientModuleNames.push(decl.ref.fileName); - } - else { - importedFiles.push(decl.ref); - } - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; - } - } - ts.preProcessFile = preProcessFile; - function getTargetLabel(referenceNode, labelName) { - while (referenceNode) { - if (referenceNode.kind === 214 && referenceNode.label.text === labelName) { - return referenceNode.label; - } - referenceNode = referenceNode.parent; - } - return undefined; - } - function isJumpStatementTarget(node) { - return node.kind === 69 && - (node.parent.kind === 210 || node.parent.kind === 209) && - node.parent.label === node; - } - function isLabelOfLabeledStatement(node) { - return node.kind === 69 && - node.parent.kind === 214 && - node.parent.label === node; - } - function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214; owner = owner.parent) { - if (owner.label.text === labelName) { - return true; - } - } - return false; - } - function isLabelName(node) { - return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); - } - function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 && node.parent.right === node; - } - function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 && node.parent.name === node; - } - function isCallExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 174 && node.parent.expression === node; - } - function isNewExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 175 && node.parent.expression === node; - } - function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 && node.parent.name === node; - } - function isNameOfFunctionDeclaration(node) { - return node.kind === 69 && - ts.isFunctionLike(node.parent) && node.parent.name === node; - } - function isObjectLiteralPropertyDeclaration(node) { - switch (node.kind) { - case 253: - case 254: - case 147: - case 149: - case 150: - return true; - } - return false; - } - function getContainingObjectLiteralElement(node) { - switch (node.kind) { - case 9: - case 8: - if (node.parent.kind === 140) { - return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; - } - case 69: - return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; - } - return undefined; - } - function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 || node.kind === 8) { - switch (node.parent.kind) { - case 145: - case 144: - case 253: - case 255: - case 147: - case 146: - case 149: - case 150: - case 225: - return node.parent.name === node; - case 173: - return node.parent.argumentExpression === node; - case 140: - return true; - } - } - return false; - } - function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9) { - return isNameOfModuleDeclaration(node) || - (ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node); - } - return false; - } - function isInsideComment(sourceFile, token, position) { - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47) { - return true; - } - else { - return !(text.charCodeAt(comment.end - 1) === 47 && - text.charCodeAt(comment.end - 2) === 42); - } - } - return false; - }); - } - } - var keywordCompletions = []; - for (var i = 70; i <= 138; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - sortText: "0" - }); - } - function getContainerNode(node) { - while (true) { - node = node.parent; - if (!node) { - return undefined; - } - switch (node.kind) { - case 256: - case 147: - case 146: - case 220: - case 179: - case 149: - case 150: - case 221: - case 222: - case 224: - case 225: - return node; - } - } - } - ts.getContainerNode = getContainerNode; - function getNodeKind(node) { - switch (node.kind) { - case 225: return ScriptElementKind.moduleElement; - case 221: - case 192: - return ScriptElementKind.classElement; - case 222: return ScriptElementKind.interfaceElement; - case 223: return ScriptElementKind.typeElement; - case 224: return ScriptElementKind.enumElement; - case 218: - return ts.isConst(node) - ? ScriptElementKind.constElement - : ts.isLet(node) - ? ScriptElementKind.letElement - : ScriptElementKind.variableElement; - case 220: - case 179: - return ScriptElementKind.functionElement; - case 149: return ScriptElementKind.memberGetAccessorElement; - case 150: return ScriptElementKind.memberSetAccessorElement; - case 147: - case 146: - return ScriptElementKind.memberFunctionElement; - case 145: - case 144: - return ScriptElementKind.memberVariableElement; - case 153: return ScriptElementKind.indexSignatureElement; - case 152: return ScriptElementKind.constructSignatureElement; - case 151: return ScriptElementKind.callSignatureElement; - case 148: return ScriptElementKind.constructorImplementationElement; - case 141: return ScriptElementKind.typeParameterElement; - case 255: return ScriptElementKind.variableElement; - case 142: return (node.flags & 92) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 229: - case 234: - case 231: - case 238: - case 232: - return ScriptElementKind.alias; - } - return ScriptElementKind.unknown; - } - ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { function CancellationTokenObject(cancellationToken) { this.cancellationToken = cancellationToken; @@ -45475,7 +59578,7 @@ var ts; return CancellationTokenObject; }()); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; @@ -45522,14 +59625,16 @@ var ts; } var oldSettings = program && program.getCompilerOptions(); var newSettings = hostCache.compilationSettings(); - var changesInCompilationSettingsAffectSyntax = oldSettings && + var shouldCreateNewSourceFiles = oldSettings && (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.baseUrl !== newSettings.baseUrl || + !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, @@ -45541,7 +59646,6 @@ var ts; writeFile: function (fileName, data, writeByteOrderMark) { }, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return hostCache.getOrCreateEntry(fileName) !== undefined; }, readFile: function (fileName) { @@ -45573,7 +59677,7 @@ var ts; var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } } @@ -45591,7 +59695,7 @@ var ts; if (!hostFileInformation) { return undefined; } - if (!changesInCompilationSettingsAffectSyntax) { + if (!shouldCreateNewSourceFiles) { var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); @@ -45655,1240 +59759,17 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - if ((symbol.flags & 1536) && (firstCharCode === 39 || firstCharCode === 34)) { - return undefined; - } - } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); - } - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { - return undefined; - } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } - if (performCharacterChecks) { - if (!ts.isIdentifier(name, target)) { - return undefined; - } - } - return name; - } - function getCompletionData(fileName, position) { - var typeChecker = program.getTypeChecker(); - var sourceFile = getValidSourceFile(fileName); - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - var isJsDocTagName = false; - var start = new Date().getTime(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); - var insideComment = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); - if (insideComment) { - if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64) { - isJsDocTagName = true; - } - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); - if (tag) { - if (tag.tagName.pos <= position && position <= tag.tagName.end) { - isJsDocTagName = true; - } - switch (tag.kind) { - case 277: - case 275: - case 276: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; - } - } - if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; - } - if (!insideJsDocTagExpression) { - log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); - return undefined; - } - } - start = new Date().getTime(); - var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); - var contextToken = previousToken; - if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_5 = new Date().getTime(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); - } - var node = currentToken; - var isRightOfDot = false; - var isRightOfOpenTag = false; - var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); - if (contextToken) { - if (isCompletionListBlocker(contextToken)) { - log("Returning an empty list because completion was requested in an invalid position."); - return undefined; - } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21) { - if (parent_17.kind === 172) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent_17.kind === 139) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - return undefined; - } - } - else if (sourceFile.languageVariant === 1) { - if (kind === 25) { - isRightOfOpenTag = true; - location = contextToken; - } - else if (kind === 39 && contextToken.parent.kind === 245) { - isStartingCloseTag = true; - location = contextToken; - } - } - } - var semanticStart = new Date().getTime(); - var isMemberCompletion; - var isNewIdentifierLocation; - var symbols = []; - if (isRightOfDot) { - getTypeScriptMemberSymbols(); - } - else if (isRightOfOpenTag) { - var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); - if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 8388608)); })); - } - else { - symbols = tagSymbols; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else if (isStartingCloseTag) { - var tagName = contextToken.parent.parent.openingElement.tagName; - var tagSymbol = typeChecker.getSymbolAtLocation(tagName); - if (!typeChecker.isUnknownSymbol(tagSymbol)) { - symbols = [tagSymbol]; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else { - if (!tryGetGlobalSymbols()) { - return undefined; - } - } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; - function getTypeScriptMemberSymbols() { - isMemberCompletion = true; - isNewIdentifierLocation = false; - if (node.kind === 69 || node.kind === 139 || node.kind === 172) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol && symbol.flags & 8388608) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - }); - } - } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); - } - function addTypeProperties(type) { - if (type) { - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - } - if (isJavaScriptFile && type.flags & 16384) { - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } - } - } - } - function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - return tryGetObjectLikeCompletionSymbols(objectLikeContainer); - } - if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { - return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); - } - if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType = void 0; - if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { - attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); - if (attrsType) { - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); - isMemberCompletion = true; - isNewIdentifierLocation = false; - return true; - } - } - } - isMemberCompletion = false; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); - if (previousToken !== contextToken) { - ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); - } - var adjustedPosition = previousToken !== contextToken ? - previousToken.getStart() : - position; - var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - var symbolMeanings = 793056 | 107455 | 1536 | 8388608; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); - return true; - } - function getScopeNode(initialToken, position, sourceFile) { - var scope = initialToken; - while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { - scope = scope.parent; - } - return scope; - } - function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); - var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || - isSolelyIdentifierDefinitionLocation(contextToken) || - isDotOfNumericLiteral(contextToken) || - isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); - return result; - } - function isInJsxText(contextToken) { - if (contextToken.kind === 244) { - return true; - } - if (contextToken.kind === 27 && contextToken.parent) { - if (contextToken.parent.kind === 243) { - return true; - } - if (contextToken.parent.kind === 245 || contextToken.parent.kind === 242) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241; - } - } - return false; - } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { - case 24: - return containingNodeKind === 174 - || containingNodeKind === 148 - || containingNodeKind === 175 - || containingNodeKind === 170 - || containingNodeKind === 187 - || containingNodeKind === 156; - case 17: - return containingNodeKind === 174 - || containingNodeKind === 148 - || containingNodeKind === 175 - || containingNodeKind === 178 - || containingNodeKind === 164; - case 19: - return containingNodeKind === 170 - || containingNodeKind === 153 - || containingNodeKind === 140; - case 125: - case 126: - return true; - case 21: - return containingNodeKind === 225; - case 15: - return containingNodeKind === 221; - case 56: - return containingNodeKind === 218 - || containingNodeKind === 187; - case 12: - return containingNodeKind === 189; - case 13: - return containingNodeKind === 197; - case 112: - case 110: - case 111: - return containingNodeKind === 145; - } - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": - return true; - } - } - return false; - } - function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { - if (contextToken.kind === 9 - || contextToken.kind === 166 - || contextToken.kind === 10 - || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_6 = contextToken.getStart(); - var end = contextToken.getEnd(); - if (start_6 < position && position < end) { - return true; - } - if (position === end) { - return !!contextToken.isUnterminated - || contextToken.kind === 10; - } - } - return false; - } - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { - isMemberCompletion = true; - var typeForObject; - var existingMembers; - if (objectLikeContainer.kind === 171) { - isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - existingMembers = objectLikeContainer.properties; - } - else if (objectLikeContainer.kind === 167) { - isNewIdentifierLocation = false; - var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 147 || rootDeclaration.parent.kind === 150) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } - } - if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - existingMembers = objectLikeContainer.elements; - } - } - else { - ts.Debug.fail("Root declaration is not variable-like."); - } - } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); - if (typeMembers && typeMembers.length > 0) { - symbols = filterObjectMembersList(typeMembers, existingMembers); - } - return true; - } - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 ? - 230 : - 236; - var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); - var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; - if (!moduleSpecifier) { - return false; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - var exports; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); - if (moduleSpecifierSymbol) { - exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); - } - symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; - return true; - } - function tryGetObjectLikeCompletionContainer(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15: - case 24: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 || parent_18.kind === 167)) { - return parent_18; - } - break; - } - } - return undefined; - } - function tryGetNamedImportsOrExportsForCompletion(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15: - case 24: - switch (contextToken.parent.kind) { - case 233: - case 237: - return contextToken.parent; - } - } - } - return undefined; - } - function tryGetContainingJsxElement(contextToken) { - if (contextToken) { - var parent_19 = contextToken.parent; - switch (contextToken.kind) { - case 26: - case 39: - case 69: - case 246: - case 247: - if (parent_19 && (parent_19.kind === 242 || parent_19.kind === 243)) { - return parent_19; - } - else if (parent_19.kind === 246) { - return parent_19.parent; - } - break; - case 9: - if (parent_19 && ((parent_19.kind === 246) || (parent_19.kind === 247))) { - return parent_19.parent; - } - break; - case 16: - if (parent_19 && - parent_19.kind === 248 && - parent_19.parent && - (parent_19.parent.kind === 246)) { - return parent_19.parent.parent; - } - if (parent_19 && parent_19.kind === 247) { - return parent_19.parent; - } - break; - } - } - return undefined; - } - function isFunction(kind) { - switch (kind) { - case 179: - case 180: - case 220: - case 147: - case 146: - case 149: - case 150: - case 151: - case 152: - case 153: - return true; - } - return false; - } - function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; - switch (contextToken.kind) { - case 24: - return containingNodeKind === 218 || - containingNodeKind === 219 || - containingNodeKind === 200 || - containingNodeKind === 224 || - isFunction(containingNodeKind) || - containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 168 || - containingNodeKind === 223; - case 21: - return containingNodeKind === 168; - case 54: - return containingNodeKind === 169; - case 19: - return containingNodeKind === 168; - case 17: - return containingNodeKind === 252 || - isFunction(containingNodeKind); - case 15: - return containingNodeKind === 224 || - containingNodeKind === 222 || - containingNodeKind === 159; - case 23: - return containingNodeKind === 144 && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 || - contextToken.parent.parent.kind === 159); - case 25: - return containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 223 || - isFunction(containingNodeKind); - case 113: - return containingNodeKind === 145; - case 22: - return containingNodeKind === 142 || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168); - case 112: - case 110: - case 111: - return containingNodeKind === 142; - case 116: - return containingNodeKind === 234 || - containingNodeKind === 238 || - containingNodeKind === 232; - case 73: - case 81: - case 107: - case 87: - case 102: - case 123: - case 131: - case 89: - case 108: - case 74: - case 114: - case 134: - return true; - } - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": - return true; - } - return false; - } - function isDotOfNumericLiteral(contextToken) { - if (contextToken.kind === 8) { - var text = contextToken.getFullText(); - return text.charAt(text.length - 1) === "."; - } - return false; - } - function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; - for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { - var element = namedImportsOrExports_1[_i]; - if (element.getStart() <= position && position <= element.getEnd()) { - continue; - } - var name_41 = element.propertyName || element.name; - existingImportsOrExports[name_41.text] = true; - } - if (ts.isEmpty(existingImportsOrExports)) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); - } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !ts.lookUp(existingImportsOrExports, e.name); }); - } - function filterObjectMembersList(contextualMemberSymbols, existingMembers) { - if (!existingMembers || existingMembers.length === 0) { - return contextualMemberSymbols; - } - var existingMemberNames = {}; - for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { - var m = existingMembers_1[_i]; - if (m.kind !== 253 && - m.kind !== 254 && - m.kind !== 169 && - m.kind !== 147) { - continue; - } - if (m.getStart() <= position && position <= m.getEnd()) { - continue; - } - var existingName = void 0; - if (m.kind === 169 && m.propertyName) { - if (m.propertyName.kind === 69) { - existingName = m.propertyName.text; - } - } - else { - existingName = m.name.text; - } - existingMemberNames[existingName] = true; - } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); - } - function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; - for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { - var attr = attributes_1[_i]; - if (attr.getStart() <= position && position <= attr.getEnd()) { - continue; - } - if (attr.kind === 246) { - seenNames[attr.name.text] = true; - } - } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); - } - } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position); - } - var completionData = getCompletionData(fileName, position); - if (!completionData) { - return undefined; - } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; - if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; - } - var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); - } - else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 && - location.parent && location.parent.kind === 245) { - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0" - }); - } - else { - return undefined; - } - } - getCompletionEntriesFromSymbols(symbols, entries, location, true); - } - if (!isMemberCompletion && !isJsDocTagName) { - ts.addRange(entries, keywordCompletions); - } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { - var entries = []; - var target = program.getCompilerOptions().target; - var nameTable = getNameTable(sourceFile); - for (var name_42 in nameTable) { - if (nameTable[name_42] === position) { - continue; - } - if (!uniqueNames[name_42]) { - uniqueNames[name_42] = name_42; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, true); - if (displayName) { - var entry = { - name: displayName, - kind: ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } - } - } - return entries; - } - function getAllJsDocCompletionEntries() { - return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { - return { - name: tagName, - kind: ScriptElementKind.keyword, - kindModifiers: "", - sortText: "0" - }; - })); - } - function createCompletionEntry(symbol, location, performCharacterChecks) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, performCharacterChecks, location); - if (!displayName) { - return undefined; - } - return { - name: displayName, - kind: getSymbolKind(symbol, location), - kindModifiers: getSymbolModifiers(symbol), - sortText: "0" - }; - } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; - if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks); - if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(uniqueNames, id)) { - entries.push(entry); - uniqueNames[id] = id; - } - } - } - } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return uniqueNames; - } - function getStringLiteralCompletionEntries(sourceFile, position) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9) { - return undefined; - } - var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - return getStringLiteralCompletionEntriesFromElementAccess(node.parent); - } - else { - return getStringLiteralCompletionEntriesFromContextualType(node); - } - } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { - var typeChecker = program.getTypeChecker(); - var candidates = []; - var entries = []; - typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); - for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { - var candidate = candidates_3[_i]; - if (candidate.parameters.length > argumentInfo.argumentIndex) { - var parameter = candidate.parameters[argumentInfo.argumentIndex]; - addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); - } - } - if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; - } - return undefined; - } - function getStringLiteralCompletionEntriesFromElementAccess(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getTypeAtLocation(node.expression); - var entries = []; - if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); - if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; - } - } - return undefined; - } - function getStringLiteralCompletionEntriesFromContextualType(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getContextualType(node); - if (type) { - var entries_2 = []; - addStringLiteralCompletionsFromType(type, entries_2); - if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; - } - } - return undefined; - } - function addStringLiteralCompletionsFromType(type, result) { - if (!type) { - return; - } - if (type.flags & 16384) { - ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); - } - else { - if (type.flags & 256) { - result.push({ - name: type.text, - kindModifiers: ScriptElementKindModifier.none, - kind: ScriptElementKind.variableElement, - sortText: "0" - }); - } - } - } + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); - var completionData = getCompletionData(fileName, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - var target_2 = program.getCompilerOptions().target; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, false, location_2) === entryName ? s : undefined; }); - if (symbol) { - var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; - return { - name: entryName, - kindModifiers: getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation - }; - } - } - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - displayParts: [ts.displayPart(entryName, SymbolDisplayPartKind.keyword)], - documentation: undefined - }; - } - return undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } - function getSymbolKind(symbol, location) { - var flags = symbol.getFlags(); - if (flags & 32) - return ts.getDeclarationOfKind(symbol, 192) ? - ScriptElementKind.localClassElement : ScriptElementKind.classElement; - if (flags & 384) - return ScriptElementKind.enumElement; - if (flags & 524288) - return ScriptElementKind.typeElement; - if (flags & 64) - return ScriptElementKind.interfaceElement; - if (flags & 262144) - return ScriptElementKind.typeParameterElement; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location); - if (result === ScriptElementKind.unknown) { - if (flags & 262144) - return ScriptElementKind.typeParameterElement; - if (flags & 8) - return ScriptElementKind.variableElement; - if (flags & 8388608) - return ScriptElementKind.alias; - if (flags & 1536) - return ScriptElementKind.moduleElement; - } - return result; - } - function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location) { - var typeChecker = program.getTypeChecker(); - if (typeChecker.isUndefinedSymbol(symbol)) { - return ScriptElementKind.variableElement; - } - if (typeChecker.isArgumentsSymbol(symbol)) { - return ScriptElementKind.localVariableElement; - } - if (location.kind === 97 && ts.isExpression(location)) { - return ScriptElementKind.parameterElement; - } - if (flags & 3) { - if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ScriptElementKind.parameterElement; - } - else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ScriptElementKind.constElement; - } - else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ScriptElementKind.letElement; - } - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement; - } - if (flags & 16) - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localFunctionElement : ScriptElementKind.functionElement; - if (flags & 32768) - return ScriptElementKind.memberGetAccessorElement; - if (flags & 65536) - return ScriptElementKind.memberSetAccessorElement; - if (flags & 8192) - return ScriptElementKind.memberFunctionElement; - if (flags & 16384) - return ScriptElementKind.constructorImplementationElement; - if (flags & 4) { - if (flags & 268435456) { - var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - var rootSymbolFlags = rootSymbol.getFlags(); - if (rootSymbolFlags & (98308 | 3)) { - return ScriptElementKind.memberVariableElement; - } - ts.Debug.assert(!!(rootSymbolFlags & 8192)); - }); - if (!unionPropertyKind) { - var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (typeOfUnionProperty.getCallSignatures().length) { - return ScriptElementKind.memberFunctionElement; - } - return ScriptElementKind.memberVariableElement; - } - return unionPropertyKind; - } - return ScriptElementKind.memberVariableElement; - } - return ScriptElementKind.unknown; - } - function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 - ? ts.getNodeModifiers(symbol.declarations[0]) - : ScriptElementKindModifier.none; - } - function getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { - if (semanticMeaning === void 0) { semanticMeaning = getMeaningFromLocation(location); } - var typeChecker = program.getTypeChecker(); - var displayParts = []; - var documentation; - var symbolFlags = symbol.flags; - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, location); - var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 && ts.isExpression(location); - var type; - if (symbolKind !== ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { - if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { - symbolKind = ScriptElementKind.memberVariableElement; - } - var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (type) { - if (location.parent && location.parent.kind === 172) { - var right = location.parent.name; - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; - } - } - var callExpression = void 0; - if (location.kind === 174 || location.kind === 175) { - callExpression = location; - } - else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { - callExpression = location.parent; - } - if (callExpression) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); - if (!signature && candidateSignatures.length) { - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpression.kind === 175 || callExpression.expression.kind === 95; - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32)) { - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else if (symbolFlags & 8388608) { - symbolKind = ScriptElementKind.alias; - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); - displayParts.push(ts.spacePart()); - } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case ScriptElementKind.memberVariableElement: - case ScriptElementKind.variableElement: - case ScriptElementKind.constElement: - case ScriptElementKind.letElement: - case ScriptElementKind.parameterElement: - case ScriptElementKind.localVariableElement: - displayParts.push(ts.punctuationPart(54)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 65536) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); - } - addSignatureDisplayParts(signature, allSignatures, 8); - break; - default: - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; - } - } - else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || - (location.kind === 121 && location.parent.kind === 148)) { - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); - } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 148) { - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; - } - } - } - if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192)) { - pushTypePart(ScriptElementKind.localClassElement); - } - else { - displayParts.push(ts.keywordPart(73)); - } - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if ((symbolFlags & 64) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if (symbolFlags & 524288) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); - } - if (symbolFlags & 384) { - addNewLineIfDisplayPartsExist(); - if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74)); - displayParts.push(ts.spacePart()); - } - displayParts.push(ts.keywordPart(81)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if (symbolFlags & 1536) { - addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69; - displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if ((symbolFlags & 262144) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(18)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90)); - displayParts.push(ts.spacePart()); - if (symbol.parent) { - addFullSymbolName(symbol.parent, enclosingDeclaration); - writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); - } - else { - var declaration = ts.getDeclarationOfKind(symbol, 141); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; - if (declaration) { - if (ts.isFunctionLikeKind(declaration.kind)) { - var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152) { - displayParts.push(ts.keywordPart(92)); - displayParts.push(ts.spacePart()); - } - else if (declaration.kind !== 151 && declaration.name) { - addFullSymbolName(declaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); - } - else { - displayParts.push(ts.keywordPart(134)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); - } - } - } - } - if (symbolFlags & 8) { - addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 255) { - var constantValue = typeChecker.getConstantValue(declaration); - if (constantValue !== undefined) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral)); - } - } - } - if (symbolFlags & 8388608) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229) { - var importEqualsDeclaration = declaration; - if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129)); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(18)); - } - else { - var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); - if (internalAliasSymbol) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); - displayParts.push(ts.spacePart()); - addFullSymbolName(internalAliasSymbol, enclosingDeclaration); - } - } - return true; - } - }); - } - if (!hasAddedSymbolInfo) { - if (symbolKind !== ScriptElementKind.unknown) { - if (type) { - if (isThisExpression) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97)); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - if (symbolKind === ScriptElementKind.memberVariableElement || - symbolFlags & 3 || - symbolKind === ScriptElementKind.localVariableElement || - isThisExpression) { - displayParts.push(ts.punctuationPart(54)); - displayParts.push(ts.spacePart()); - if (type.symbol && type.symbol.flags & 262144) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } - else { - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); - } - } - else if (symbolFlags & 16 || - symbolFlags & 8192 || - symbolFlags & 16384 || - symbolFlags & 131072 || - symbolFlags & 98304 || - symbolKind === ScriptElementKind.memberFunctionElement) { - var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); - } - } - } - else { - symbolKind = getSymbolKind(symbol, location); - } - } - if (!documentation) { - documentation = symbol.getDocumentationComment(); - } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; - function addNewLineIfDisplayPartsExist() { - if (displayParts.length) { - displayParts.push(ts.lineBreakPart()); - } - } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); - ts.addRange(displayParts, fullSymbolDisplayParts); - } - function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); - if (symbolKind) { - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - } - function pushTypePart(symbolKind) { - switch (symbolKind) { - case ScriptElementKind.variableElement: - case ScriptElementKind.functionElement: - case ScriptElementKind.letElement: - case ScriptElementKind.constElement: - case ScriptElementKind.constructorImplementationElement: - displayParts.push(ts.textOrKeywordPart(symbolKind)); - return; - default: - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(18)); - return; - } - } - function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); - if (allSignatures.length > 1) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.operatorPart(35)); - displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), SymbolDisplayPartKind.numericLiteral)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18)); - } - documentation = signature.getDocumentationComment(); - } - function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } + function getCompletionEntrySymbol(fileName, position, entryName) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -46897,7 +59778,7 @@ var ts; if (node === sourceFile) { return undefined; } - if (isLabelName(node)) { + if (ts.isLabelName(node)) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -46913,200 +59794,42 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ScriptElementKind.unknown, - kindModifiers: ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.unknown, + kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: ts.typeToDisplayParts(typeChecker, type, getContainerNode(node)), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined }; } } return undefined; } - var displayPartsDocumentationsAndKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, getContainerNode(node), node); + var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); return { kind: displayPartsDocumentationsAndKind.symbolKind, - kindModifiers: getSymbolModifiers(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, documentation: displayPartsDocumentationsAndKind.documentation }; } - function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), - kind: symbolKind, - name: symbolName, - containerKind: undefined, - containerName: containerName - }; - } - function getDefinitionFromSymbol(symbol, node) { - var typeChecker = program.getTypeChecker(); - var result = []; - var declarations = symbol.getDeclarations(); - var symbolName = typeChecker.symbolToString(symbol); - var symbolKind = getSymbolKind(symbol, node); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isNewExpressionTarget(location) || location.kind === 121) { - if (symbol.flags & 32) { - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } - } - return false; - } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); - } - return false; - } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { - var declarations = []; - var definition; - ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148) || - (!selectConstructors && (d.kind === 220 || d.kind === 147 || d.kind === 146))) { - declarations.push(d); - if (d.body) - definition = d; - } - }); - if (definition) { - result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); - return true; - } - else if (declarations.length) { - result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; - } - } - function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { - return ref; - } - } - return undefined; - } - function getDefinitionInfoForFileReference(name, targetFileName) { - return { - fileName: targetFileName, - textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ScriptElementKind.scriptElement, - name: name, - containerName: undefined, - containerKind: undefined - }; - } function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - return undefined; - } - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); - if (referenceFile && referenceFile.resolvedFileName) { - return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; - } - return undefined; - } - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - if (isJumpStatementTarget(node)) { - var labelName = node.text; - var label = getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, undefined)] : undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - if (symbol.flags & 8388608) { - var declaration = symbol.declarations[0]; - if (node.kind === 69 && - (node.parent === declaration || - (declaration.kind === 234 && declaration.parent && declaration.parent.kind === 233))) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - } - if (node.parent.kind === 254) { - var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - if (!shorthandSymbol) { - return []; - } - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); - var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); - } - return getDefinitionFromSymbol(symbol, node); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToImplementation.getImplementationAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { - return undefined; - } - if (type.flags & 16384) { - var result_3 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(result_3, getDefinitionFromSymbol(t.symbol, node)); - } - }); - return result_3; - } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(type.symbol, node); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -47114,492 +59837,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingWord(sourceFile, position); - if (!node) { - return undefined; - } - return getSemanticDocumentHighlights(node) || getSyntacticDocumentHighlights(node); - function getHighlightSpanForNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - return { - fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: HighlightSpanKind.none - }; - } - function getSemanticDocumentHighlights(node) { - if (node.kind === 69 || - node.kind === 97 || - node.kind === 165 || - node.kind === 95 || - node.kind === 9 || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, false, false); - return convertReferencedSymbols(referencedSymbols); - } - return undefined; - function convertReferencedSymbols(referencedSymbols) { - if (!referencedSymbols) { - return undefined; - } - var fileNameToDocumentHighlights = {}; - var result = []; - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var referencedSymbol = referencedSymbols_1[_i]; - for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { - var referenceEntry = _b[_a]; - var fileName_1 = referenceEntry.fileName; - var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); - if (!documentHighlights) { - documentHighlights = { fileName: fileName_1, highlightSpans: [] }; - fileNameToDocumentHighlights[fileName_1] = documentHighlights; - result.push(documentHighlights); - } - documentHighlights.highlightSpans.push({ - textSpan: referenceEntry.textSpan, - kind: referenceEntry.isWriteAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference - }); - } - } - return result; - } - } - function getSyntacticDocumentHighlights(node) { - var fileName = sourceFile.fileName; - var highlightSpans = getHighlightSpans(node); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: fileName, highlightSpans: highlightSpans }]; - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - function parent(node) { - return node && node.parent; - } - function getHighlightSpans(node) { - if (node) { - switch (node.kind) { - case 88: - case 80: - if (hasKind(node.parent, 203)) { - return getIfElseOccurrences(node.parent); - } - break; - case 94: - if (hasKind(node.parent, 211)) { - return getReturnOccurrences(node.parent); - } - break; - case 98: - if (hasKind(node.parent, 215)) { - return getThrowOccurrences(node.parent); - } - break; - case 72: - if (hasKind(parent(parent(node)), 216)) { - return getTryCatchFinallyOccurrences(node.parent.parent); - } - break; - case 100: - case 85: - if (hasKind(parent(node), 216)) { - return getTryCatchFinallyOccurrences(node.parent); - } - break; - case 96: - if (hasKind(node.parent, 213)) { - return getSwitchCaseDefaultOccurrences(node.parent); - } - break; - case 71: - case 77: - if (hasKind(parent(parent(parent(node))), 213)) { - return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); - } - break; - case 70: - case 75: - if (hasKind(node.parent, 210) || hasKind(node.parent, 209)) { - return getBreakOrContinueStatementOccurrences(node.parent); - } - break; - case 86: - if (hasKind(node.parent, 206) || - hasKind(node.parent, 207) || - hasKind(node.parent, 208)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 104: - case 79: - if (hasKind(node.parent, 205) || hasKind(node.parent, 204)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 121: - if (hasKind(node.parent, 148)) { - return getConstructorOccurrences(node.parent); - } - break; - case 123: - case 131: - if (hasKind(node.parent, 149) || hasKind(node.parent, 150)) { - return getGetAndSetOccurrences(node.parent); - } - break; - default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 200)) { - return getModifierOccurrences(node.kind, node.parent); - } - } - } - return undefined; - } - function aggregateOwnedThrowStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 215) { - statementAccumulator.push(node); - } - else if (node.kind === 216) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); - } - else { - aggregate(tryStatement.tryBlock); - } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); - } - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - function getThrowStatementOwner(throwStatement) { - var child = throwStatement; - while (child.parent) { - var parent_20 = child.parent; - if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256) { - return parent_20; - } - if (parent_20.kind === 216) { - var tryStatement = parent_20; - if (tryStatement.tryBlock === child && tryStatement.catchClause) { - return child; - } - } - child = parent_20; - } - return undefined; - } - function aggregateAllBreakAndContinueStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 210 || node.kind === 209) { - statementAccumulator.push(node); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - function ownsBreakOrContinueStatement(owner, statement) { - var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; - } - function getBreakOrContinueOwner(statement) { - for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) { - switch (node_1.kind) { - case 213: - if (statement.kind === 209) { - continue; - } - case 206: - case 207: - case 208: - case 205: - case 204: - if (!statement.label || isLabeledBy(node_1, statement.label.text)) { - return node_1; - } - break; - default: - if (ts.isFunctionLike(node_1)) { - return undefined; - } - break; - } - } - return undefined; - } - function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 221 || - container.kind === 192 || - (declaration.kind === 142 && hasKind(container, 148)))) { - return undefined; - } - } - else if (modifier === 113) { - if (!(container.kind === 221 || container.kind === 192)) { - return undefined; - } - } - else if (modifier === 82 || modifier === 122) { - if (!(container.kind === 226 || container.kind === 256)) { - return undefined; - } - } - else if (modifier === 115) { - if (!(container.kind === 221 || declaration.kind === 221)) { - return undefined; - } - } - else { - return undefined; - } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; - switch (container.kind) { - case 226: - case 256: - if (modifierFlag & 128) { - nodes = declaration.members.concat(declaration); - } - else { - nodes = container.statements; - } - break; - case 148: - nodes = container.parameters.concat(container.parent.members); - break; - case 221: - case 192: - nodes = container.members; - if (modifierFlag & 28) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 148 && member; - }); - if (constructor) { - nodes = nodes.concat(constructor.parameters); - } - } - else if (modifierFlag & 128) { - nodes = nodes.concat(container); - } - break; - default: - ts.Debug.fail("Invalid container kind."); - } - ts.forEach(nodes, function (node) { - if (node.modifiers && node.flags & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - function getFlagFromModifier(modifier) { - switch (modifier) { - case 112: - return 4; - case 110: - return 8; - case 111: - return 16; - case 113: - return 32; - case 82: - return 1; - case 122: - return 2; - case 115: - return 128; - default: - ts.Debug.fail(); - } - } - } - function pushKeywordIf(keywordList, token) { - var expected = []; - for (var _i = 2; _i < arguments.length; _i++) { - expected[_i - 2] = arguments[_i]; - } - if (token && ts.contains(expected, token.kind)) { - keywordList.push(token); - return true; - } - return false; - } - function getGetAndSetOccurrences(accessorDeclaration) { - var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 149); - tryPushAccessorKeyword(accessorDeclaration.symbol, 150); - return ts.map(keywords, getHighlightSpanForNode); - function tryPushAccessorKeyword(accessorSymbol, accessorKind) { - var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); - if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123, 131); }); - } - } - } - function getConstructorOccurrences(constructorDeclaration) { - var declarations = constructorDeclaration.symbol.getDeclarations(); - var keywords = []; - ts.forEach(declarations, function (declaration) { - ts.forEach(declaration.getChildren(), function (token) { - return pushKeywordIf(keywords, token, 121); - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getLoopBreakContinueOccurrences(loopNode) { - var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86, 104, 79)) { - if (loopNode.kind === 204) { - var loopTokens = loopNode.getChildren(); - for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104)) { - break; - } - } - } - } - var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70, 75); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { - var owner = getBreakOrContinueOwner(breakOrContinueStatement); - if (owner) { - switch (owner.kind) { - case 206: - case 207: - case 208: - case 204: - case 205: - return getLoopBreakContinueOccurrences(owner); - case 213: - return getSwitchCaseDefaultOccurrences(owner); - } - } - return undefined; - } - function getSwitchCaseDefaultOccurrences(switchStatement) { - var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96); - ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71, 77); - var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70); - } - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getTryCatchFinallyOccurrences(tryStatement) { - var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100); - if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72); - } - if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getThrowOccurrences(throwStatement) { - var owner = getThrowStatementOwner(throwStatement); - if (!owner) { - return undefined; - } - var keywords = []; - ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); - }); - if (ts.isFunctionBlock(owner)) { - ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); - }); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getReturnOccurrences(returnStatement) { - var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 199))) { - return undefined; - } - var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); - }); - ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getIfElseOccurrences(ifStatement) { - var keywords = []; - while (hasKind(ifStatement.parent, 203) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88); - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 203)) { - break; - } - ifStatement = ifStatement.elseStatement; - } - var result = []; - for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 && i < keywords.length - 1) { - var elseKeyword = keywords[i]; - var ifKeyword = keywords[i + 1]; - var shouldCombindElseAndIf = true; - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { - if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; - break; - } - } - if (shouldCombindElseAndIf) { - result.push({ - fileName: fileName, - textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: HighlightSpanKind.reference - }); - i++; - continue; - } - } - result.push(getHighlightSpanForNode(keywords[i])); - } - return result; - } - } + return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); } function getOccurrencesAtPositionCore(fileName, position) { synchronizeHostData(); @@ -47616,7 +59854,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, isDefinition: false }); } @@ -47624,24 +59862,13 @@ var ts; return result; } } - function convertReferences(referenceSymbols) { - if (!referenceSymbols) { - return undefined; - } - var referenceEntries = []; - for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { - var referenceSymbol = referenceSymbols_1[_i]; - ts.addRange(referenceEntries, referenceSymbol.references); - } - return referenceEntries; - } function findRenameLocations(fileName, position, findInStrings, findInComments) { var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, false, false); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function findReferences(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, false, false); @@ -47649,672 +59876,12 @@ var ts; } function findReferencedSymbols(fileName, position, findInStrings, findInComments) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position, true); - if (node === sourceFile) { - return undefined; - } - switch (node.kind) { - case 8: - if (!isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - break; - } - case 69: - case 97: - case 9: - return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); - } - return undefined; + return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function isThis(node) { - switch (node.kind) { - case 97: - return true; - case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; - default: - return false; - } - } - function getReferencedSymbolsForNode(node, sourceFiles, findInStrings, findInComments) { - var typeChecker = program.getTypeChecker(); - if (isLabelName(node)) { - if (isJumpStatementTarget(node)) { - var labelDefinition = getTargetLabel(node.parent, node.text); - return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; - } - else { - return getLabelReferencesInNode(node.parent, node); - } - } - if (isThis(node)) { - return getReferencesForThisKeyword(node, sourceFiles); - } - if (node.kind === 95) { - return getReferencesForSuperKeyword(node); - } - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol && node.kind === 9) { - return getReferencesForStringLiteral(node, sourceFiles); - } - if (!symbol) { - return undefined; - } - var declarations = symbol.declarations; - if (!declarations || !declarations.length) { - return undefined; - } - var result; - var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); - var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - var scope = getSymbolScope(symbol); - var symbolToIndex = []; - if (scope) { - result = []; - getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; - cancellationToken.throwIfCancellationRequested(); - var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { - result = result || []; - getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - } - } - return result; - function getDefinition(symbol) { - var info = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, node.getSourceFile(), getContainerNode(node), node); - var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } - return { - containerKind: "", - containerName: "", - name: name, - kind: info.symbolKind, - fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0) - }; - } - function getAliasSymbolForPropertyNameSymbol(symbol, location) { - if (symbol.flags & 8388608) { - var defaultImport = ts.getDeclarationOfKind(symbol, 231); - if (defaultImport) { - return typeChecker.getAliasedSymbol(symbol); - } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 || - declaration.kind === 238) ? declaration : undefined; }); - if (importOrExportSpecifier && - (!importOrExportSpecifier.propertyName || - importOrExportSpecifier.propertyName === location)) { - return importOrExportSpecifier.kind === 234 ? - typeChecker.getAliasedSymbol(symbol) : - typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); - } - } - return undefined; - } - function getPropertySymbolOfDestructuringAssignment(location) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - typeChecker.getPropertySymbolOfDestructuringAssignment(location); - } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); - return bindingElement && - bindingElement.parent.kind === 167 && - !bindingElement.propertyName; - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); - var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); - return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - } - return undefined; - } - function getInternedName(symbol, location, declarations) { - if (ts.isImportOrExportSpecifierName(location)) { - return location.getText(); - } - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - symbol = localExportDefaultSymbol || symbol; - return ts.stripQuotes(symbol.name); - } - function getSymbolScope(symbol) { - var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 || valueDeclaration.kind === 192)) { - return valueDeclaration; - } - if (symbol.flags & (4 | 8192)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8) ? d : undefined; }); - if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221); - } - } - if (symbol.flags & 8388608) { - return undefined; - } - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - return undefined; - } - if (symbol.parent || (symbol.flags & 268435456)) { - return undefined; - } - var scope; - var declarations = symbol.getDeclarations(); - if (declarations) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - var container = getContainerNode(declaration); - if (!container) { - return undefined; - } - if (scope && scope !== container) { - return undefined; - } - if (container.kind === 256 && !ts.isExternalModule(container)) { - return undefined; - } - scope = container; - } - } - return scope; - } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { - var positions = []; - if (!symbolName || !symbolName.length) { - return positions; - } - var text = sourceFile.text; - var sourceLength = text.length; - var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); - while (position >= 0) { - cancellationToken.throwIfCancellationRequested(); - if (position > end) - break; - var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2))) { - positions.push(position); - } - position = text.indexOf(symbolName, position + symbolNameLength + 1); - } - return positions; - } - function getLabelReferencesInNode(container, targetLabel) { - var references = []; - var sourceFile = container.getSourceFile(); - var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - return; - } - if (node === targetLabel || - (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = { - containerKind: "", - containerName: "", - fileName: targetLabel.getSourceFile().fileName, - kind: ScriptElementKind.label, - name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) - }; - return [{ definition: definition, references: references }]; - } - function isValidReferencePosition(node, searchSymbolName) { - if (node) { - switch (node.kind) { - case 69: - return node.getWidth() === searchSymbolName.length; - case 9: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isNameOfExternalModuleImportOrDeclaration(node)) { - return node.getWidth() === searchSymbolName.length + 2; - } - break; - case 8: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - return node.getWidth() === searchSymbolName.length; - } - break; - } - } - return false; - } - function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { - var sourceFile = container.getSourceFile(); - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0) { - var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); - referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); - } - } - }); - } - return; - function getReferencedSymbol(symbol) { - var symbolId = ts.getSymbolId(symbol); - var index = symbolToIndex[symbolId]; - if (index === undefined) { - index = result.length; - symbolToIndex[symbolId] = index; - result.push({ - definition: getDefinition(symbol), - references: [] - }); - } - return result[index]; - } - function isInNonReferenceComment(sourceFile, position) { - return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - } - function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, false); - if (!searchSpaceNode) { - return undefined; - } - var staticFlag = 32; - switch (searchSpaceNode.kind) { - case 145: - case 144: - case 147: - case 146: - case 148: - case 149: - case 150: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; - break; - default: - return undefined; - } - var references = []; - var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95) { - return; - } - var container = ts.getSuperContainer(node, false); - if (container && (32 & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = getDefinition(searchSpaceNode.symbol); - return [{ definition: definition, references: references }]; - } - function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { - var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); - var staticFlag = 32; - switch (searchSpaceNode.kind) { - case 147: - case 146: - if (ts.isObjectLiteralMethod(searchSpaceNode)) { - break; - } - case 145: - case 144: - case 148: - case 149: - case 150: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; - break; - case 256: - if (ts.isExternalModule(searchSpaceNode)) { - return undefined; - } - case 220: - case 179: - break; - default: - return undefined; - } - var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 256) { - ts.forEach(sourceFiles, function (sourceFile) { - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: "this", - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || !isThis(node)) { - return; - } - var container = ts.getThisContainer(node, false); - switch (searchSpaceNode.kind) { - case 179: - case 220: - if (searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 147: - case 146: - if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 192: - case 221: - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 32) === staticFlag) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 256: - if (container.kind === 256 && !ts.isExternalModule(container)) { - result.push(getReferenceEntryFromNode(node)); - } - break; - } - }); - } - } - function getReferencesForStringLiteral(node, sourceFiles) { - var typeChecker = program.getTypeChecker(); - var type = getStringLiteralTypeForNode(node, typeChecker); - if (!type) { - return undefined; - } - var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); - getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: type.text, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; - cancellationToken.throwIfCancellationRequested(); - var node_2 = ts.getTouchingWord(sourceFile, position); - if (!node_2 || node_2.kind !== 9) { - return; - } - var type_1 = getStringLiteralTypeForNode(node_2, typeChecker); - if (type_1 === searchType) { - references.push(getReferenceEntryFromNode(node_2)); - } - } - } - } - function populateSearchSymbolSet(symbol, location) { - var result = [symbol]; - var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254) { - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); - if (propertySymbol) { - result.push(propertySymbol); - } - } - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); - if (aliasSymbol) { - result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); - } - if (containingObjectLiteralElement) { - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); - }); - var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); - if (shorthandValueSymbol) { - result.push(shorthandValueSymbol); - } - } - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); - if (bindingElementPropertySymbol) { - result.push(bindingElementPropertySymbol); - } - ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, {}); - } - }); - return result; - } - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { - if (!symbol) { - return; - } - if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { - return; - } - if (symbol.flags & (32 | 64)) { - ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === 222) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = typeChecker.getTypeAtLocation(typeReference); - if (type) { - var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); - if (propertySymbol) { - result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); - } - previousIterationSymbolsCache[symbol.name] = symbol; - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); - } - } - } - } - function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation) { - if (searchSymbols.indexOf(referenceSymbol) >= 0) { - return referenceSymbol; - } - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); - if (aliasSymbol) { - return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation); - } - var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); - if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - }); - if (contextualSymbol) { - return contextualSymbol; - } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); - if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { - return propertySymbol; - } - } - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); - if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { - return bindingElementPropertySymbol; - } - return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { - if (searchSymbols.indexOf(rootSymbol) >= 0) { - return rootSymbol; - } - if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - var result_4 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, {}); - return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - } - return undefined; - }); - } - function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140) { - var nameExpression = node.name.expression; - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { - return nameExpression.text; - } - return undefined; - } - return node.name.text; - } - function getPropertySymbolsFromContextualType(node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol_1 = contextualType.getProperty(name); - if (symbol_1) { - result_5.push(symbol_1); - } - if (contextualType.flags & 16384) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; - } - function getIntersectingMeaningFromDeclarations(meaning, declarations) { - if (declarations) { - var lastIterationMeaning = void 0; - do { - lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; - var declarationMeaning = getMeaningFromDeclaration(declaration); - if (declarationMeaning & meaning) { - meaning |= declarationMeaning; - } - } - } while (meaning !== lastIterationMeaning); - } - return meaning; - } - } - function getReferenceEntryFromNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - if (node.kind === 9) { - start += 1; - end -= 1; - } - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) - }; - } - function isWriteAccess(node) { - if (node.kind === 69 && ts.isDeclarationName(node)) { - return true; - } - var parent = node.parent; - if (parent) { - if (parent.kind === 186 || parent.kind === 185) { - return true; - } - else if (parent.kind === 187 && parent.left === node) { - var operator = parent.operatorToken.kind; - return 56 <= operator && operator <= 68; - } - } - return false; - } - function getNavigateToItems(searchValue, maxResultCount) { + function getNavigateToItems(searchValue, maxResultCount, fileName) { synchronizeHostData(); - var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -48333,130 +59900,6 @@ var ts; emitSkipped: emitOutput.emitSkipped }; } - function getMeaningFromDeclaration(node) { - switch (node.kind) { - case 142: - case 218: - case 169: - case 145: - case 144: - case 253: - case 254: - case 255: - case 147: - case 146: - case 148: - case 149: - case 150: - case 220: - case 179: - case 180: - case 252: - return 1; - case 141: - case 222: - case 223: - case 159: - return 2; - case 221: - case 224: - return 1 | 2; - case 225: - if (ts.isAmbientModule(node)) { - return 4 | 1; - } - else if (ts.getModuleInstanceState(node) === 1) { - return 4 | 1; - } - else { - return 4; - } - case 233: - case 234: - case 229: - case 230: - case 235: - case 236: - return 1 | 2 | 4; - case 256: - return 4 | 1; - } - return 1 | 2 | 4; - } - function isTypeReference(node) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - return node.parent.kind === 155 || - (node.parent.kind === 194 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 && !ts.isExpression(node)) || - node.kind === 165; - } - function isNamespaceReference(node) { - return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); - } - function isPropertyAccessNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 172) { - while (root.parent && root.parent.kind === 172) { - root = root.parent; - } - isLastClause = root.name === node; - } - if (!isLastClause && root.parent.kind === 194 && root.parent.parent.kind === 251) { - var decl = root.parent.parent.parent; - return (decl.kind === 221 && root.parent.parent.token === 106) || - (decl.kind === 222 && root.parent.parent.token === 83); - } - return false; - } - function isQualifiedNameNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 139) { - while (root.parent && root.parent.kind === 139) { - root = root.parent; - } - isLastClause = root.right === node; - } - return root.parent.kind === 155 && !isLastClause; - } - function isInRightSideOfImport(node) { - while (node.parent.kind === 139) { - node = node.parent; - } - return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; - } - function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69); - if (node.parent.kind === 139 && - node.parent.right === node && - node.parent.parent.kind === 229) { - return 1 | 2 | 4; - } - return 4; - } - function getMeaningFromLocation(node) { - if (node.parent.kind === 235) { - return 1 | 2 | 4; - } - else if (isInRightSideOfImport(node)) { - return getMeaningFromRightHandSideOfImportEquals(node); - } - else if (ts.isDeclarationName(node)) { - return getMeaningFromDeclaration(node.parent); - } - else if (isTypeReference(node)) { - return 2; - } - else if (isNamespaceReference(node)) { - return 4; - } - else { - return 1; - } - } function getSignatureHelpItems(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -48465,6 +59908,9 @@ var ts; function getNonBoundSourceFile(fileName) { return syntaxTreeCache.getCurrentSourceFile(fileName); } + function getSourceFile(fileName) { + return getNonBoundSourceFile(fileName); + } function getNameOrDottedNameSpan(fileName, startPos, endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, startPos); @@ -48475,7 +59921,6 @@ var ts; case 172: case 139: case 9: - case 166: case 84: case 99: case 93: @@ -48489,10 +59934,10 @@ var ts; } var nodeForStartPos = node; while (true) { - if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { nodeForStartPos = nodeForStartPos.parent; } - else if (isNameOfModuleDeclaration(nodeForStartPos)) { + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { if (nodeForStartPos.parent.parent.kind === 225 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -48516,406 +59961,18 @@ var ts; return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { - return convertClassifications(getEncodedSemanticClassifications(fileName, span)); - } - function checkForClassificationCancellation(kind) { - switch (kind) { - case 225: - case 221: - case 222: - case 220: - cancellationToken.throwIfCancellationRequested(); - } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); - var result = []; - var classifiableNames = program.getClassifiableNames(); - processNode(sourceFile); - return { spans: result, endOfLineState: 0 }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448) === 0) { - return; - } - if (flags & 32) { - return 11; - } - else if (flags & 384) { - return 12; - } - else if (flags & 524288) { - return 16; - } - else if (meaningAtPosition & 2) { - if (flags & 64) { - return 13; - } - else if (flags & 262144) { - return 15; - } - } - else if (flags & 1536) { - if (meaningAtPosition & 4 || - (meaningAtPosition & 1 && hasValueSideModule(symbol))) { - return 14; - } - } - return undefined; - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 && - ts.getModuleInstanceState(declaration) === 1; - }); - } - } - function processNode(node) { - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(kind); - if (kind === 69 && !ts.nodeIsMissing(node)) { - var identifier = node; - if (classifiableNames[identifier.text]) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } - } - } - function getClassificationTypeName(type) { - switch (type) { - case 1: return ClassificationTypeNames.comment; - case 2: return ClassificationTypeNames.identifier; - case 3: return ClassificationTypeNames.keyword; - case 4: return ClassificationTypeNames.numericLiteral; - case 5: return ClassificationTypeNames.operator; - case 6: return ClassificationTypeNames.stringLiteral; - case 8: return ClassificationTypeNames.whiteSpace; - case 9: return ClassificationTypeNames.text; - case 10: return ClassificationTypeNames.punctuation; - case 11: return ClassificationTypeNames.className; - case 12: return ClassificationTypeNames.enumName; - case 13: return ClassificationTypeNames.interfaceName; - case 14: return ClassificationTypeNames.moduleName; - case 15: return ClassificationTypeNames.typeParameterName; - case 16: return ClassificationTypeNames.typeAliasName; - case 17: return ClassificationTypeNames.parameterName; - case 18: return ClassificationTypeNames.docCommentTagName; - case 19: return ClassificationTypeNames.jsxOpenTagName; - case 20: return ClassificationTypeNames.jsxCloseTagName; - case 21: return ClassificationTypeNames.jsxSelfClosingTagName; - case 22: return ClassificationTypeNames.jsxAttribute; - case 23: return ClassificationTypeNames.jsxText; - case 24: return ClassificationTypeNames.jsxAttributeStringLiteralValue; - } - } - function convertClassifications(classifications) { - ts.Debug.assert(classifications.spans.length % 3 === 0); - var dense = classifications.spans; - var result = []; - for (var i = 0, n = dense.length; i < n; i += 3) { - result.push({ - textSpan: ts.createTextSpan(dense[i], dense[i + 1]), - classificationType: getClassificationTypeName(dense[i + 2]) - }); - } - return result; + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getSyntacticClassifications(fileName, span) { - return convertClassifications(getEncodedSyntacticClassifications(fileName, span)); + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getEncodedSyntacticClassifications(fileName, span) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var spanStart = span.start; - var spanLength = span.length; - var triviaScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); - var result = []; - processElement(sourceFile); - return { spans: result, endOfLineState: 0 }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifyLeadingTriviaAndGetTokenStart(token) { - triviaScanner.setTextPos(token.pos); - while (true) { - var start = triviaScanner.getTextPos(); - if (!ts.couldStartTrivia(sourceFile.text, start)) { - return start; - } - var kind = triviaScanner.scan(); - var end = triviaScanner.getTextPos(); - var width = end - start; - if (!ts.isTrivia(kind)) { - return start; - } - if (kind === 4 || kind === 5) { - continue; - } - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - if (ch === 60 || ch === 62) { - pushClassification(start, width, 1); - continue; - } - ts.Debug.assert(ch === 61); - classifyDisabledMergeCode(text, start, end); - } - } - } - function classifyComment(token, kind, start, width) { - if (kind === 3) { - var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); - if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { - docCommentAndDiagnostics.jsDocComment.parent = token; - classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); - return; - } - } - pushCommentRange(start, width); - } - function pushCommentRange(start, width) { - pushClassification(start, width, 1); - } - function classifyJSDocComment(docComment) { - var pos = docComment.pos; - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - if (tag.pos !== pos) { - pushCommentRange(pos, tag.pos - pos); - } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10); - pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); - pos = tag.tagName.end; - switch (tag.kind) { - case 275: - processJSDocParameterTag(tag); - break; - case 278: - processJSDocTemplateTag(tag); - break; - case 277: - processElement(tag.typeExpression); - break; - case 276: - processElement(tag.typeExpression); - break; - } - pos = tag.end; - } - if (pos !== docComment.end) { - pushCommentRange(pos, docComment.end - pos); - } - return; - function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17); - pos = tag.preParameterName.end; - } - if (tag.typeExpression) { - pushCommentRange(pos, tag.typeExpression.pos - pos); - processElement(tag.typeExpression); - pos = tag.typeExpression.end; - } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17); - pos = tag.postParameterName.end; - } - } - } - function processJSDocTemplateTag(tag) { - for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { - var child = _a[_i]; - processElement(child); - } - } - function classifyDisabledMergeCode(text, start, end) { - var i; - for (i = start; i < end; i++) { - if (ts.isLineBreak(text.charCodeAt(i))) { - break; - } - } - pushClassification(start, i - start, 1); - mergeConflictScanner.setTextPos(i); - while (mergeConflictScanner.getTextPos() < end) { - classifyDisabledCodeToken(); - } - } - function classifyDisabledCodeToken() { - var start = mergeConflictScanner.getTextPos(); - var tokenKind = mergeConflictScanner.scan(); - var end = mergeConflictScanner.getTextPos(); - var type = classifyTokenType(tokenKind); - if (type) { - pushClassification(start, end - start, type); - } - } - function tryClassifyNode(node) { - if (ts.nodeIsMissing(node)) { - return true; - } - var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 && classifiedElementName === undefined) { - return false; - } - var tokenStart = node.kind === 244 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); - var tokenWidth = node.end - tokenStart; - ts.Debug.assert(tokenWidth >= 0); - if (tokenWidth > 0) { - var type = classifiedElementName || classifyTokenType(node.kind, node); - if (type) { - pushClassification(tokenStart, tokenWidth, type); - } - } - return true; - } - function tryClassifyJsxElementName(token) { - switch (token.parent && token.parent.kind) { - case 243: - if (token.parent.tagName === token) { - return 19; - } - break; - case 245: - if (token.parent.tagName === token) { - return 20; - } - break; - case 242: - if (token.parent.tagName === token) { - return 21; - } - break; - case 246: - if (token.parent.name === token) { - return 22; - } - break; - } - return undefined; - } - function classifyTokenType(tokenKind, token) { - if (ts.isKeyword(tokenKind)) { - return 3; - } - if (tokenKind === 25 || tokenKind === 27) { - if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { - return 10; - } - } - if (ts.isPunctuation(tokenKind)) { - if (token) { - if (tokenKind === 56) { - if (token.parent.kind === 218 || - token.parent.kind === 145 || - token.parent.kind === 142 || - token.parent.kind === 246) { - return 5; - } - } - if (token.parent.kind === 187 || - token.parent.kind === 185 || - token.parent.kind === 186 || - token.parent.kind === 188) { - return 5; - } - } - return 10; - } - else if (tokenKind === 8) { - return 4; - } - else if (tokenKind === 9 || tokenKind === 166) { - return token.parent.kind === 246 ? 24 : 6; - } - else if (tokenKind === 10) { - return 6; - } - else if (ts.isTemplateLiteralKind(tokenKind)) { - return 6; - } - else if (tokenKind === 244) { - return 23; - } - else if (tokenKind === 69) { - if (token) { - switch (token.parent.kind) { - case 221: - if (token.parent.name === token) { - return 11; - } - return; - case 141: - if (token.parent.name === token) { - return 15; - } - return; - case 222: - if (token.parent.name === token) { - return 13; - } - return; - case 224: - if (token.parent.name === token) { - return 12; - } - return; - case 225: - if (token.parent.name === token) { - return 14; - } - return; - case 142: - if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; - } - return; - } - } - return 2; - } - } - function processElement(element) { - if (!element) { - return; - } - if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { - checkForClassificationCancellation(element.kind); - var children = element.getChildren(sourceFile); - for (var i = 0, n = children.length; i < n; i++) { - var child = children[i]; - if (!tryClassifyNode(child)) { - processElement(child); - } - } - } - } + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getOutliningSpans(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); @@ -48962,12 +60019,12 @@ var ts; } } function getIndentationAtPosition(fileName, position, editorOptions) { - var start = new Date().getTime(); + var start = ts.timestamp(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); - start = new Date().getTime(); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); - log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { @@ -48992,56 +60049,7 @@ var ts; return []; } function getDocCommentTemplateAtPosition(fileName, position) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { - return undefined; - } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); - var tokenStart = tokenAtPos.getStart(); - if (!tokenAtPos || tokenStart < position) { - return undefined; - } - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 220: - case 147: - case 148: - case 221: - case 200: - break findOwner; - case 256: - return undefined; - case 225: - if (commentOwner.parent.kind === 225) { - return undefined; - } - break findOwner; - } - } - if (!commentOwner || commentOwner.getStart() < position) { - return undefined; - } - var parameters = getParametersForJsDocOwningNode(commentOwner); - var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); - var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; - var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); - var newLine = ts.getNewLineOrDefaultFromHost(host); - var docParams = ""; - for (var i = 0, numParams = parameters.length; i < numParams; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 69 ? - currentName.text : - "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; - } - var preamble = "/**" + newLine + - indentationStr + " * "; - var result = preamble + newLine + - docParams + - indentationStr + " */" + - (tokenStart === position ? newLine + indentationStr : ""); - return { newText: result, caretOffset: preamble.length }; + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { if (openingBrace === 60) { @@ -49059,38 +60067,6 @@ var ts; } return true; } - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 200) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); - } - } - return emptyArray; - } - function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178) { - rightHandSide = rightHandSide.expression; - } - switch (rightHandSide.kind) { - case 179: - case 180: - return rightHandSide.parameters; - case 192: - for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148) { - return member.parameters; - } - } - break; - } - return emptyArray; - } function getTodoComments(fileName, descriptors) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -49107,7 +60083,7 @@ var ts; var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInsideComment(sourceFile, token, matchPosition)) { continue; } var descriptor = undefined; @@ -49150,101 +60126,10 @@ var ts; (char >= 48 && char <= 57); } } - function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 ? node.parent : node; - var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256) { - return type; - } - return undefined; - } function getRenameInfo(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); - var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); - var node = ts.getTouchingWord(sourceFile, position, true); - if (node) { - if (node.kind === 69 || - node.kind === 9 || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isThis(node)) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var declarations = symbol.getDeclarations(); - if (declarations && declarations.length > 0) { - if (ts.forEach(declarations, isDefinedInLibraryFile)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - var kind = getSymbolKind(symbol, node); - if (kind) { - return { - canRename: true, - kind: kind, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), - kindModifiers: getSymbolModifiers(symbol), - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - else if (node.kind === 9) { - var type = getStringLiteralTypeForNode(node, typeChecker); - if (type) { - if (isDefinedInLibraryFile(node)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - else { - var displayName = ts.stripQuotes(type.text); - return { - canRename: true, - kind: ScriptElementKind.variableElement, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: displayName, - kindModifiers: ScriptElementKindModifier.none, - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - } - } - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); - function getRenameInfoError(localizedErrorMessage) { - return { - canRename: false, - localizedErrorMessage: localizedErrorMessage, - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; - } - function isDefinedInLibraryFile(declaration) { - if (defaultLibFileName) { - var sourceFile_2 = declaration.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (canonicalName === canonicalDefaultLibName) { - return true; - } - } - return false; - } - function createTriggerSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var width = node.getWidth(sourceFile); - if (node.kind === 9) { - start += 1; - width -= 2; - } - return ts.createTextSpan(start, width); - } + return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } return { dispose: dispose, @@ -49258,9 +60143,11 @@ var ts; getEncodedSemanticClassifications: getEncodedSemanticClassifications, getCompletionsAtPosition: getCompletionsAtPosition, getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, findReferences: findReferences, @@ -49283,6 +60170,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, + getSourceFile: getSourceFile, getProgram: getProgram }; } @@ -49295,7 +60183,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -49329,340 +60217,6 @@ var ts; node.parent.kind === 173 && node.parent.argumentExpression === node; } - function createClassifier() { - var scanner = ts.createScanner(2, false); - var noRegexTable = []; - noRegexTable[69] = true; - noRegexTable[9] = true; - noRegexTable[8] = true; - noRegexTable[10] = true; - noRegexTable[97] = true; - noRegexTable[41] = true; - noRegexTable[42] = true; - noRegexTable[18] = true; - noRegexTable[20] = true; - noRegexTable[16] = true; - noRegexTable[99] = true; - noRegexTable[84] = true; - var templateStack = []; - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 || - keyword2 === 131 || - keyword2 === 121 || - keyword2 === 113) { - return true; - } - return false; - } - return true; - } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0, n = dense.length; i < n; i += 3) { - var start = dense[i]; - var length_3 = dense[i + 1]; - var type = dense[i + 2]; - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); - } - } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1: return TokenClass.Comment; - case 3: return TokenClass.Keyword; - case 4: return TokenClass.NumberLiteral; - case 5: return TokenClass.Operator; - case 6: return TokenClass.StringLiteral; - case 8: return TokenClass.Whitespace; - case 10: return TokenClass.Punctuation; - case 2: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 9: - case 17: - default: - return TokenClass.Identifier; - } - } - function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); - } - function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; - var token = 0; - var lastNonTriviaToken = 0; - while (templateStack.length > 0) { - templateStack.pop(); - } - switch (lexState) { - case 3: - text = "\"\\\n" + text; - offset = 3; - break; - case 2: - text = "'\\\n" + text; - offset = 3; - break; - case 1: - text = "/*\n" + text; - offset = 3; - break; - case 4: - text = "`\n" + text; - offset = 2; - break; - case 5: - text = "}\n" + text; - offset = 2; - case 6: - templateStack.push(12); - break; - } - scanner.setText(text); - var result = { - endOfLineState: 0, - spans: [] - }; - var angleBracketStack = 0; - do { - token = scanner.scan(); - if (!ts.isTrivia(token)) { - if ((token === 39 || token === 61) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10) { - token = 10; - } - } - else if (lastNonTriviaToken === 21 && isKeyword(token)) { - token = 69; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - token = 69; - } - else if (lastNonTriviaToken === 69 && - token === 25) { - angleBracketStack++; - } - else if (token === 27 && angleBracketStack > 0) { - angleBracketStack--; - } - else if (token === 117 || - token === 132 || - token === 130 || - token === 120 || - token === 133) { - if (angleBracketStack > 0 && !syntacticClassifierAbsent) { - token = 69; - } - } - else if (token === 12) { - templateStack.push(token); - } - else if (token === 15) { - if (templateStack.length > 0) { - templateStack.push(token); - } - } - else if (token === 16) { - if (templateStack.length > 0) { - var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12) { - token = scanner.reScanTemplateToken(); - if (token === 14) { - templateStack.pop(); - } - else { - ts.Debug.assert(token === 13, "Should have been a template middle. Was " + token); - } - } - else { - ts.Debug.assert(lastTemplateStackToken === 15, "Should have been an open brace. Was: " + token); - templateStack.pop(); - } - } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9 || token === 166) { - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92) { - numBackslashes++; - } - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 - ? 3 - : 2; - } - } - } - else if (token === 3) { - if (scanner.isUnterminated()) { - result.endOfLineState = 1; - } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 14) { - result.endOfLineState = 5; - } - else if (token === 11) { - result.endOfLineState = 4; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } - } - } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12) { - result.endOfLineState = 6; - } - } - } - function addResult(start, end, classification) { - if (classification === 8) { - return; - } - if (start === 0 && offset > 0) { - start += offset; - } - start -= offset; - end -= offset; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); - } - } - } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 37: - case 39: - case 40: - case 35: - case 36: - case 43: - case 44: - case 45: - case 25: - case 27: - case 28: - case 29: - case 91: - case 90: - case 116: - case 30: - case 31: - case 32: - case 33: - case 46: - case 48: - case 47: - case 51: - case 52: - case 67: - case 66: - case 68: - case 63: - case 64: - case 65: - case 57: - case 58: - case 59: - case 61: - case 62: - case 56: - case 24: - return true; - default: - return false; - } - } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 35: - case 36: - case 50: - case 49: - case 41: - case 42: - return true; - default: - return false; - } - } - function isKeyword(token) { - return token >= 70 && token <= 138; - } - function classFromKind(token) { - if (isKeyword(token)) { - return 3; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5; - } - else if (token >= 15 && token <= 68) { - return 10; - } - switch (token) { - case 8: - return 4; - case 9: - case 166: - return 6; - case 10: - return 7; - case 7: - case 3: - case 2: - return 1; - case 5: - case 4: - return 8; - case 69: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6; - } - return 2; - } - } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; - } - ts.createClassifier = createClassifier; function getDefaultLibFilePath(options) { if (typeof __dirname !== "undefined") { return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); @@ -49671,13 +60225,7 @@ var ts; } ts.getDefaultLibFilePath = getDefaultLibFilePath; function initializeServices() { - ts.objectAllocator = { - getNodeConstructor: function () { return NodeObject; }, - getSourceFileConstructor: function () { return SourceFileObject; }, - getSymbolConstructor: function () { return SymbolObject; }, - getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } - }; + ts.objectAllocator = getServicesObjectAllocator(); } initializeServices(); })(ts || (ts = {})); @@ -49775,6 +60323,7 @@ var ts; CommandNames.Formatonkey = "formatonkey"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; + CommandNames.Implementation = "implementation"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; @@ -49806,7 +60355,7 @@ var ts; this.hrtime = hrtime; this.logger = logger; this.changeSeq = 0; - this.handlers = (_a = {}, + this.handlers = ts.createMap((_a = {}, _a[CommandNames.Exit] = function () { _this.exit(); return { responseRequired: false }; @@ -49819,6 +60368,10 @@ var ts; var defArgs = request.arguments; return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, + _a[CommandNames.Implementation] = function (request) { + var implArgs = request.arguments; + return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + }, _a[CommandNames.References] = function (request) { var defArgs = request.arguments; return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; @@ -49915,7 +60468,7 @@ var ts; }, _a[CommandNames.Navto] = function (request) { var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true }; + return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; }, _a[CommandNames.Brace] = function (request) { var braceArguments = request.arguments; @@ -49941,19 +60494,24 @@ var ts; _this.reloadProjects(); return { responseRequired: false }; }, - _a - ); + _a)); this.projectService = - new server.ProjectService(host, logger, function (eventName, project, fileName) { - _this.handleEvent(eventName, project, fileName); + new server.ProjectService(host, logger, function (event) { + _this.handleEvent(event); }); var _a; } - Session.prototype.handleEvent = function (eventName, project, fileName) { + Session.prototype.handleEvent = function (event) { var _this = this; - if (eventName == "context") { - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); - this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); + switch (event.eventName) { + case "context": + var _a = event.data, project = _a.project, fileName = _a.fileName; + this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); + break; + case "configFileDiag": + var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; + this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); } }; Session.prototype.logError = function (err, cmd) { @@ -50133,6 +60691,23 @@ var ts; end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) }); }); }; + Session.prototype.getImplementation = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + if (!implementations) { + return undefined; + } + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), + end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) + }); }); + }; Session.prototype.getOccurrences = function (line, offset, fileName) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); @@ -50469,7 +61044,15 @@ var ts; } return completions.entries.reduce(function (result, entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - result.push(entry); + var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = undefined; + if (replacementSpan) { + convertedSpan = { + start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), + end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) + }; + } + result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } return result; }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); @@ -50603,7 +61186,7 @@ var ts; } return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { + Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); @@ -50613,7 +61196,7 @@ var ts; } var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); + var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); if (!navItems) { return []; } @@ -50717,7 +61300,7 @@ var ts; return { response: response, responseRequired: true }; }; Session.prototype.addProtocolHandler = function (command, handler) { - if (this.handlers[command]) { + if (command in this.handlers) { throw new Error("Protocol handler already exists for command \"" + command + "\""); } this.handlers[command] = handler; @@ -50793,7 +61376,6 @@ var ts; if (isOpen === void 0) { isOpen = false; } this.host = host; this.fileName = fileName; - this.content = content; this.isOpen = isOpen; this.children = []; this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); @@ -50849,25 +61431,28 @@ var ts; readFile: function (fileName) { return _this.host.readFile(fileName); }, directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } }; + if (this.host.realpath) { + this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; + } } LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); var currentResolutionsInFile = cache.get(path); - var newResolutions = {}; + var newResolutions = ts.createMap(); var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_43 = names_2[_i]; - var resolution = ts.lookUp(newResolutions, name_43); + for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { + var name_53 = names_3[_i]; + var resolution = newResolutions[name_53]; if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } else { - resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); + resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); resolution.lastCheckTime = Date.now(); - newResolutions[name_43] = resolution; + newResolutions[name_53] = resolution; } } ts.Debug.assert(resolution !== undefined); @@ -50966,7 +61551,7 @@ var ts; LSHost.prototype.removeRoot = function (info) { if (this.filenameToScript.contains(info.path)) { this.filenameToScript.remove(info.path); - this.roots = copyListRemovingItem(info, this.roots); + ts.unorderedRemoveItem(this.roots, info); this.resolvedModuleNames.remove(info.path); this.resolvedTypeReferenceDirectives.remove(info.path); } @@ -50992,10 +61577,6 @@ var ts; } throw new Error("No script with name '" + filename + "'"); }; - LSHost.prototype.resolvePath = function (path) { - var result = this.host.resolvePath(path); - return result; - }; LSHost.prototype.fileExists = function (path) { var result = this.host.fileExists(path); return result; @@ -51006,6 +61587,12 @@ var ts; LSHost.prototype.getDirectories = function (path) { return this.host.getDirectories(path); }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.readFile = function (path, encoding) { + return this.host.readFile(path, encoding); + }; LSHost.prototype.lineToTextSpan = function (filename, line) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); @@ -51048,7 +61635,7 @@ var ts; this.projectOptions = projectOptions; this.languageServiceDiabled = languageServiceDiabled; this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = {}; + this.filenameToSourceFile = ts.createMap(); this.updateGraphSeq = 0; this.openRefCount = 0; if (projectOptions && projectOptions.files) { @@ -51132,7 +61719,7 @@ var ts; if (this.languageServiceDiabled) { return; } - this.filenameToSourceFile = {}; + this.filenameToSourceFile = ts.createMap(); var sourceFiles = this.program.getSourceFiles(); for (var i = 0, len = sourceFiles.length; i < len; i++) { var normFilename = ts.normalizePath(sourceFiles[i].fileName); @@ -51177,7 +61764,7 @@ var ts; } } var strBuilder = ""; - ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); + ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); return strBuilder; }; Project.prototype.setProjectOptions = function (projectOptions) { @@ -51192,15 +61779,6 @@ var ts; return Project; }()); server.Project = Project; - function copyListRemovingItem(item, list) { - var copiedList = []; - for (var i = 0, len = list.length; i < len; i++) { - if (list[i] != item) { - copiedList.push(list[i]); - } - } - return copiedList; - } function combineProjectOutput(projects, action, comparer, areEqual) { var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; @@ -51211,15 +61789,15 @@ var ts; this.host = host; this.psLogger = psLogger; this.eventHandler = eventHandler; - this.filenameToScriptInfo = {}; + this.filenameToScriptInfo = ts.createMap(); this.openFileRoots = []; this.inferredProjects = []; this.configuredProjects = []; this.openFilesReferenced = []; this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = {}; - this.directoryWatchersRefCount = {}; - this.timerForDetectingProjectFileListChanges = {}; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + this.timerForDetectingProjectFileListChanges = ts.createMap(); this.addDefaultHostConfiguration(); } ProjectService.prototype.addDefaultHostConfiguration = function () { @@ -51267,7 +61845,8 @@ var ts; }; ProjectService.prototype.handleProjectFileListChanges = function (project) { var _this = this; - var projectOptions = this.configFileToProjectOptions(project.projectFilename).projectOptions; + var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; + this.reportConfigFileDiagnostics(project.projectFilename, errors); var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { @@ -51275,14 +61854,26 @@ var ts; this.updateProjectStructure(); } }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (diagnostics && diagnostics.length > 0) { + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } + }); + } + }; ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { var _this = this; - if (ts.getBaseFileName(fileName) != "tsconfig.json") { + if (ts.getBaseFileName(fileName) !== "tsconfig.json") { this.log(fileName + " is not tsconfig.json"); return; } this.log("Detected newly added tsconfig file: " + fileName); - var projectOptions = this.configFileToProjectOptions(fileName).projectOptions; + var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; + this.reportConfigFileDiagnostics(fileName, errors); + if (!projectOptions) { + return; + } var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { @@ -51299,8 +61890,11 @@ var ts; }; ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { this.log("Config file changed: " + project.projectFilename); - this.updateConfiguredProject(project); + var configFileErrors = this.updateConfiguredProject(project); this.updateProjectStructure(); + if (configFileErrors && configFileErrors.length > 0) { + this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); + } }; ProjectService.prototype.log = function (msg, type) { if (type === void 0) { type = "Err"; } @@ -51370,13 +61964,13 @@ var ts; for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { var openFile = this.openFileRoots[j]; if (this.eventHandler) { - this.eventHandler("context", openFile.defaultProject, openFile.fileName); + this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); } } for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { var openFile = this.openFilesReferenced[j]; if (this.eventHandler) { - this.eventHandler("context", openFile.defaultProject, openFile.fileName); + this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); } } } @@ -51396,9 +61990,9 @@ var ts; if (project.isConfiguredProject()) { project.projectFileWatcher.close(); project.directoryWatcher.close(); - ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); delete project.directoriesWatchedForWildcards; - this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); + ts.unorderedRemoveItem(this.configuredProjects, project); } else { for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { @@ -51410,7 +62004,7 @@ var ts; delete project.projectService.directoryWatchersForTsconfig[directory]; } } - this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); + ts.unorderedRemoveItem(this.inferredProjects, project); } var fileNames = project.getFileNames(); for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { @@ -51509,7 +62103,7 @@ var ts; } } else { - this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + ts.unorderedRemoveItem(this.openFilesReferenced, info); } info.close(); }; @@ -51604,12 +62198,12 @@ var ts; }; ProjectService.prototype.getScriptInfo = function (filename) { filename = ts.normalizePath(filename); - return ts.lookUp(this.filenameToScriptInfo, filename); + return this.filenameToScriptInfo[filename]; }; ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { var _this = this; fileName = ts.normalizePath(fileName); - var info = ts.lookUp(this.filenameToScriptInfo, fileName); + var info = this.filenameToScriptInfo[fileName]; if (!info) { var content = void 0; if (this.host.fileExists(fileName)) { @@ -51674,7 +62268,7 @@ var ts; var project = this.findConfiguredProjectByConfigFile(configFileName); if (!project) { var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.success) { + if (!configResult.project) { return { configFileName: configFileName, configFileErrors: configResult.errors }; } else { @@ -51688,14 +62282,15 @@ var ts; else { this.updateConfiguredProject(project); } + return { configFileName: configFileName }; } else { this.log("No config files found."); } - return configFileName ? { configFileName: configFileName } : {}; + return {}; }; ProjectService.prototype.closeClientFile = function (filename) { - var info = ts.lookUp(this.filenameToScriptInfo, filename); + var info = this.filenameToScriptInfo[filename]; if (info) { this.closeOpenFile(info); info.isOpen = false; @@ -51703,13 +62298,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + var scriptInfo = this.filenameToScriptInfo[filename]; if (scriptInfo) { return scriptInfo.defaultProject; } }; ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + var scriptInfo = this.filenameToScriptInfo[filename]; if (scriptInfo) { this.psLogger.startGroup(); this.psLogger.info("Projects for " + filename); @@ -51773,30 +62368,25 @@ var ts; }; ProjectService.prototype.configFileToProjectOptions = function (configFilename) { configFilename = ts.normalizePath(configFilename); + var errors = []; var dirPath = ts.getDirectoryPath(configFilename); var contents = this.host.readFile(configFilename); - var rawConfig = ts.parseConfigFileTextToJson(configFilename, contents); - if (rawConfig.error) { - return { succeeded: false, errors: [rawConfig.error] }; + var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; + errors = ts.concatenate(errors, diagnostics); + var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); + errors = ts.concatenate(errors, parsedCommandLine.errors); + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { errors: errors }; } else { - var parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath, {}, configFilename); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { - return { succeeded: false, errors: parsedCommandLine.errors }; - } - else if (parsedCommandLine.fileNames.length === 0) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename); - return { succeeded: false, errors: [error] }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { succeeded: true, projectOptions: projectOptions }; - } + var projectOptions = { + files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, + compilerOptions: parsedCommandLine.options + }; + return { projectOptions: projectOptions, errors: errors }; } }; ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { @@ -51818,45 +62408,44 @@ var ts; }; ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { var _this = this; - var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; - if (!succeeded) { - return { success: false, errors: errors }; + var parseConfigFileResult = this.configFileToProjectOptions(configFilename); + var errors = parseConfigFileResult.errors; + if (!parseConfigFileResult.projectOptions) { + return { errors: errors }; } - else { - if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { - if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - var project_1 = this.createProject(configFilename, projectOptions, true); - project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - return { success: true, project: project_1 }; - } + var projectOptions = parseConfigFileResult.projectOptions; + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { project: project_1, errors: errors }; } - var project_2 = this.createProject(configFilename, projectOptions); - var errors_1; - for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { - var rootFilename = _b[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project_2.addRoot(info); - } - else { - (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project_2.finishGraph(); - project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); - var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath_1); - project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); - project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); - } - return watchers; - }, {}); - return { success: true, project: project_2, errors: errors_1 }; } + var project = this.createProject(configFilename, projectOptions); + for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { + var rootFilename = _a[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, clientFileName == rootFilename); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); + } + } + project.finishGraph(); + project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); + var configDirectoryPath = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath); + project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive); + } + return watchers; + }, {}); + return { project: project, errors: errors }; }; ProjectService.prototype.updateConfiguredProject = function (project) { var _this = this; @@ -51865,22 +62454,22 @@ var ts; this.removeProject(project); } else { - var _a = this.configFileToProjectOptions(project.projectFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; - if (!succeeded) { + var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; + if (!projectOptions) { return errors; } else { if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { project.setProjectOptions(projectOptions); if (project.languageServiceDiabled) { - return; + return errors; } project.disableLanguageService(); if (project.directoryWatcher) { project.directoryWatcher.close(); project.directoryWatcher = undefined; } - return; + return errors; } if (project.languageServiceDiabled) { project.setProjectOptions(projectOptions); @@ -51894,7 +62483,7 @@ var ts; } } project.finishGraph(); - return; + return errors; } var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); @@ -51916,13 +62505,13 @@ var ts; else { if (info.isOpen) { if (this.openFileRoots.indexOf(info) >= 0) { - this.openFileRoots = copyListRemovingItem(info, this.openFileRoots); + ts.unorderedRemoveItem(this.openFileRoots, info); if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { this.removeProject(info.defaultProject); } } if (this.openFilesReferenced.indexOf(info) >= 0) { - this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + ts.unorderedRemoveItem(this.openFilesReferenced, info); } this.openFileRootsConfigured.push(info); info.defaultProject = project; @@ -51933,6 +62522,7 @@ var ts; project.setProjectOptions(projectOptions); project.finishGraph(); } + return errors; } }; ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { @@ -51983,8 +62573,10 @@ var ts; InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + InsertSpaceAfterTypeAssertion: false, PlaceOpenBraceOnNewLineForFunctions: false, PlaceOpenBraceOnNewLineForControlBlocks: false }); @@ -52307,11 +62899,11 @@ var ts; snap.index.load(lm.lines); return svc; }; - ScriptVersionCache.changeNumberThreshold = 8; - ScriptVersionCache.changeLengthThreshold = 256; - ScriptVersionCache.maxVersions = 8; return ScriptVersionCache; }()); + ScriptVersionCache.changeNumberThreshold = 8; + ScriptVersionCache.changeLengthThreshold = 256; + ScriptVersionCache.maxVersions = 8; server.ScriptVersionCache = ScriptVersionCache; var LineIndexSnapshot = (function () { function LineIndexSnapshot(version, cache) { @@ -52419,7 +63011,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - this.done = true; + walkFns.done = true; } } }; @@ -52835,7 +63427,7 @@ var ts; server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = this; +var debugObjectHost = new Function("return this")(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -52879,7 +63471,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.lookUp(resolutionsInFile, name); + var result = ts.getProperty(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -52890,7 +63482,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -52963,11 +63555,21 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return this.shimHost.getDirectories(path); + return JSON.parse(this.shimHost.getDirectories(path)); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -52977,7 +63579,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = Date.now(); + var time = ts.timestamp(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { this.lastCancellationCheckTime = time; @@ -53027,6 +63629,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -53034,11 +63639,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = Date.now(); + start = ts.timestamp(); } var result = action(); if (logPerformance) { - var end = Date.now(); + var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -53188,6 +63793,10 @@ var ts; var _this = this; return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); @@ -53264,9 +63873,9 @@ var ts; var _this = this; return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; @@ -53365,6 +63974,13 @@ var ts; }; }); }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -53488,4 +64104,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "1.9"; +var toolsVersion = "2.1"; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index c322ba1dd0c..9116a629d6d 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -14,9 +14,12 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - interface Map { + interface MapLike { [index: string]: T; } + interface Map extends MapLike { + __mapBrand: any; + } type Path = string & { __pathBrand: any; }; @@ -199,7 +202,7 @@ declare namespace ts { IntersectionType = 163, ParenthesizedType = 164, ThisType = 165, - StringLiteralType = 166, + LiteralType = 166, ObjectBindingPattern = 167, ArrayBindingPattern = 168, BindingElement = 169, @@ -315,10 +318,18 @@ declare namespace ts { JSDocTypedefTag = 279, JSDocPropertyTag = 280, JSDocTypeLiteral = 281, - SyntaxList = 282, - Count = 283, + JSDocLiteralType = 282, + JSDocNullKeyword = 283, + JSDocUndefinedKeyword = 284, + JSDocNeverKeyword = 285, + SyntaxList = 286, + NotEmittedStatement = 287, + PartiallyEmittedExpression = 288, + Count = 289, FirstAssignment = 56, LastAssignment = 68, + FirstCompoundAssignment = 57, + LastCompoundAssignment = 68, FirstReservedWord = 70, LastReservedWord = 105, FirstKeyword = 70, @@ -341,11 +352,44 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 139, FirstJSDocNode = 257, - LastJSDocNode = 281, + LastJSDocNode = 282, FirstJSDocTagNode = 273, - LastJSDocTagNode = 281, + LastJSDocTagNode = 285, } enum NodeFlags { + None = 0, + Let = 1, + Const = 2, + NestedNamespace = 4, + Synthesized = 8, + Namespace = 16, + ExportContext = 32, + ContainsThis = 64, + HasImplicitReturn = 128, + HasExplicitReturn = 256, + GlobalAugmentation = 512, + HasClassExtends = 1024, + HasDecorators = 2048, + HasParamDecorators = 4096, + HasAsyncFunctions = 8192, + HasJsxSpreadAttributes = 16384, + DisallowInContext = 32768, + YieldContext = 65536, + DecoratorContext = 131072, + AwaitContext = 262144, + ThisNodeHasError = 524288, + JavaScriptFile = 1048576, + ThisNodeOrAnySubNodesHasError = 2097152, + HasAggregatedChildData = 4194304, + BlockScoped = 3, + ReachabilityCheckFlags = 384, + EmitHelperFlags = 31744, + ReachabilityAndEmitFlags = 32128, + ContextFlags = 1540096, + TypeExcludesFlags = 327680, + } + type ModifiersArray = NodeArray; + enum ModifierFlags { None = 0, Export = 1, Ambient = 2, @@ -357,36 +401,11 @@ declare namespace ts { Abstract = 128, Async = 256, Default = 512, - Let = 1024, Const = 2048, - Namespace = 4096, - ExportContext = 8192, - ContainsThis = 16384, - HasImplicitReturn = 32768, - HasExplicitReturn = 65536, - GlobalAugmentation = 131072, - HasClassExtends = 262144, - HasDecorators = 524288, - HasParamDecorators = 1048576, - HasAsyncFunctions = 2097152, - DisallowInContext = 4194304, - YieldContext = 8388608, - DecoratorContext = 16777216, - AwaitContext = 33554432, - ThisNodeHasError = 67108864, - JavaScriptFile = 134217728, - ThisNodeOrAnySubNodesHasError = 268435456, - HasAggregatedChildData = 536870912, - HasJsxSpreadAttribute = 1073741824, - Modifier = 1023, + HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 92, - BlockScoped = 3072, - ReachabilityCheckFlags = 98304, - EmitHelperFlags = 3932160, - ReachabilityAndEmitFlags = 4030464, - ContextFlags = 197132288, - TypeExcludesFlags = 41943040, + NonPublicAccessibilityModifier = 24, } enum JsxFlags { None = 0, @@ -403,18 +422,21 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } - interface NodeArray extends Array, TextRange { + interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface ModifiersArray extends NodeArray { - flags: NodeFlags; + interface Token extends Node { + __tokenTag: any; } - interface Modifier extends Node { + interface Modifier extends Token { } interface Identifier extends PrimaryExpression { text: string; originalKeywordKind?: SyntaxKind; } + interface TransientIdentifier extends Identifier { + resolvedSymbol: Symbol; + } interface QualifiedName extends Node { left: EntityName; right: Identifier; @@ -450,9 +472,10 @@ declare namespace ts { } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { } + type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { parent?: VariableDeclarationList; - name: Identifier | BindingPattern; + name: BindingName; type?: TypeNode; initializer?: Expression; } @@ -461,7 +484,7 @@ declare namespace ts { } interface ParameterDeclaration extends Declaration { dotDotDotToken?: Node; - name: Identifier | BindingPattern; + name: BindingName; questionToken?: Node; type?: TypeNode; initializer?: Expression; @@ -469,7 +492,7 @@ declare namespace ts { interface BindingElement extends Declaration { propertyName?: PropertyName; dotDotDotToken?: Node; - name: Identifier | BindingPattern; + name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { @@ -488,6 +511,7 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { _propertyAssignmentBrand: any; name: PropertyName; @@ -512,11 +536,14 @@ declare namespace ts { name: PropertyName; } interface BindingPattern extends Node { - elements: NodeArray; + elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + elements: NodeArray; } + type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + elements: NodeArray; } /** * Several node kinds share function-like features such as a signature, @@ -604,8 +631,9 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { + interface LiteralTypeNode extends TypeNode { _stringLiteralTypeBrand: any; + literal: Expression; } interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; @@ -615,6 +643,7 @@ declare namespace ts { contextualType?: Type; } interface OmittedExpression extends Expression { + _omittedExpressionBrand: any; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -688,9 +717,14 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface NumericLiteral extends LiteralExpression { + _numericLiteralBrand: any; + trailingComment?: string; + } interface TemplateLiteralFragment extends LiteralLikeNode { _templateLiteralFragmentBrand: any; } + type Template = TemplateExpression | LiteralExpression; interface TemplateExpression extends PrimaryExpression { head: TemplateLiteralFragment; templateSpans: NodeArray; @@ -708,14 +742,28 @@ declare namespace ts { interface SpreadElementExpression extends Expression { expression: Expression; } - interface ObjectLiteralExpression extends PrimaryExpression, Declaration { - properties: NodeArray; + /** + * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to + * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be + * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type + * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) + **/ + interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { + properties: NodeArray; } + interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + } + type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; + type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; name: Identifier; } - type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; + /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ + interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { + _propertyAccessExpressionLikeQualifiedNameBrand?: any; + expression: EntityNameExpression; + } interface ElementAccessExpression extends MemberExpression { expression: LeftHandSideExpression; argumentExpression?: Expression; @@ -733,7 +781,7 @@ declare namespace ts { } interface TaggedTemplateExpression extends MemberExpression { tag: LeftHandSideExpression; - template: LiteralExpression | TemplateExpression; + template: Template; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { @@ -763,9 +811,10 @@ declare namespace ts { _selfClosingElementBrand?: any; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { name: Identifier; - initializer?: Expression; + initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { expression: Expression; @@ -814,17 +863,18 @@ declare namespace ts { interface WhileStatement extends IterationStatement { expression: Expression; } + type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { - initializer?: VariableDeclarationList | Expression; + initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; + initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; + initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { @@ -910,7 +960,7 @@ declare namespace ts { type: TypeNode; } interface EnumMember extends Declaration { - name: DeclarationName; + name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { @@ -918,6 +968,7 @@ declare namespace ts { members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; + type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; body?: ModuleBlock | ModuleDeclaration; @@ -925,9 +976,10 @@ declare namespace ts { interface ModuleBlock extends Node, Statement { statements: NodeArray; } + type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { name: Identifier; - moduleReference: EntityName | ExternalModuleReference; + moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { expression?: Expression; @@ -936,9 +988,10 @@ declare namespace ts { importClause?: ImportClause; moduleSpecifier: Expression; } + type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { name?: Identifier; - namedBindings?: NamespaceImport | NamedImports; + namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { name: Identifier; @@ -1006,7 +1059,7 @@ declare namespace ts { type: JSDocType; } interface JSDocRecordType extends JSDocType, TypeLiteralNode { - members: NodeArray; + literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { name: EntityName; @@ -1028,17 +1081,22 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } + interface JSDocLiteralType extends JSDocType { + literal: LiteralTypeNode; + } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; type?: JSDocType; } - interface JSDocComment extends Node { - tags: NodeArray; + interface JSDoc extends Node { + tags: NodeArray | undefined; + comment: string | undefined; } interface JSDocTag extends Node { atToken: Node; tagName: Identifier; + comment: string | undefined; } interface JSDocTemplateTag extends JSDocTag { typeParameters: NodeArray; @@ -1063,9 +1121,13 @@ declare namespace ts { jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; + /** the parameter name, if provided *after* the type (JSDoc-standard) */ postParameterName?: Identifier; + /** the parameter name, regardless of the location it was provided */ + parameterName: Identifier; isBracketed: boolean; } enum FlowFlags { @@ -1106,6 +1168,11 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } interface AmdDependency { path: string; name: string; @@ -1147,6 +1214,7 @@ declare namespace ts { * @param path The path to test. */ fileExists(path: string): boolean; + readFile(path: string): string; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1263,6 +1331,7 @@ declare namespace ts { getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; + getAmbientModules(): Symbol[]; } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1302,6 +1371,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, InFirstTypeArgument = 256, + InTypeAlias = 512, } enum SymbolFormatFlags { None = 0, @@ -1360,18 +1430,18 @@ declare namespace ts { Enum = 384, Variable = 3, Value = 107455, - Type = 793056, - Namespace = 1536, + Type = 793064, + Namespace = 1920, Module = 1536, Accessor = 98304, FunctionScopedVariableExcludes = 107454, BlockScopedVariableExcludes = 107455, ParameterExcludes = 107455, PropertyExcludes = 0, - EnumMemberExcludes = 107455, + EnumMemberExcludes = 900095, FunctionExcludes = 106927, ClassExcludes = 899519, - InterfaceExcludes = 792960, + InterfaceExcludes = 792968, RegularEnumExcludes = 899327, ConstEnumExcludes = 899967, ValueModuleExcludes = 106639, @@ -1379,8 +1449,8 @@ declare namespace ts { MethodExcludes = 99263, GetAccessorExcludes = 41919, SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, + TypeParameterExcludes = 530920, + TypeAliasExcludes = 793064, AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, @@ -1400,48 +1470,65 @@ declare namespace ts { exports?: SymbolTable; globalExports?: SymbolTable; } - interface SymbolTable { - [index: string]: Symbol; - } + type SymbolTable = Map; enum TypeFlags { Any = 1, String = 2, Number = 4, Boolean = 8, - Void = 16, - Undefined = 32, - Null = 64, - Enum = 128, - StringLiteral = 256, - TypeParameter = 512, - Class = 1024, - Interface = 2048, - Reference = 4096, - Tuple = 8192, - Union = 16384, - Intersection = 32768, - Anonymous = 65536, - Instantiated = 131072, - ObjectLiteral = 524288, - ESSymbol = 16777216, - ThisType = 33554432, - ObjectLiteralPatternWithComputedProperties = 67108864, - Never = 134217728, - StringLike = 258, - NumberLike = 132, - ObjectType = 80896, - UnionOrIntersection = 49152, - StructuredType = 130048, - Narrowable = 16908175, + Enum = 16, + StringLiteral = 32, + NumberLiteral = 64, + BooleanLiteral = 128, + EnumLiteral = 256, + ESSymbol = 512, + Void = 1024, + Undefined = 2048, + Null = 4096, + Never = 8192, + TypeParameter = 16384, + Class = 32768, + Interface = 65536, + Reference = 131072, + Tuple = 262144, + Union = 524288, + Intersection = 1048576, + Anonymous = 2097152, + Instantiated = 4194304, + ThisType = 268435456, + ObjectLiteralPatternWithComputedProperties = 536870912, + Literal = 480, + StringOrNumberLiteral = 96, + PossiblyFalsy = 7406, + StringLike = 34, + NumberLike = 340, + BooleanLike = 136, + EnumLike = 272, + ObjectType = 2588672, + UnionOrIntersection = 1572864, + StructuredType = 4161536, + StructuredOrTypeParameter = 4177920, + Narrowable = 4178943, + NotUnionOrUnit = 2589191, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { flags: TypeFlags; symbol?: Symbol; pattern?: DestructuringPattern; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; } - interface StringLiteralType extends Type { + interface LiteralType extends Type { text: string; + freshType?: LiteralType; + regularType?: LiteralType; + } + interface EnumType extends Type { + memberTypes: Map; + } + interface EnumLiteralType extends LiteralType { + baseType: EnumType & UnionType; } interface ObjectType extends Type { } @@ -1464,9 +1551,6 @@ declare namespace ts { } interface GenericType extends InterfaceType, TypeReference { } - interface TupleType extends ObjectType { - elementTypes: Type[]; - } interface UnionOrIntersectionType extends Type { types: Type[]; } @@ -1531,7 +1615,7 @@ declare namespace ts { NodeJs = 2, } type RootPaths = string[]; - type PathSubstitutions = Map; + type PathSubstitutions = MapLike; type TsConfigOnlyOptions = RootPaths | PathSubstitutions; type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; interface CompilerOptions { @@ -1548,6 +1632,7 @@ declare namespace ts { emitDecoratorMetadata?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; inlineSourceMap?: boolean; inlineSources?: boolean; isolatedModules?: boolean; @@ -1656,7 +1741,7 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; - wildcardDirectories?: Map; + wildcardDirectories?: MapLike; } enum WatchDirectoryFlags { None = 0, @@ -1664,7 +1749,7 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - wildcardDirectories: Map; + wildcardDirectories: MapLike; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1673,6 +1758,7 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; realpath?(path: string): string; getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; } interface ResolvedModule { resolvedFileName: string; @@ -1696,7 +1782,6 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; - getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getDirectories(path: string): string[]; @@ -1708,6 +1793,7 @@ declare namespace ts { * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + getEnvironmentVariable?(name: string): string; } interface TextSpan { start: number; @@ -1782,6 +1868,7 @@ declare namespace ts { reScanSlashToken(): SyntaxKind; reScanTemplateToken(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; + scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; scanJSDocToken(): SyntaxKind; @@ -1804,6 +1891,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; /** Optionally, get the shebang */ @@ -1842,8 +1933,8 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; - function startsWith(str: string, prefix: string): boolean; - function endsWith(str: string, suffix: string): boolean; + function getCombinedModifierFlags(node: Node): ModifierFlags; + function getCombinedNodeFlags(node: Node): NodeFlags; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -1854,9 +1945,13 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version: string; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; + const version = "2.1.0"; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -1868,16 +1963,22 @@ declare namespace ts { function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** - * Given a set of options and a set of root files, returns the set of type directive names + * Given a set of options, returns the set of type directive names * that should be included for this program automatically. * This list could either come from the config file, * or from enumerating the types root + initial secondary types lookup location. * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1905,7 +2006,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -1916,8 +2017,6 @@ declare namespace ts { }; } declare namespace ts { - /** The version of the language service API */ - const servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -1983,7 +2082,7 @@ declare namespace ts { * change range cannot be determined. However, in that case, incremental parsing will * not happen and the entire document will be re - parsed. */ - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; /** Releases all resources held by this script snapshot */ dispose?(): void; } @@ -2016,6 +2115,9 @@ declare namespace ts { trace?(s: string): void; error?(s: string): void; useCaseSensitiveFileNames?(): boolean; + readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readFile?(path: string, encoding?: string): string; + fileExists?(path: string): boolean; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2038,6 +2140,7 @@ declare namespace ts { getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; @@ -2046,12 +2149,13 @@ declare namespace ts { findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; @@ -2112,15 +2216,19 @@ declare namespace ts { isWriteAccess: boolean; isDefinition: boolean; } + interface ImplementationLocation { + textSpan: TextSpan; + fileName: string; + } interface DocumentHighlights { fileName: string; highlightSpans: HighlightSpan[]; } namespace HighlightSpanKind { - const none: string; - const definition: string; - const reference: string; - const writtenReference: string; + const none = "none"; + const definition = "definition"; + const reference = "reference"; + const writtenReference = "writtenReference"; } interface HighlightSpan { fileName?: string; @@ -2159,8 +2267,10 @@ declare namespace ts { InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; [s: string]: boolean | number | string | undefined; @@ -2173,8 +2283,11 @@ declare namespace ts { containerKind: string; containerName: string; } + interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { + displayParts: SymbolDisplayPart[]; + } interface ReferencedSymbol { - definition: DefinitionInfo; + definition: ReferencedSymbolDefinitionInfo; references: ReferenceEntry[]; } enum SymbolDisplayPartKind { @@ -2262,6 +2375,12 @@ declare namespace ts { kind: string; kindModifiers: string; sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. It will be + * set if the required span differs from the one generated by the default replacement behavior and should + * be used in that case + */ + replacementSpan?: TextSpan; } interface CompletionEntryDetails { name: string; @@ -2349,6 +2468,135 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } + namespace ScriptElementKind { + const unknown = ""; + const warning = "warning"; + /** predefined type (void) or keyword (class) */ + const keyword = "keyword"; + /** top level script node */ + const scriptElement = "script"; + /** module foo {} */ + const moduleElement = "module"; + /** class X {} */ + const classElement = "class"; + /** var x = class X {} */ + const localClassElement = "local class"; + /** interface Y {} */ + const interfaceElement = "interface"; + /** type T = ... */ + const typeElement = "type"; + /** enum E */ + const enumElement = "enum"; + const enumMemberElement = "const"; + /** + * Inside module and script only + * const v = .. + */ + const variableElement = "var"; + /** Inside function */ + const localVariableElement = "local var"; + /** + * Inside module and script only + * function f() { } + */ + const functionElement = "function"; + /** Inside function */ + const localFunctionElement = "local function"; + /** class X { [public|private]* foo() {} } */ + const memberFunctionElement = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + const memberGetAccessorElement = "getter"; + const memberSetAccessorElement = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + const memberVariableElement = "property"; + /** class X { constructor() { } } */ + const constructorImplementationElement = "constructor"; + /** interface Y { ():number; } */ + const callSignatureElement = "call"; + /** interface Y { []:number; } */ + const indexSignatureElement = "index"; + /** interface Y { new():Y; } */ + const constructSignatureElement = "construct"; + /** function foo(*Y*: string) */ + const parameterElement = "parameter"; + const typeParameterElement = "type parameter"; + const primitiveType = "primitive type"; + const label = "label"; + const alias = "alias"; + const constElement = "const"; + const letElement = "let"; + const directory = "directory"; + const externalModuleName = "external module name"; + } + namespace ScriptElementKindModifier { + const none = ""; + const publicMemberModifier = "public"; + const privateMemberModifier = "private"; + const protectedMemberModifier = "protected"; + const exportedModifier = "export"; + const ambientModifier = "declare"; + const staticModifier = "static"; + const abstractModifier = "abstract"; + } + class ClassificationTypeNames { + static comment: string; + static identifier: string; + static keyword: string; + static numericLiteral: string; + static operator: string; + static stringLiteral: string; + static whiteSpace: string; + static text: string; + static punctuation: string; + static className: string; + static enumName: string; + static interfaceName: string; + static moduleName: string; + static typeParameterName: string; + static typeAliasName: string; + static parameterName: string; + static docCommentTagName: string; + static jsxOpenTagName: string; + static jsxCloseTagName: string; + static jsxSelfClosingTagName: string; + static jsxAttribute: string; + static jsxText: string; + static jsxAttributeStringLiteralValue: string; + } + 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, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + } +} +declare namespace ts { + function createClassifier(): Classifier; +} +declare namespace ts { /** * The document registry represents a store of SourceFile objects that can be shared between * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) @@ -2412,138 +2660,18 @@ declare namespace ts { type DocumentRegistryBucketKey = string & { __bucketKey: any; }; - namespace ScriptElementKind { - const unknown: string; - const warning: string; - /** predefined type (void) or keyword (class) */ - const keyword: string; - /** top level script node */ - const scriptElement: string; - /** module foo {} */ - const moduleElement: string; - /** class X {} */ - const classElement: string; - /** var x = class X {} */ - const localClassElement: string; - /** interface Y {} */ - const interfaceElement: string; - /** type T = ... */ - const typeElement: string; - /** enum E */ - const enumElement: string; - /** - * Inside module and script only - * const v = .. - */ - const variableElement: string; - /** Inside function */ - const localVariableElement: string; - /** - * Inside module and script only - * function f() { } - */ - const functionElement: string; - /** Inside function */ - const localFunctionElement: string; - /** class X { [public|private]* foo() {} } */ - const memberFunctionElement: string; - /** class X { [public|private]* [get|set] foo:number; } */ - const memberGetAccessorElement: string; - const memberSetAccessorElement: string; - /** - * class X { [public|private]* foo:number; } - * interface Y { foo:number; } - */ - const memberVariableElement: string; - /** class X { constructor() { } } */ - const constructorImplementationElement: string; - /** interface Y { ():number; } */ - const callSignatureElement: string; - /** interface Y { []:number; } */ - const indexSignatureElement: string; - /** interface Y { new():Y; } */ - const constructSignatureElement: string; - /** function foo(*Y*: string) */ - const parameterElement: string; - const typeParameterElement: string; - const primitiveType: string; - const label: string; - const alias: string; - const constElement: string; - const letElement: string; - } - namespace ScriptElementKindModifier { - const none: string; - const publicMemberModifier: string; - const privateMemberModifier: string; - const protectedMemberModifier: string; - const exportedModifier: string; - const ambientModifier: string; - const staticModifier: string; - const abstractModifier: string; - } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - static jsxOpenTagName: string; - static jsxCloseTagName: string; - static jsxSelfClosingTagName: string; - static jsxAttribute: string; - static jsxText: string; - static jsxAttributeStringLiteralValue: string; - } - 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, - docCommentTagName = 18, - jsxOpenTagName = 19, - jsxCloseTagName = 20, - jsxSelfClosingTagName = 21, - jsxAttribute = 22, - jsxText = 23, - jsxAttributeStringLiteralValue = 24, - } - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; - function getDefaultCompilerOptions(): CompilerOptions; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; +} +declare namespace ts { + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; +} +declare namespace ts { interface TranspileOptions { compilerOptions?: CompilerOptions; fileName?: string; reportDiagnostics?: boolean; moduleName?: string; - renamedDependencies?: Map; + renamedDependencies?: MapLike; } interface TranspileOutput { outputText: string; @@ -2552,13 +2680,19 @@ declare namespace ts { } function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; +} +declare namespace ts { + /** The version of the language service API */ + const servicesVersion = "0.5"; + interface DisplayPartsSymbolWriter extends SymbolWriter { + displayParts(): SymbolDisplayPart[]; + } + function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function getDefaultCompilerOptions(): CompilerOptions; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; - function createClassifier(): Classifier; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript * node package. diff --git a/lib/typescript.js b/lib/typescript.js index 22cbe79129c..14fbdce59a8 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -205,7 +205,7 @@ var ts; SyntaxKind[SyntaxKind["IntersectionType"] = 163] = "IntersectionType"; SyntaxKind[SyntaxKind["ParenthesizedType"] = 164] = "ParenthesizedType"; SyntaxKind[SyntaxKind["ThisType"] = 165] = "ThisType"; - SyntaxKind[SyntaxKind["StringLiteralType"] = 166] = "StringLiteralType"; + SyntaxKind[SyntaxKind["LiteralType"] = 166] = "LiteralType"; // Binding patterns SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 167] = "ObjectBindingPattern"; SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 168] = "ArrayBindingPattern"; @@ -334,13 +334,22 @@ var ts; SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 279] = "JSDocTypedefTag"; SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 280] = "JSDocPropertyTag"; SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 281] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 282] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 283] = "JSDocNullKeyword"; + SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 284] = "JSDocUndefinedKeyword"; + SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 285] = "JSDocNeverKeyword"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 282] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 283] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 289] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 57] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 68] = "LastCompoundAssignment"; SyntaxKind[SyntaxKind["FirstReservedWord"] = 70] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 105] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 70] = "FirstKeyword"; @@ -363,58 +372,66 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 139] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 257] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 281] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 282] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 273] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 281] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Export"] = 1] = "Export"; - NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; - NodeFlags[NodeFlags["Public"] = 4] = "Public"; - NodeFlags[NodeFlags["Private"] = 8] = "Private"; - NodeFlags[NodeFlags["Protected"] = 16] = "Protected"; - NodeFlags[NodeFlags["Static"] = 32] = "Static"; - NodeFlags[NodeFlags["Readonly"] = 64] = "Readonly"; - NodeFlags[NodeFlags["Abstract"] = 128] = "Abstract"; - NodeFlags[NodeFlags["Async"] = 256] = "Async"; - NodeFlags[NodeFlags["Default"] = 512] = "Default"; - NodeFlags[NodeFlags["Let"] = 1024] = "Let"; - NodeFlags[NodeFlags["Const"] = 2048] = "Const"; - NodeFlags[NodeFlags["Namespace"] = 4096] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 8192] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 16384] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 32768] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 65536] = "HasExplicitReturn"; - NodeFlags[NodeFlags["GlobalAugmentation"] = 131072] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasClassExtends"] = 262144] = "HasClassExtends"; - NodeFlags[NodeFlags["HasDecorators"] = 524288] = "HasDecorators"; - NodeFlags[NodeFlags["HasParamDecorators"] = 1048576] = "HasParamDecorators"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 2097152] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["DisallowInContext"] = 4194304] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 8388608] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 16777216] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 33554432] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 67108864] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 134217728] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 268435456] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 536870912] = "HasAggregatedChildData"; - NodeFlags[NodeFlags["HasJsxSpreadAttribute"] = 1073741824] = "HasJsxSpreadAttribute"; - NodeFlags[NodeFlags["Modifier"] = 1023] = "Modifier"; - NodeFlags[NodeFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; - // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - NodeFlags[NodeFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; - NodeFlags[NodeFlags["BlockScoped"] = 3072] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 98304] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["EmitHelperFlags"] = 3932160] = "EmitHelperFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 4030464] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasClassExtends"] = 1024] = "HasClassExtends"; + NodeFlags[NodeFlags["HasDecorators"] = 2048] = "HasDecorators"; + NodeFlags[NodeFlags["HasParamDecorators"] = 4096] = "HasParamDecorators"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 8192] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["HasJsxSpreadAttributes"] = 16384] = "HasJsxSpreadAttributes"; + NodeFlags[NodeFlags["DisallowInContext"] = 32768] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 65536] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 131072] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 262144] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 524288] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 1048576] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 2097152] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 4194304] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["EmitHelperFlags"] = 31744] = "EmitHelperFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 32128] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 197132288] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 1540096] = "ContextFlags"; // Exclude these flags when parsing a Type - NodeFlags[NodeFlags["TypeExcludesFlags"] = 41943040] = "TypeExcludesFlags"; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 327680] = "TypeExcludesFlags"; })(ts.NodeFlags || (ts.NodeFlags = {})); var NodeFlags = ts.NodeFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + })(ts.ModifierFlags || (ts.ModifierFlags = {})); + var ModifierFlags = ts.ModifierFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; /** An element from a named property of the JSX.IntrinsicElements interface */ @@ -431,6 +448,15 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); var RelationComparisonResult = ts.RelationComparisonResult; + /*@internal*/ + (function (GeneratedIdentifierKind) { + GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; + })(ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierKind = ts.GeneratedIdentifierKind; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; FlowFlags[FlowFlags["Start"] = 2] = "Start"; @@ -475,6 +501,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -512,15 +539,16 @@ var ts; // function that can be reached at runtime (e.g. a `class` // declaration or a `var` declaration for the static side // of a type, such as the global `Promise` type in lib.d.ts). - TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidType"] = 2] = "VoidType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 8] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; // with call signatures. - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 9] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; (function (SymbolFlags) { @@ -559,8 +587,8 @@ var ts; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793056] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1536] = "Namespace"; + SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the @@ -571,10 +599,10 @@ var ts; SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792960] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; @@ -582,8 +610,8 @@ var ts; SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530912] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793056] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -618,6 +646,9 @@ var ts; NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -625,55 +656,64 @@ var ts; TypeFlags[TypeFlags["String"] = 2] = "String"; TypeFlags[TypeFlags["Number"] = 4] = "Number"; TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Void"] = 16] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 32] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 64] = "Null"; - TypeFlags[TypeFlags["Enum"] = 128] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 256] = "StringLiteral"; - TypeFlags[TypeFlags["TypeParameter"] = 512] = "TypeParameter"; - TypeFlags[TypeFlags["Class"] = 1024] = "Class"; - TypeFlags[TypeFlags["Interface"] = 2048] = "Interface"; - TypeFlags[TypeFlags["Reference"] = 4096] = "Reference"; - TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; - TypeFlags[TypeFlags["Union"] = 16384] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 32768] = "Intersection"; - TypeFlags[TypeFlags["Anonymous"] = 65536] = "Anonymous"; - TypeFlags[TypeFlags["Instantiated"] = 131072] = "Instantiated"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["Void"] = 1024] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 4096] = "Null"; + TypeFlags[TypeFlags["Never"] = 8192] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; + TypeFlags[TypeFlags["Class"] = 32768] = "Class"; + TypeFlags[TypeFlags["Interface"] = 65536] = "Interface"; + TypeFlags[TypeFlags["Reference"] = 131072] = "Reference"; + TypeFlags[TypeFlags["Tuple"] = 262144] = "Tuple"; + TypeFlags[TypeFlags["Union"] = 524288] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 1048576] = "Intersection"; + TypeFlags[TypeFlags["Anonymous"] = 2097152] = "Anonymous"; + TypeFlags[TypeFlags["Instantiated"] = 4194304] = "Instantiated"; /* @internal */ - TypeFlags[TypeFlags["FromSignature"] = 262144] = "FromSignature"; - TypeFlags[TypeFlags["ObjectLiteral"] = 524288] = "ObjectLiteral"; + TypeFlags[TypeFlags["ObjectLiteral"] = 8388608] = "ObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["FreshObjectLiteral"] = 1048576] = "FreshObjectLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 16777216] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsWideningType"] = 33554432] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; - TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; - TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; + TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; + TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 16015] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 16777726] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; - TypeFlags[TypeFlags["ObjectType"] = 80896] = "ObjectType"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 49152] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 130048] = "StructuredType"; + TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; + TypeFlags[TypeFlags["ObjectType"] = 2588672] = "ObjectType"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 1572864] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 4161536] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 4177920] = "StructuredOrTypeParameter"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 16908175] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + TypeFlags[TypeFlags["PropagatingFlags"] = 234881024] = "PropagatingFlags"; })(ts.TypeFlags || (ts.TypeFlags = {})); var TypeFlags = ts.TypeFlags; (function (SignatureKind) { @@ -892,8 +932,195 @@ var ts; CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; })(ts.CharacterCodes || (ts.CharacterCodes = {})); var CharacterCodes = ts.CharacterCodes; + /* @internal */ + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["Jsx"] = 4] = "Jsx"; + TransformFlags[TransformFlags["ContainsJsx"] = 8] = "ContainsJsx"; + TransformFlags[TransformFlags["ES7"] = 16] = "ES7"; + TransformFlags[TransformFlags["ContainsES7"] = 32] = "ContainsES7"; + TransformFlags[TransformFlags["ES6"] = 64] = "ES6"; + TransformFlags[TransformFlags["ContainsES6"] = 128] = "ContainsES6"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 256] = "DestructuringAssignment"; + TransformFlags[TransformFlags["Generator"] = 512] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. + TransformFlags[TransformFlags["ContainsDecorators"] = 2048] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 4096] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 131072] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpreadElementExpression"] = 262144] = "ContainsSpreadElementExpression"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 12] = "AssertJsx"; + TransformFlags[TransformFlags["AssertES7"] = 48] = "AssertES7"; + TransformFlags[TransformFlags["AssertES6"] = 192] = "AssertES6"; + TransformFlags[TransformFlags["AssertGenerator"] = 1536] = "AssertGenerator"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. + TransformFlags[TransformFlags["NodeExcludes"] = 536871765] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 550710101] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 550726485] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 550593365] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 550593365] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 537590613] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 546335573] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 537430869] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537133909] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 538968917] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 538968917] = "ParameterExcludes"; + // Masks + // - Additional bitmasks + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 137216] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES6FunctionSyntaxMask"] = 81920] = "ES6FunctionSyntaxMask"; + })(ts.TransformFlags || (ts.TransformFlags = {})); + var TransformFlags = ts.TransformFlags; + /* @internal */ + (function (NodeEmitFlags) { + NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; + NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; + NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; + NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; + NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; + NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; + NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; + NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; + NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; + NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; + NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; + NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; + NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; + NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; + NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; + NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; + NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; + NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; + NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; + NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; + NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; + NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; + NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; + })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); + var NodeEmitFlags = ts.NodeEmitFlags; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +var ts; +(function (ts) { + var performance; + (function (performance) { + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true + ? onProfilerEvent + : function (markName) { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks[markName] = ts.timestamp(); + counts[markName] = (counts[markName] || 0) + 1; + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks[endMarkName] || ts.timestamp(); + var start = startMarkName && marks[startMarkName] || profilerStart; + measures[measureName] = (measures[measureName] || 0) + (end - start); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts[markName] || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures[measureName] || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + for (var key in measures) { + cb(key, measures[key]); + } + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /// +/// /* @internal */ var ts; (function (ts) { @@ -912,8 +1139,25 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; + var createObject = Object.create; + function createMap(template) { + var map = createObject(null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map["__"] = undefined; + delete map["__"]; + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) + if (hasOwnProperty.call(template, key)) { + map[key] = template[key]; + } + return map; + } + ts.createMap = createMap; function createFileMap(keyMapper) { - var files = {}; + var files = createMap(); return { get: get, set: set, @@ -935,14 +1179,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return hasProperty(files, toKey(path)); + return toKey(path) in files; } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = {}; + files = createMap(); } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -979,11 +1223,52 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ + function find(array, predicate) { + for (var i = 0, len = array.length; i < len; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0, len = array.length; i < len; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (areEqual ? areEqual(v, value) : v === value) { + if (v === value) { return true; } } @@ -1014,9 +1299,9 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var v = array_2[_i]; - if (predicate(v)) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { count++; } } @@ -1025,23 +1310,47 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { - var result; if (array) { - result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - result.push(item); + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; } + return result; } } - return result; + return array; } ts.filter = filter; + function removeWhere(array, f) { + var outIndex = 0; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var item = array_2[_i]; + if (!f(item)) { + array[outIndex] = item; + outIndex++; + } + } + if (outIndex !== array.length) { + array.length = outIndex; + return true; + } + return false; + } + ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var item = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { array[outIndex] = item; outIndex++; @@ -1054,14 +1363,136 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; - result.push(f(v)); + for (var i = 0; i < array.length; i++) { + var v = array[i]; + result.push(f(v, i)); } } return result; } ts.map = map; + /** + * Flattens an array containing a mix of array or non-array elements. + * + * @param array The array to flatten. + */ + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function flatMap(array, mapfn) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMap = flatMap; + /** + * Computes the first matching span of elements and returns a tuple of the first span + * and the remaining elements. + */ + function span(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!f(array[i], i)) { + return [array.slice(0, i), array.slice(i)]; + } + } + return [array.slice(0), []]; + } + return undefined; + } + ts.span = span; + /** + * Maps contiguous spans of values with the same key. + * + * @param array The array to map. + * @param keyfn A callback used to select the key for an element. + * @param mapfn A callback used to map a contiguous chunk of values to a single value. + */ + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapObject(object, f) { + var result; + if (object) { + result = {}; + for (var _i = 0, _a = getOwnKeys(object); _i < _a.length; _i++) { + var v = _a[_i]; + var _b = f(v, object[v]) || [undefined, undefined], key = _b[0], value = _b[1]; + if (key !== undefined) { + result[key] = value; + } + } + } + return result; + } + ts.mapObject = mapObject; function concatenate(array1, array2) { if (!array2 || !array2.length) return array1; @@ -1074,20 +1505,45 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; - if (!contains(result, item, areEqual)) { - result.push(item); + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; + for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { + var res = result_1[_a]; + if (areEqual ? areEqual(res, item) : res === item) { + continue loop; + } } + result.push(item); } } return result; } ts.deduplicate = deduplicate; + /** + * Compacts an array, removing any falsey elements. + */ + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -1097,7 +1553,9 @@ var ts; if (to && from) { for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { var v = from_1[_i]; - to.push(v); + if (v !== undefined) { + to.push(v); + } } } } @@ -1112,14 +1570,31 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function firstOrUndefined(array) { + return array && array.length > 0 + ? array[0] + : undefined; + } + ts.firstOrUndefined = firstOrUndefined; + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; /** * Returns the last element of an array if non-empty, undefined otherwise. */ function lastOrUndefined(array) { - if (array.length === 0) { - return undefined; - } - return array[array.length - 1]; + return array && array.length > 0 + ? array[array.length - 1] + : undefined; } ts.lastOrUndefined = lastOrUndefined; /** @@ -1148,11 +1623,12 @@ var ts; return ~low; } ts.binarySearch = binarySearch; - function reduceLeft(array, f, initial) { - if (array) { - var count = array.length; - if (count > 0) { - var pos = 0; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -1161,8 +1637,8 @@ var ts; else { result = initial; } - while (pos < count) { - result = f(result, array[pos]); + while (pos <= end) { + result = f(result, array[pos], pos); pos++; } return result; @@ -1171,10 +1647,12 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial) { + function reduceRight(array, f, initial, start, count) { if (array) { - var pos = array.length - 1; - if (pos >= 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start > size - 1 ? size - 1 : start; + var end = count === undefined || pos - count < 0 ? 0 : pos - count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -1183,8 +1661,8 @@ var ts; else { result = initial; } - while (pos >= 0) { - result = f(result, array[pos]); + while (pos >= end) { + result = f(result, array[pos], pos); pos--; } return result; @@ -1194,22 +1672,177 @@ var ts; } ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * NOTE: This is intended for use only with MapLike objects. For Map objects, use + * the 'in' operator. + * + * @param map A map-like. + * @param key A property key. + */ function hasProperty(map, key) { return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; - function getKeys(map) { - var keys = []; - for (var key in map) { - keys.push(key); - } - return keys; - } - ts.getKeys = getKeys; + /** + * Gets the value of an owned property in a map-like. + * + * NOTE: This is intended for use only with MapLike objects. For Map objects, use + * an indexer. + * + * @param map A map-like. + * @param key A property key. + */ function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + * + * NOTE: This is intended for use with MapLike objects. For Map objects, use + * Object.keys instead as it offers better performance. + * + * @param map A map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + /** + * Enumerates the properties of a Map, invoking a callback and returning the first truthy result. + * + * @param map A map for which properties should be enumerated. + * @param callback A callback to invoke for each property. + */ + function forEachProperty(map, callback) { + var result; + for (var key in map) { + if (result = callback(map[key], key)) + break; + } + return result; + } + ts.forEachProperty = forEachProperty; + /** + * Returns true if a Map has some matching property. + * + * @param map A map whose properties should be tested. + * @param predicate An optional callback used to test each property. + */ + function someProperties(map, predicate) { + for (var key in map) { + if (!predicate || predicate(map[key], key)) + return true; + } + return false; + } + ts.someProperties = someProperties; + /** + * Performs a shallow copy of the properties from a source Map to a target MapLike + * + * @param source A map from which properties should be copied. + * @param target A map to which properties should be copied. + */ + function copyProperties(source, target) { + for (var key in source) { + target[key] = source[key]; + } + } + ts.copyProperties = copyProperties; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var _b = 0, _c = getOwnKeys(arg); _b < _c.length; _b++) { + var p = _c[_b]; + t[p] = arg[p]; + } + } + return t; + } + ts.assign = assign; + /** + * Reduce the properties of a map. + * + * NOTE: This is intended for use with Map objects. For MapLike objects, use + * reduceOwnProperties instead as it offers better runtime safety. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + function reduceProperties(map, callback, initial) { + var result = initial; + for (var key in map) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceProperties = reduceProperties; + /** + * Reduce the properties defined on a map-like (but not from its prototype chain). + * + * NOTE: This is intended for use with MapLike objects. For Map objects, use + * reduceProperties instead as it offers better performance. + * + * @param map The map-like to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + function reduceOwnProperties(map, callback, initial) { + var result = initial; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceOwnProperties = reduceOwnProperties; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key) === undefined) + return false; + if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + return false; + } + for (var key in right) + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; function isEmpty(map) { for (var id in map) { if (hasProperty(map, id)) { @@ -1219,92 +1852,65 @@ var ts; return true; } ts.isEmpty = isEmpty; + function cloneMap(map) { + var clone = createMap(); + copyProperties(map, clone); + return clone; + } + ts.cloneMap = cloneMap; function clone(object) { var result = {}; for (var id in object) { - result[id] = object[id]; + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in first) { - result[id] = first[id]; - } - for (var id in second) { - if (!hasProperty(result, id)) { + for (var id in second) + if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - } + for (var id in first) + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } return result; } ts.extend = extend; - function forEachValue(map, callback) { - var result; - for (var id in map) { - if (result = callback(map[id])) - break; - } - return result; - } - ts.forEachValue = forEachValue; - function forEachKey(map, callback) { - var result; - for (var id in map) { - if (result = callback(id)) - break; - } - return result; - } - ts.forEachKey = forEachKey; - function lookUp(map, key) { - return hasProperty(map, key) ? map[key] : undefined; - } - ts.lookUp = lookUp; - function copyMap(source, target) { - for (var p in source) { - target[p] = source[p]; - } - } - ts.copyMap = copyMap; /** - * Creates a map from the elements of an array. - * - * @param array the array of input elements. - * @param makeKey a function that produces a key for a given element. - * - * This function makes no effort to avoid collisions; if any two elements produce - * the same key with the given 'makeKey' function, then the element with the higher - * index in the array will be the one associated with the produced key. + * Adds the value to an array of values associated with the key, and returns the array. + * Creates the array if it does not already exist. */ - function arrayToMap(array, makeKey) { - var result = {}; - forEach(array, function (value) { - result[makeKey(value)] = value; - }); - return result; + function multiMapAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + return values; + } + else { + return map[key] = [value]; + } } - ts.arrayToMap = arrayToMap; + ts.multiMapAdd = multiMapAdd; /** - * Reduce the properties of a map. - * - * @param map The map to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. + * Removes a value from an array of values associated with the key. + * Does not preserve the order of those values. + * Does nothing if `key` is not in `map`, or `value` is not in `map[key]`. */ - function reduceProperties(map, callback, initial) { - var result = initial; - if (map) { - for (var key in map) { - if (hasProperty(map, key)) { - result = callback(result, map[key], String(key)); - } + function multiMapRemove(map, key, value) { + var values = map[key]; + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + delete map[key]; } } - return result; } - ts.reduceProperties = reduceProperties; + ts.multiMapRemove = multiMapRemove; /** * Tests whether a value is an array. */ @@ -1329,9 +1935,7 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] - ? ts.localizedDiagnosticMessages[message.key] - : message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -1526,6 +2130,7 @@ var ts; } ts.getRootLength = getRootLength; ts.directorySeparator = "/"; + var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; @@ -1549,10 +2154,22 @@ var ts; function normalizePath(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); + var root = path.substr(0, rootLength); var normalized = getNormalizedParts(path, rootLength); - return path.substr(0, rootLength) + normalized.join(ts.directorySeparator); + if (normalized.length) { + var joinedParts = root + normalized.join(ts.directorySeparator); + return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + } + else { + return root; + } } ts.normalizePath = normalizePath; + /** A path ending with '/' refers to a directory only, never a file. */ + function pathEndsWithDirectorySeparator(path) { + return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; + } + ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; function getDirectoryPath(path) { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); } @@ -1756,10 +2373,19 @@ var ts; return true; } ts.containsPath = containsPath; + /* @internal */ + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + /* @internal */ + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - var pathLen = path.length; - var extLen = extension.length; - return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; + return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -1777,10 +2403,25 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory seperators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; + var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } + var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; + var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -1805,7 +2446,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -1817,6 +2458,19 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } + if (usage !== "exclude") { + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + subpattern += "[^./]"; + component = component.substr(1); + } + } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -1837,8 +2491,14 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildcardCharacter(match) { - return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + function replaceWildCardCharacterFiles(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); + } + function replaceWildCardCharacterOther(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1957,6 +2617,8 @@ var ts; * List of supported extensions in order of file resolution precedence. */ ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { @@ -2040,9 +2702,13 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; + return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -2062,14 +2728,21 @@ var ts; function Signature(checker) { } function Node(kind, pos, end) { + this.id = 0; this.kind = kind; this.pos = pos; this.end = end; this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; this.parent = undefined; + this.original = undefined; + this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -2084,9 +2757,9 @@ var ts; var AssertionLevel = ts.AssertionLevel; var Debug; (function (Debug) { - var currentAssertionLevel = 0 /* None */; + var currentAssertionLevel; function shouldAssert(level) { - return currentAssertionLevel >= level; + return getCurrentAssertionLevel() >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2104,20 +2777,61 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; + function getCurrentAssertionLevel() { + if (currentAssertionLevel !== undefined) { + return currentAssertionLevel; + } + if (ts.sys === undefined) { + return 0 /* None */; + } + var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); + currentAssertionLevel = developmentMode + ? 1 /* Normal */ + : 0 /* None */; + return currentAssertionLevel; + } })(Debug = ts.Debug || (ts.Debug = {})); - function copyListRemovingItem(item, list) { - var copiedList = []; - for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { - var e = list_1[_i]; - if (e !== item) { - copiedList.push(e); + function getEnvironmentVariable(name, host) { + if (host && host.getEnvironmentVariable) { + return host.getEnvironmentVariable(name); + } + if (ts.sys && ts.sys.getEnvironmentVariable) { + return ts.sys.getEnvironmentVariable(name); + } + return ""; + } + ts.getEnvironmentVariable = getEnvironmentVariable; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + break; } } - return copiedList; } - ts.copyListRemovingItem = copyListRemovingItem; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? (function (fileName) { return fileName; }) : (function (fileName) { return fileName.toLowerCase(); }); } @@ -2216,7 +2930,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - return { + var wscriptSystem = { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -2235,7 +2949,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!wscriptSystem.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -2246,6 +2960,9 @@ var ts; return shell.CurrentDirectory; }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%" + name + "%"); + }, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -2255,6 +2972,7 @@ var ts; } } }; + return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -2263,14 +2981,14 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = {}; + var dirWatchers = ts.createMap(); // One file can have multiple watchers - var fileWatcherCallbacks = {}; + var fileWatcherCallbacks = ts.createMap(); return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - if (ts.hasProperty(dirWatchers, dirName)) { - var watcher = dirWatchers[dirName]; + var watcher = dirWatchers[dirName]; + if (watcher) { watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -2279,23 +2997,18 @@ var ts; } } function addDirWatcher(dirPath) { - if (ts.hasProperty(dirWatchers, dirPath)) { - var watcher_1 = dirWatchers[dirPath]; - watcher_1.referenceCount += 1; + var watcher = dirWatchers[dirPath]; + if (watcher) { + watcher.referenceCount += 1; return; } - var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - fileWatcherCallbacks[filePath].push(callback); - } - else { - fileWatcherCallbacks[filePath] = [callback]; - } + ts.multiMapAdd(fileWatcherCallbacks, filePath, callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -2307,15 +3020,7 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); - if (newCallbacks.length === 0) { - delete fileWatcherCallbacks[filePath]; - } - else { - fileWatcherCallbacks[filePath] = newCallbacks; - } - } + ts.multiMapRemove(fileWatcherCallbacks, filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" @@ -2323,7 +3028,7 @@ var ts; ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); // Some applications save a working file via rename operations - if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -2442,9 +3147,9 @@ var ts; return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - return { + var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -2500,7 +3205,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!nodeSystem.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -2511,6 +3216,9 @@ var ts; return process.cwd(); }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -2546,8 +3254,16 @@ var ts; }, realpath: function (path) { return _fs.realpathSync(path); + }, + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (e) { + } } }; + return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -2574,6 +3290,7 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), readDirectory: function (path, extensions, excludes, includes) { var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); @@ -2809,9 +3526,9 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher_1311", message: "Async functions are only available when targeting ECMAScript 2015 or higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, @@ -2866,12 +3583,11 @@ var ts; Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, - Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_2349", message: "Cannot invoke an expression whose type lacks a call signature." }, + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, @@ -3013,7 +3729,6 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_yield_expressions_2504", message: "No best common type exists among yield expressions." }, A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, @@ -3030,7 +3745,7 @@ var ts; A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, @@ -3043,6 +3758,7 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, + Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3090,6 +3806,13 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, + A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, + Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -3160,7 +3883,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -3188,6 +3911,7 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -3218,6 +3942,7 @@ var ts; VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, + STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, @@ -3304,10 +4029,12 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, - Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, + Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, + Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, + Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3316,7 +4043,6 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -3331,6 +4057,8 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -3358,7 +4086,9 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." } + Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } }; })(ts || (ts = {})); /// @@ -3370,7 +4100,7 @@ var ts; return token >= 69 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115 /* AbstractKeyword */, "any": 117 /* AnyKeyword */, "as": 116 /* AsKeyword */, @@ -3494,7 +4224,7 @@ var ts; "|=": 67 /* BarEqualsToken */, "^=": 68 /* CaretEqualsToken */, "@": 55 /* AtToken */ - }; + }); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -3580,9 +4310,7 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - if (source.hasOwnProperty(name_4)) { - result[source[name_4]] = name_4; - } + result[source[name_4]] = name_4; } return result; } @@ -3743,9 +4471,7 @@ var ts; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { if (stopAtComments === void 0) { stopAtComments = false; } - // Using ! with a greater than test is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - if (!(pos >= 0)) { + if (ts.positionIsSynthesized(pos)) { return pos; } // Keep in sync with couldStartTrivia @@ -3876,20 +4602,34 @@ var ts; return pos; } /** - * Extract comments from text prefixing the token closest following `pos`. - * The return value is an array containing a TextRange for each comment. - * Single-line comment ranges include the beginning '//' characters but not the ending line break. - * Multi - line comment ranges include the beginning '/* and ending '/' characters. - * The return value is undefined if no comments were found. - * @param trailing - * If false, whitespace is skipped until the first line break and comments between that location - * and the next token are returned. - * If true, comments occurring between the given position and the next line break are returned. + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. */ - function getCommentRanges(text, pos, trailing) { - var result; + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; var collecting = trailing || pos === 0; - while (pos < text.length) { + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13 /* carriageReturn */: @@ -3899,11 +4639,11 @@ var ts; case 10 /* lineFeed */: pos++; if (trailing) { - return result; + break scan; } collecting = true; - if (result && result.length) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; } continue; case 9 /* tab */: @@ -3938,34 +4678,68 @@ var ts; } } if (collecting) { - if (!result) { - result = []; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. + return accumulator; + } + hasPendingCommentRange = false; } - result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; } continue; } - break; + break scan; default: if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch))) { - if (result && result.length && isLineBreak(ch)) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; } pos++; continue; } - break; + break scan; } - return result; } - return result; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + if (!comments) { + comments = []; + } + comments.push({ pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + return comments; } function getLeadingCommentRanges(text, pos) { - return getCommentRanges(text, pos, /*trailing*/ false); + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getLeadingCommentRanges = getLeadingCommentRanges; function getTrailingCommentRanges(text, pos) { - return getCommentRanges(text, pos, /*trailing*/ true); + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ @@ -3988,7 +4762,7 @@ var ts; } ts.isIdentifierPart = isIdentifierPart; /* @internal */ - function isIdentifier(name, languageVersion) { + function isIdentifierText(name, languageVersion) { if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { return false; } @@ -3999,7 +4773,7 @@ var ts; } return true; } - ts.isIdentifier = isIdentifier; + ts.isIdentifierText = isIdentifierText; // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } @@ -4033,6 +4807,7 @@ var ts; reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, scanJSDocToken: scanJSDocToken, @@ -4124,7 +4899,8 @@ var ts; } return value; } - function scanString() { + function scanString(allowEscapes) { + if (allowEscapes === void 0) { allowEscapes = true; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -4142,7 +4918,7 @@ var ts; pos++; break; } - if (ch === 92 /* backslash */) { + if (ch === 92 /* backslash */ && allowEscapes) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; @@ -4887,43 +5663,62 @@ var ts; } return token; } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*allowEscapes*/ false); + return token = 9 /* StringLiteral */; + default: + // If this scans anything other than `{`, it's a parse error. + return scan(); + } + } function scanJSDocToken() { if (pos >= end) { return token = 1 /* EndOfFileToken */; } startPos = pos; - // Eat leading whitespace - var ch = text.charCodeAt(pos); - while (pos < end) { - ch = text.charCodeAt(pos); - if (isWhiteSpaceSingleLine(ch)) { - pos++; - } - else { - break; - } - } tokenPos = pos; + var ch = text.charCodeAt(pos); switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - return pos += 1, token = 55 /* AtToken */; + pos++; + return token = 55 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - return pos += 1, token = 4 /* NewLineTrivia */; + pos++; + return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - return pos += 1, token = 37 /* AsteriskToken */; + pos++; + return token = 37 /* AsteriskToken */; case 123 /* openBrace */: - return pos += 1, token = 15 /* OpenBraceToken */; + pos++; + return token = 15 /* OpenBraceToken */; case 125 /* closeBrace */: - return pos += 1, token = 16 /* CloseBraceToken */; + pos++; + return token = 16 /* CloseBraceToken */; case 91 /* openBracket */: - return pos += 1, token = 19 /* OpenBracketToken */; + pos++; + return token = 19 /* OpenBracketToken */; case 93 /* closeBracket */: - return pos += 1, token = 20 /* CloseBracketToken */; + pos++; + return token = 20 /* CloseBracketToken */; case 61 /* equals */: - return pos += 1, token = 56 /* EqualsToken */; + pos++; + return token = 56 /* EqualsToken */; case 44 /* comma */: - return pos += 1, token = 24 /* CommaToken */; + pos++; + return token = 24 /* CommaToken */; } if (isIdentifierStart(ch, 2 /* Latest */)) { pos++; @@ -5020,6 +5815,7 @@ var ts; /* @internal */ var ts; (function (ts) { + ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -5070,24 +5866,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function mapIsEqualTo(map1, map2) { - if (!map1 || !map2) { - return map1 === map2; - } - return containsAll(map1, map2) && containsAll(map2, map1); - } - ts.mapIsEqualTo = mapIsEqualTo; - function containsAll(map, other) { - for (var key in map) { - if (!ts.hasProperty(map, key)) { - continue; - } - if (!ts.hasProperty(other, key) || map[key] !== other[key]) { - return false; - } - } - return true; - } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -5105,7 +5883,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5114,14 +5892,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = {}; + sourceFile.resolvedModules = ts.createMap(); } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = {}; + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -5143,7 +5921,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; + var oldResolution = oldResolutions && oldResolutions[names[i]]; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -5157,24 +5935,24 @@ var ts; // Returns true if this node contains a parse error anywhere underneath it. function containsParseError(node) { aggregateChildData(node); - return (node.flags & 268435456 /* ThisNodeOrAnySubNodesHasError */) !== 0; + return (node.flags & 2097152 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 536870912 /* HasAggregatedChildData */)) { + if (!(node.flags & 4194304 /* HasAggregatedChildData */)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. - var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864 /* ThisNodeHasError */) !== 0) || + var thisNodeOrAnySubNodesHasError = ((node.flags & 524288 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.flags |= 268435456 /* ThisNodeOrAnySubNodesHasError */; + node.flags |= 2097152 /* ThisNodeOrAnySubNodesHasError */; } // Also mark that we've propagated the child information to this node. This way we can // always consult the bit directly on this node without needing to check its children // again. - node.flags |= 536870912 /* HasAggregatedChildData */; + node.flags |= 4194304 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { @@ -5212,6 +5990,10 @@ var ts; return node.pos; } ts.getStartPosOfNode = getStartPosOfNode; + function isDefined(value) { + return value !== undefined; + } + ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -5251,7 +6033,7 @@ var ts; // However, this node will be 'missing' in the sense that no actual source-code/tokens are // contained within it. function nodeIsMissing(node) { - if (!node) { + if (node === undefined) { return true; } return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; @@ -5277,16 +6059,20 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 282 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 281 /* LastJSDocNode */; + return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 282 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; + function isJSDocTag(node) { + return node.kind >= 273 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5315,6 +6101,56 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getLiteralText(node, sourceFile, languageVersion) { + // Any template literal or string literal with an extended escape + // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. + if (languageVersion < 2 /* ES6 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + return getQuotedEscapedLiteralText('"', node.text, '"'); + } + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (!nodeIsSynthesized(node) && node.parent) { + var text = getSourceTextOfNodeFromSourceFile(sourceFile, node); + if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { + return node.text; + } + return text; + } + // If we can't reach the original source text, use the canonical form if it's a number, + // or an escaped quoted form of the original text if it's string-like. + switch (node.kind) { + case 9 /* StringLiteral */: + return getQuotedEscapedLiteralText('"', node.text, '"'); + case 11 /* NoSubstitutionTemplateLiteral */: + return getQuotedEscapedLiteralText("`", node.text, "`"); + case 12 /* TemplateHead */: + return getQuotedEscapedLiteralText("`", node.text, "${"); + case 13 /* TemplateMiddle */: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 14 /* TemplateTail */: + return getQuotedEscapedLiteralText("}", node.text, "`"); + case 8 /* NumericLiteral */: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function isBinaryOrOctalIntegerLiteral(node, text) { + if (node.kind === 8 /* NumericLiteral */ && text.length > 1) { + switch (text.charCodeAt(1)) { + case 98 /* b */: + case 66 /* B */: + case 111 /* o */: + case 79 /* O */: + return true; + } + } + return false; + } + ts.isBinaryOrOctalIntegerLiteral = isBinaryOrOctalIntegerLiteral; + function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { + return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + } // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -5332,7 +6168,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 3072 /* BlockScoped */) !== 0 || + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -5341,20 +6177,22 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. return node.kind === 225 /* ModuleDeclaration */ && (!node.body); } - ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || - isFunctionLike(node) || - isFunctionBlock(node); + isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { - return !!(module.flags & 131072 /* GlobalAugmentation */); + return !!(module.flags & 512 /* GlobalAugmentation */); } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { @@ -5373,30 +6211,39 @@ var ts; return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 256 /* SourceFile */: + case 227 /* CaseBlock */: + case 252 /* CatchClause */: + case 225 /* ModuleDeclaration */: + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + case 148 /* Constructor */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + return true; + case 199 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + return parentNode && !isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { - if (isFunctionLike(current)) { + if (isBlockScope(current, current.parent)) { return current; } - switch (current.kind) { - case 256 /* SourceFile */: - case 227 /* CaseBlock */: - case 252 /* CatchClause */: - case 225 /* ModuleDeclaration */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - return current; - case 199 /* Block */: - // function block is not considered block-scope container - // see comment in binder.ts: bind(...), case for SyntaxKind.Block - if (!isFunctionLike(current.parent)) { - return current; - } - } current = current.parent; } } @@ -5508,41 +6355,13 @@ var ts; return node.kind === 224 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 /* BindingElement */ || isBindingPattern(node))) { - node = node.parent; - } - return node; - } - // Returns the node flags for this node and all relevant parent nodes. This is done so that - // nodes like variable declarations and binding elements can returned a view of their flags - // that includes the modifiers from their container. i.e. flags like export/declare aren't - // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration - // list. By calling this function, all those flags are combined so that the client can treat - // the node as if it actually had those flags. - function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 218 /* VariableDeclaration */) { - node = node.parent; - } - if (node && node.kind === 219 /* VariableDeclarationList */) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 200 /* VariableStatement */) { - flags |= node.flags; - } - return flags; - } - ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 2048 /* Const */); + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */) + || !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 1024 /* Let */); + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; function isSuperCallExpression(n) { @@ -5584,7 +6403,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; - function isTypeNode(node) { + function isPartOfTypeNode(node) { if (154 /* FirstTypeNode */ <= node.kind && node.kind <= 166 /* LastTypeNode */) { return true; } @@ -5612,7 +6431,7 @@ var ts; node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 139 /* QualifiedName */: case 172 /* PropertyAccessExpression */: case 97 /* ThisKeyword */: @@ -5620,11 +6439,11 @@ var ts; if (parent_1.kind === 158 /* TypeQuery */) { return false; } - // Do not recursively call isTypeNode on the parent. In the example: + // Do not recursively call isPartOfTypeNode on the parent. In the example: // // let a: A.B.C; // - // Calling isTypeNode would consider the qualified name A.B a type node. Only C or + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. if (154 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 166 /* LastTypeNode */) { return true; @@ -5664,7 +6483,7 @@ var ts; } return false; } - ts.isTypeNode = isTypeNode; + ts.isPartOfTypeNode = isPartOfTypeNode; // Warning: This has the same semantics as the forEach family of functions, // in that traversal terminates in the event that 'visitor' supplies a truthy value. function forEachReturnStatement(body, visitor) { @@ -5723,7 +6542,7 @@ var ts; return; } } - else if (!isTypeNode(node)) { + else if (!isPartOfTypeNode(node)) { // This is the general case, which should include mostly expressions and statements. // Also includes NodeArrays. ts.forEachChild(node, traverse); @@ -5969,18 +6788,19 @@ var ts; /** * Determines whether a node is a property or element access expression for super. */ - function isSuperPropertyOrElementAccess(node) { - return (node.kind === 172 /* PropertyAccessExpression */ - || node.kind === 173 /* ElementAccessExpression */) + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 172 /* PropertyAccessExpression */ || kind === 173 /* ElementAccessExpression */) && node.expression.kind === 95 /* SuperKeyword */; } - ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; + ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { case 155 /* TypeReference */: return node.typeName; case 194 /* ExpressionWithTypeArguments */: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69 /* Identifier */: case 139 /* QualifiedName */: @@ -5990,6 +6810,18 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function isCallLikeExpression(node) { + switch (node.kind) { + case 174 /* CallExpression */: + case 175 /* NewExpression */: + case 176 /* TaggedTemplateExpression */: + case 143 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { if (node.kind === 176 /* TaggedTemplateExpression */) { return node.tag; @@ -6028,14 +6860,20 @@ var ts; && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function isPropertyAccessExpression(node) { - return node.kind === 172 /* PropertyAccessExpression */; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isElementAccessExpression(node) { - return node.kind === 173 /* ElementAccessExpression */; + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 221 /* ClassDeclaration */: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 147 /* MethodDeclaration */: + case 150 /* SetAccessor */: + return ts.forEach(node.parameters, nodeIsDecorated); + } } - ts.isElementAccessExpression = isElementAccessExpression; + ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; if (parent.kind === 243 /* JsxOpeningElement */ || @@ -6046,7 +6884,7 @@ var ts; return false; } ts.isJSXTagName = isJSXTagName; - function isExpression(node) { + function isPartOfExpression(node) { switch (node.kind) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: @@ -6142,18 +6980,18 @@ var ts; case 194 /* ExpressionWithTypeArguments */: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: - if (isExpression(parent_3)) { + if (isPartOfExpression(parent_3)) { return true; } } } return false; } - ts.isExpression = isExpression; + ts.isPartOfExpression = isPartOfExpression; function isExternalModuleNameRelative(moduleName) { // TypeScript 1.0 spec (April 2014): 11.2.1 // An external module name is "relative" if the first term is "." or "..". - return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + return /^\.\.?($|[\\/])/.test(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { @@ -6180,7 +7018,7 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 134217728 /* JavaScriptFile */); + return node && !!(node.flags & 1048576 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; /** @@ -6276,6 +7114,22 @@ var ts; } } ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + if (node.kind === 229 /* ImportEqualsDeclaration */) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232 /* NamespaceImport */) { + return importClause.namedBindings; + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 230 /* ImportDeclaration */ + && node.importClause + && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { @@ -6302,37 +7156,71 @@ var ts; if (!node) { return undefined; } - var jsDocComments = getJSDocComments(node, checkParentVariableStatement); - if (!jsDocComments) { + var jsDocTags = getJSDocTags(node, checkParentVariableStatement); + if (!jsDocTags) { return undefined; } - for (var _i = 0, jsDocComments_1 = jsDocComments; _i < jsDocComments_1.length; _i++) { - var jsDocComment = jsDocComments_1[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === kind) { - return tag; - } + for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { + var tag = jsDocTags_1[_i]; + if (tag.kind === kind) { + return tag; } } } - function getJSDocComments(node, checkParentVariableStatement) { - if (node.jsDocComments) { - return node.jsDocComments; + function append(previous, additional) { + if (additional) { + if (!previous) { + previous = []; + } + for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { + var x = additional_1[_i]; + previous.push(x); + } } - // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. - // /** - // * @param {number} name - // * @returns {number} - // */ - // var x = function(name) { return name.length; } + return previous; + } + function getJSDocComments(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); + } + ts.getJSDocComments = getJSDocComments; + function getJSDocTags(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { + var result = []; + for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { + var doc = docs_1[_i]; + if (doc.tags) { + result.push.apply(result, doc.tags); + } + } + return result; + }, function (tags) { return tags; }); + } + function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { + // TODO: Get rid of getJsDocComments and friends (note the lowercase 's' in Js) + // TODO: A lot of this work should be cached, maybe. I guess it's only used in services right now... + var result = undefined; + // prepend documentation from parent sources if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 218 /* VariableDeclaration */ && - node.parent.initializer === node && + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && + (node.parent).initializer === node && node.parent.parent.parent.kind === 200 /* VariableStatement */; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + var isVariableOfVariableDeclarationStatement = isVariableLike(node) && + node.parent.parent.kind === 200 /* VariableStatement */; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : + isVariableOfVariableDeclarationStatement ? node.parent.parent : + undefined; if (variableStatementNode) { - return variableStatementNode.jsDocComments; + result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 225 /* ModuleDeclaration */ && + node.parent && node.parent.kind === 225 /* ModuleDeclaration */) { + result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } // Also recognize when the node is the RHS of an assignment expression var parent_4 = node.parent; @@ -6341,14 +7229,56 @@ var ts; parent_4.operatorToken.kind === 56 /* EqualsToken */ && parent_4.parent.kind === 202 /* ExpressionStatement */; if (isSourceOfAssignmentExpressionStatement) { - return parent_4.parent.jsDocComments; + result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); } var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253 /* PropertyAssignment */; if (isPropertyAssignmentExpression) { - return parent_4.jsDocComments; + result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + } + // Pull parameter comments from declaring function as well + if (node.kind === 142 /* Parameter */) { + var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); + if (paramTags) { + result = append(result, getTags(paramTags)); + } } } - return undefined; + if (isVariableLike(node) && node.initializer) { + result = append(result, getJSDocs(node.initializer, /*checkParentVariableStatement*/ false, getDocs, getTags)); + } + if (node.jsDocComments) { + if (result) { + result = append(result, getDocs(node.jsDocComments)); + } + else { + return getDocs(node.jsDocComments); + } + } + return result; + } + function getJSDocParameterTag(param, checkParentVariableStatement) { + var func = param.parent; + var tags = getJSDocTags(func, checkParentVariableStatement); + if (!param.name) { + // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification + var i = func.parameters.indexOf(param); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */; }); + if (paramTags && 0 <= i && i < paramTags.length) { + return [paramTags[i]]; + } + } + else if (param.name.kind === 69 /* Identifier */) { + var name_6 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */ && tag.parameterName.text === name_6; }); + if (paramTags) { + return paramTags; + } + } + else { + // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines + // But multi-line object types aren't supported yet either + return undefined; + } } function getJSDocTypeTag(node) { return getJSDocTag(node, 277 /* JSDocTypeTag */, /*checkParentVariableStatement*/ false); @@ -6367,19 +7297,16 @@ var ts; // If it's a parameter, see if the parent has a jsdoc comment with an @param // annotation. var parameterName = parameter.name.text; - var jsDocComments = getJSDocComments(parameter.parent, /*checkParentVariableStatement*/ true); - if (jsDocComments) { - for (var _i = 0, jsDocComments_2 = jsDocComments; _i < jsDocComments_2.length; _i++) { - var jsDocComment = jsDocComments_2[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === 275 /* JSDocParameterTag */) { - var parameterTag = tag; - var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_6.text === parameterName) { - return parameterTag; - } - } + var jsDocTags = getJSDocTags(parameter.parent, /*checkParentVariableStatement*/ true); + if (!jsDocTags) { + return undefined; + } + for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { + var tag = jsDocTags_2[_i]; + if (tag.kind === 275 /* JSDocParameterTag */) { + var parameterTag = tag; + if (parameterTag.parameterName.text === parameterName) { + return parameterTag; } } } @@ -6396,7 +7323,7 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 134217728 /* JavaScriptFile */)) { + if (node && (node.flags & 1048576 /* JavaScriptFile */)) { if (node.type && node.type.kind === 270 /* JSDocVariadicType */) { return true; } @@ -6412,22 +7339,6 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isTemplateLiteralKind(kind) { - return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isBindingPattern(node) { - return !!node && (node.kind === 168 /* ArrayBindingPattern */ || node.kind === 167 /* ObjectBindingPattern */); - } - ts.isBindingPattern = isBindingPattern; // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. @@ -6446,14 +7357,14 @@ var ts; continue; } return parent_5.kind === 187 /* BinaryExpression */ && - parent_5.operatorToken.kind === 56 /* EqualsToken */ && + isAssignmentOperator(parent_5.operatorToken.kind) && parent_5.left === node || (parent_5.kind === 207 /* ForInStatement */ || parent_5.kind === 208 /* ForOfStatement */) && parent_5.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; - function isNodeDescendentOf(node, ancestor) { + function isNodeDescendantOf(node, ancestor) { while (node) { if (node === ancestor) return true; @@ -6461,10 +7372,10 @@ var ts; } return false; } - ts.isNodeDescendentOf = isNodeDescendentOf; + ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (node.flags & 2 /* Ambient */ || (node.kind === 256 /* SourceFile */ && node.isDeclarationFile)) { + if (hasModifier(node, 2 /* Ambient */) || (node.kind === 256 /* SourceFile */ && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6472,84 +7383,6 @@ var ts; return false; } ts.isInAmbientContext = isInAmbientContext; - function isDeclaration(node) { - switch (node.kind) { - case 180 /* ArrowFunction */: - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 148 /* Constructor */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 238 /* ExportSpecifier */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 149 /* GetAccessor */: - case 231 /* ImportClause */: - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 222 /* InterfaceDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 225 /* ModuleDeclaration */: - case 232 /* NamespaceImport */: - case 142 /* Parameter */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 150 /* SetAccessor */: - case 254 /* ShorthandPropertyAssignment */: - case 223 /* TypeAliasDeclaration */: - case 141 /* TypeParameter */: - case 218 /* VariableDeclaration */: - case 279 /* JSDocTypedefTag */: - return true; - } - return false; - } - ts.isDeclaration = isDeclaration; - function isStatement(n) { - switch (n.kind) { - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: - case 217 /* DebuggerStatement */: - case 204 /* DoStatement */: - case 202 /* ExpressionStatement */: - case 201 /* EmptyStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 206 /* ForStatement */: - case 203 /* IfStatement */: - case 214 /* LabeledStatement */: - case 211 /* ReturnStatement */: - case 213 /* SwitchStatement */: - case 215 /* ThrowStatement */: - case 216 /* TryStatement */: - case 200 /* VariableStatement */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 235 /* ExportAssignment */: - return true; - default: - return false; - } - } - ts.isStatement = isStatement; - function isClassElement(n) { - switch (n.kind) { - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - return true; - default: - return false; - } - } - ts.isClassElement = isClassElement; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { if (name.kind !== 69 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { @@ -6614,8 +7447,8 @@ var ts; // import * as from ... // import { x as } from ... // export { x as } from ... - // export = ... - // export default ... + // export = + // export default function isAliasSymbolDeclaration(node) { return node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 228 /* NamespaceExportDeclaration */ || @@ -6623,9 +7456,13 @@ var ts; node.kind === 232 /* NamespaceImport */ || node.kind === 234 /* ImportSpecifier */ || node.kind === 238 /* ExportSpecifier */ || - node.kind === 235 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; + node.kind === 235 /* ExportAssignment */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + return isEntityNameExpression(node.expression); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -6713,7 +7550,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node); + return isFunctionLike(node) && hasModifier(node, 256 /* Async */) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; function isStringOrNumericLiteral(kind) { @@ -6804,80 +7641,250 @@ var ts; return node; } ts.getRootDeclaration = getRootDeclaration; - function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 225 /* ModuleDeclaration */ || n.kind === 256 /* SourceFile */; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 148 /* Constructor */ + || kind === 179 /* FunctionExpression */ + || kind === 220 /* FunctionDeclaration */ + || kind === 180 /* ArrowFunction */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 225 /* ModuleDeclaration */ + || kind === 256 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - /** - * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" - * properties are excluded by default, and can be provided via the "location", "flags", and - * "parent" parameters. - * @param node The node to clone. - * @param location An optional TextRange to use to supply the new position. - * @param flags The NodeFlags to use for the cloned node. - * @param parent The parent for the new node. - */ - function cloneNode(node, location, flags, parent) { - // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of - // the original node. We also need to exclude specific properties and only include own- - // properties (to skip members already defined on the shared prototype). - var clone = location !== undefined - ? ts.createNode(node.kind, location.pos, location.end) - : createSynthesizedNode(node.kind); - for (var key in node) { - if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { - continue; - } - clone[key] = node[key]; - } - if (flags !== undefined) { - clone.flags = flags; - } - if (parent !== undefined) { - clone.parent = parent; - } - return clone; - } - ts.cloneNode = cloneNode; - /** - * Creates a deep clone of an EntityName, with new parent pointers. - * @param node The EntityName to clone. - * @param parent The parent for the cloned node. - */ - function cloneEntityName(node, parent) { - var clone = cloneNode(node, node, node.flags, parent); - if (isQualifiedName(clone)) { - var left = clone.left, right = clone.right; - clone.left = cloneEntityName(left, clone); - clone.right = cloneNode(right, right, right.flags, parent); - } - return clone; - } - ts.cloneEntityName = cloneEntityName; - function isQualifiedName(node) { - return node.kind === 139 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { - return node.pos === -1; + return positionIsSynthesized(node.pos) + || positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function createSynthesizedNode(kind, startsOnNewLine) { - var node = ts.createNode(kind, /* pos */ -1, /* end */ -1); - node.startsOnNewLine = startsOnNewLine; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function getOriginalNode(node) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } return node; } - ts.createSynthesizedNode = createSynthesizedNode; - function createSynthesizedNodeArray() { - var array = []; - array.pos = -1; - array.end = -1; - return array; + ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node) { + return (node.flags & 8 /* Synthesized */) === 0; } - ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function getOriginalSourceFiles(sourceFiles) { + var originalSourceFiles = []; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + var originalSourceFile = getParseTreeNode(sourceFile, isSourceFile); + if (originalSourceFile) { + originalSourceFiles.push(originalSourceFile); + } + } + return originalSourceFiles; + } + ts.getOriginalSourceFiles = getOriginalSourceFiles; + function getOriginalNodeId(node) { + node = getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(ts.Associativity || (ts.Associativity = {})); + var Associativity = ts.Associativity; + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 175 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 185 /* PrefixUnaryExpression */: + case 182 /* TypeOfExpression */: + case 183 /* VoidExpression */: + case 181 /* DeleteExpression */: + case 184 /* AwaitExpression */: + case 188 /* ConditionalExpression */: + case 190 /* YieldExpression */: + return 1 /* Right */; + case 187 /* BinaryExpression */: + switch (operator) { + case 38 /* AsteriskAsteriskToken */: + case 56 /* EqualsToken */: + case 57 /* PlusEqualsToken */: + case 58 /* MinusEqualsToken */: + case 60 /* AsteriskAsteriskEqualsToken */: + case 59 /* AsteriskEqualsToken */: + case 61 /* SlashEqualsToken */: + case 62 /* PercentEqualsToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* AmpersandEqualsToken */: + case 68 /* CaretEqualsToken */: + case 67 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 187 /* BinaryExpression */) { + return expression.operatorToken.kind; + } + else if (expression.kind === 185 /* PrefixUnaryExpression */ || expression.kind === 186 /* PostfixUnaryExpression */) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 97 /* ThisKeyword */: + case 95 /* SuperKeyword */: + case 69 /* Identifier */: + case 93 /* NullKeyword */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 170 /* ArrayLiteralExpression */: + case 171 /* ObjectLiteralExpression */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 192 /* ClassExpression */: + case 241 /* JsxElement */: + case 242 /* JsxSelfClosingElement */: + case 10 /* RegularExpressionLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 189 /* TemplateExpression */: + case 178 /* ParenthesizedExpression */: + case 193 /* OmittedExpression */: + return 19; + case 176 /* TaggedTemplateExpression */: + case 172 /* PropertyAccessExpression */: + case 173 /* ElementAccessExpression */: + return 18; + case 175 /* NewExpression */: + return hasArguments ? 18 : 17; + case 174 /* CallExpression */: + return 17; + case 186 /* PostfixUnaryExpression */: + return 16; + case 185 /* PrefixUnaryExpression */: + case 182 /* TypeOfExpression */: + case 183 /* VoidExpression */: + case 181 /* DeleteExpression */: + case 184 /* AwaitExpression */: + return 15; + case 187 /* BinaryExpression */: + switch (operatorKind) { + case 49 /* ExclamationToken */: + case 50 /* TildeToken */: + return 15; + case 38 /* AsteriskAsteriskToken */: + case 37 /* AsteriskToken */: + case 39 /* SlashToken */: + case 40 /* PercentToken */: + return 14; + case 35 /* PlusToken */: + case 36 /* MinusToken */: + return 13; + case 43 /* LessThanLessThanToken */: + case 44 /* GreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 25 /* LessThanToken */: + case 28 /* LessThanEqualsToken */: + case 27 /* GreaterThanToken */: + case 29 /* GreaterThanEqualsToken */: + case 90 /* InKeyword */: + case 91 /* InstanceOfKeyword */: + return 11; + case 30 /* EqualsEqualsToken */: + case 32 /* EqualsEqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + return 10; + case 46 /* AmpersandToken */: + return 9; + case 48 /* CaretToken */: + return 8; + case 47 /* BarToken */: + return 7; + case 51 /* AmpersandAmpersandToken */: + return 6; + case 52 /* BarBarToken */: + return 5; + case 56 /* EqualsToken */: + case 57 /* PlusEqualsToken */: + case 58 /* MinusEqualsToken */: + case 60 /* AsteriskAsteriskEqualsToken */: + case 59 /* AsteriskEqualsToken */: + case 61 /* SlashEqualsToken */: + case 62 /* PercentEqualsToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* AmpersandEqualsToken */: + case 68 /* CaretEqualsToken */: + case 67 /* BarEqualsToken */: + return 3; + case 24 /* CommaToken */: + return 0; + default: + return -1; + } + case 188 /* ConditionalExpression */: + return 4; + case 190 /* YieldExpression */: + return 2; + case 191 /* SpreadElementExpression */: + return 1; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6930,9 +7937,7 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); - } + ts.forEach(fileDiagnostics[key], pushDiagnostic); } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -6943,9 +7948,7 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); - } + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } } } @@ -6956,7 +7959,7 @@ var ts; // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { + var escapedCharsMap = ts.createMap({ "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -6969,7 +7972,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine - }; + }); /** * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) @@ -7079,10 +8082,23 @@ var ts; getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, reset: reset }; } ts.createTextWriter = createTextWriter; + function getResolvedExternalModuleName(host, file) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; /** * Resolves a local path to a path which is absolute to the base of the emit */ @@ -7127,6 +8143,105 @@ var ts; getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; } ts.getEmitModuleKind = getEmitModuleKind; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + var moduleKind = getEmitModuleKind(options); + var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var sourceFiles = host.getSourceFiles(); + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, isNonDeclarationFile); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function isNonDeclarationFile(sourceFile) { + return !isDeclarationFile(sourceFile); + } + function isBundleEmitNonExternalModule(sourceFile) { + return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + /** + * Iterates over each source file to emit. The source files are expected to have been + * transformed for use by the pretty printer. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param sourceFiles The transformed source files to emit. + * @param action The action to execute. + */ + function forEachTransformedEmitFile(host, sourceFiles, action) { + var options = host.getCompilerOptions(); + // Emit on each source file + if (options.outFile || options.out) { + onBundledEmit(host, sourceFiles); + } + else { + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + // Don't emit if source file is a declaration file, or was located under node_modules + if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + var extension = ".js"; + if (options.jsx === 1 /* Preserve */) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); + } + function onBundledEmit(host, sourceFiles) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, /*isBundledEmit*/ true); + } + } + } + ts.forEachTransformedEmitFile = forEachTransformedEmitFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + /** + * Iterates over the source files that are expected to have an emit output. This function + * is used by the legacy emitter and the declaration emitter and should not be used by + * the tree transforming emitter. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param targetSourceFile An optional target source file to emit. + */ function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); // Emit on each source file @@ -7135,8 +8250,8 @@ var ts; } else { var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; // Don't emit if source file is a declaration file, or was located under node_modules if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { onSingleFileEmit(host, sourceFile); @@ -7184,9 +8299,6 @@ var ts; action(emitFileNames, bundledSources, /*isBundledEmit*/ true); } } - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } } ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { @@ -7248,7 +8360,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 149 /* GetAccessor */ || member.kind === 150 /* SetAccessor */) - && (member.flags & 32 /* Static */) === (accessor.flags & 32 /* Static */)) { + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -7277,32 +8389,49 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { // If the leading comments start on different line than the start of node, write new line - if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } - ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { - var emitLeadingSpace = !trailingSeparator; - ts.forEach(comments, function (comment) { - if (emitLeadingSpace) { - writer.write(" "); - emitLeadingSpace = false; - } - writeComment(text, lineMap, writer, comment, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - else if (trailingSeparator) { + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { writer.write(" "); } - else { - // Emit leading space to separate comment during next comment emit - emitLeadingSpace = true; + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.write(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } } - }); + if (emitInterveningSeparator && trailingSeparator) { + writer.write(" "); + } + } } ts.emitComments = emitComments; /** @@ -7353,7 +8482,7 @@ var ts; if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } @@ -7365,19 +8494,19 @@ var ts; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(text, lineMap, writer, comment, newLine) { - if (text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); var lineCount = lineMap.length; var firstCommentLineIndent = void 0; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount ? text.length + 1 : lineMap[currentLine + 1]; - if (pos !== comment.pos) { + if (pos !== commentPos) { // If we are not emitting first line, we need to write the spaces to adjust the alignment if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); } // These are number of spaces writer is going to write at current indent var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); @@ -7413,23 +8542,23 @@ var ts; } } // Write the comment line text - writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { // Single line comment of style //.... - writer.write(text.substring(comment.pos, comment.end)); + writer.write(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; - function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text writer.write(currentLineText); - if (end !== comment.end) { + if (end !== commentEnd) { writer.writeLine(); } } @@ -7452,6 +8581,32 @@ var ts; } return currentLineIndent; } + function hasModifiers(node) { + return getModifierFlags(node) !== 0 /* None */; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return (getModifierFlags(node) & flags) !== 0; + } + ts.hasModifier = hasModifier; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; + } + var flags = 0 /* None */; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 /* NestedNamespace */) { + flags |= 1 /* Export */; + } + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { case 113 /* StaticKeyword */: return 32 /* Static */; @@ -7466,52 +8621,39 @@ var ts; case 118 /* AsyncKeyword */: return 256 /* Async */; case 128 /* ReadonlyKeyword */: return 64 /* Readonly */; } - return 0; + return 0 /* None */; } ts.modifierToFlag = modifierToFlag; - function isLeftHandSideExpression(expr) { - if (expr) { - switch (expr.kind) { - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: - case 175 /* NewExpression */: - case 174 /* CallExpression */: - case 196 /* NonNullExpression */: - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 176 /* TaggedTemplateExpression */: - case 170 /* ArrayLiteralExpression */: - case 178 /* ParenthesizedExpression */: - case 171 /* ObjectLiteralExpression */: - case 192 /* ClassExpression */: - case 179 /* FunctionExpression */: - case 69 /* Identifier */: - case 10 /* RegularExpressionLiteral */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 189 /* TemplateExpression */: - case 84 /* FalseKeyword */: - case 93 /* NullKeyword */: - case 97 /* ThisKeyword */: - case 99 /* TrueKeyword */: - case 95 /* SuperKeyword */: - return true; - } - } - return false; + function isLogicalOperator(token) { + return token === 52 /* BarBarToken */ + || token === 51 /* AmpersandAmpersandToken */ + || token === 49 /* ExclamationToken */; } - ts.isLeftHandSideExpression = isLeftHandSideExpression; + ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { return token >= 56 /* FirstAssignment */ && token <= 68 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; - function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 194 /* ExpressionWithTypeArguments */ && + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ + function tryGetClassExtendingExpressionWithTypeArguments(node) { + if (node.kind === 194 /* ExpressionWithTypeArguments */ && node.parent.token === 83 /* ExtendsKeyword */ && - isClassLike(node.parent.parent); + isClassLike(node.parent.parent)) { + return node.parent.parent; + } } - ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isDestructuringAssignment(node) { + if (isBinaryExpression(node)) { + if (node.operatorToken.kind === 56 /* EqualsToken */) { + var kind = node.left.kind; + return kind === 171 /* ObjectLiteralExpression */ + || kind === 170 /* ArrayLiteralExpression */; + } + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; // Returns false if this heritage clause element's expression contains something unsupported // (i.e. not a name or dotted name). function isSupportedExpressionWithTypeArguments(node) { @@ -7529,6 +8671,15 @@ var ts; return false; } } + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 69 /* Identifier */ || + node.kind === 172 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + } + ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) || (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node); @@ -7546,7 +8697,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { @@ -7557,6 +8708,11 @@ var ts; return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ + function tryExtractTypeScriptExtension(fileName) { + return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -7626,7 +8782,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -7685,6 +8841,847 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; + /** + * Tests whether a node and its subtree is simple enough to have its position + * information ignored when emitting source maps in a destructuring assignment. + * + * @param node The expression to test. + */ + function isSimpleExpression(node) { + return isSimpleExpressionWorker(node, 0); + } + ts.isSimpleExpression = isSimpleExpression; + function isSimpleExpressionWorker(node, depth) { + if (depth <= 5) { + var kind = node.kind; + if (kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 10 /* RegularExpressionLiteral */ + || kind === 11 /* NoSubstitutionTemplateLiteral */ + || kind === 69 /* Identifier */ + || kind === 97 /* ThisKeyword */ + || kind === 95 /* SuperKeyword */ + || kind === 99 /* TrueKeyword */ + || kind === 84 /* FalseKeyword */ + || kind === 93 /* NullKeyword */) { + return true; + } + else if (kind === 172 /* PropertyAccessExpression */) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 173 /* ElementAccessExpression */) { + return isSimpleExpressionWorker(node.expression, depth + 1) + && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + } + else if (kind === 185 /* PrefixUnaryExpression */ + || kind === 186 /* PostfixUnaryExpression */) { + return isSimpleExpressionWorker(node.operand, depth + 1); + } + else if (kind === 187 /* BinaryExpression */) { + return node.operatorToken.kind !== 38 /* AsteriskAsteriskToken */ + && isSimpleExpressionWorker(node.left, depth + 1) + && isSimpleExpressionWorker(node.right, depth + 1); + } + else if (kind === 188 /* ConditionalExpression */) { + return isSimpleExpressionWorker(node.condition, depth + 1) + && isSimpleExpressionWorker(node.whenTrue, depth + 1) + && isSimpleExpressionWorker(node.whenFalse, depth + 1); + } + else if (kind === 183 /* VoidExpression */ + || kind === 182 /* TypeOfExpression */ + || kind === 181 /* DeleteExpression */) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 170 /* ArrayLiteralExpression */) { + return node.elements.length === 0; + } + else if (kind === 171 /* ObjectLiteralExpression */) { + return node.properties.length === 0; + } + else if (kind === 174 /* CallExpression */) { + if (!isSimpleExpressionWorker(node.expression, depth + 1)) { + return false; + } + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (!isSimpleExpressionWorker(argument, depth + 1)) { + return false; + } + } + return true; + } + } + return false; + } + var syntaxKindCache = ts.createMap(); + function formatSyntaxKind(kind) { + var syntaxKindEnum = ts.SyntaxKind; + if (syntaxKindEnum) { + if (syntaxKindCache[kind]) { + return syntaxKindCache[kind]; + } + for (var name_7 in syntaxKindEnum) { + if (syntaxKindEnum[name_7] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_7 + ")"; + } + } + } + else { + return kind.toString(); + } + } + ts.formatSyntaxKind = formatSyntaxKind; + /** + * Increases (or decreases) a position by the provided amount. + * + * @param pos The position. + * @param value The delta. + */ + function movePos(pos, value) { + return positionIsSynthesized(pos) ? -1 : pos + value; + } + ts.movePos = movePos; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ + function createRange(pos, end) { + return { pos: pos, end: end }; + } + ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange from a provided range with its end position collapsed to its + * start position. + * + * @param range A TextRange. + */ + function collapseRangeToStart(range) { + return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); + } + ts.collapseRangeToStart = collapseRangeToStart; + /** + * Creates a new TextRange from a provided range with its start position collapsed to its + * end position. + * + * @param range A TextRange. + */ + function collapseRangeToEnd(range) { + return isCollapsedRange(range) ? range : moveRangePos(range, range.end); + } + ts.collapseRangeToEnd = collapseRangeToEnd; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function collectExternalModuleInfo(sourceFile, resolver) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 230 /* ImportDeclaration */: + if (!node.importClause || + resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { + // import "mod" + // import x from "mod" where x is referenced + // import * as x from "mod" where x is referenced + // import { x, y } from "mod" where at least one import is referenced + externalImports.push(node); + } + break; + case 229 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 240 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + // import x = require("mod") where x is referenced + externalImports.push(node); + } + break; + case 236 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + } + else if (resolver.isValueAliasDeclaration(node)) { + // export { x, y } from "mod" where at least one export is a value symbol + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + var name_8 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_8] || (exportSpecifiers[name_8] = [])).push(specifier); + } + } + break; + case 235 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + /** + * Gets a value indicating whether a node is merged with a class declaration in the same scope. + */ + function isMergedWithClass(node) { + if (node.symbol) { + for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 221 /* ClassDeclaration */ && declaration !== node) { + return true; + } + } + } + return false; + } + ts.isMergedWithClass = isMergedWithClass; + /** + * Gets a value indicating whether a node is the first declaration of its kind. + * + * @param node A Declaration node. + * @param kind The SyntaxKind to find among related declarations. + */ + function isFirstDeclarationOfKind(node, kind) { + return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; + } + ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; + // Node tests + // + // All node tests in the following list should *not* reference parent pointers so that + // they may be used with transformations. + // Node Arrays + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 11 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isTextualLiteralKind(kind) { + return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; + } + ts.isTextualLiteralKind = isTextualLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + function isTemplateLiteralKind(kind) { + return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralFragmentKind(kind) { + return kind === 12 /* TemplateHead */ + || kind === 13 /* TemplateMiddle */ + || kind === 14 /* TemplateTail */; + } + function isTemplateLiteralFragment(node) { + return isTemplateLiteralFragmentKind(node.kind); + } + ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + // Identifiers + function isIdentifier(node) { + return node.kind === 69 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + function isGeneratedIdentifier(node) { + // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. + return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + // Names + function isQualifiedName(node) { + return node.kind === 139 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 140 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isEntityName(node) { + var kind = node.kind; + return kind === 139 /* QualifiedName */ + || kind === 69 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 140 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isModuleName(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 9 /* StringLiteral */; + } + ts.isModuleName = isModuleName; + function isBindingName(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 167 /* ObjectBindingPattern */ + || kind === 168 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Signature elements + function isTypeParameter(node) { + return node.kind === 141 /* TypeParameter */; + } + ts.isTypeParameter = isTypeParameter; + function isParameter(node) { + return node.kind === 142 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 143 /* Decorator */; + } + ts.isDecorator = isDecorator; + // Type members + function isMethodDeclaration(node) { + return node.kind === 147 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isClassElement(node) { + var kind = node.kind; + return kind === 148 /* Constructor */ + || kind === 145 /* PropertyDeclaration */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 153 /* IndexSignature */ + || kind === 198 /* SemicolonClassElement */; + } + ts.isClassElement = isClassElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 253 /* PropertyAssignment */ + || kind === 254 /* ShorthandPropertyAssignment */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 239 /* MissingDeclaration */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + function isTypeNodeKind(kind) { + return (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) + || kind === 117 /* AnyKeyword */ + || kind === 130 /* NumberKeyword */ + || kind === 120 /* BooleanKeyword */ + || kind === 132 /* StringKeyword */ + || kind === 133 /* SymbolKeyword */ + || kind === 103 /* VoidKeyword */ + || kind === 127 /* NeverKeyword */ + || kind === 194 /* ExpressionWithTypeArguments */; + } + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + // Binding patterns + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 168 /* ArrayBindingPattern */ + || kind === 167 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isBindingElement(node) { + return node.kind === 169 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 169 /* BindingElement */ + || kind === 193 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + // Expression + function isPropertyAccessExpression(node) { + return node.kind === 172 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 173 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isBinaryExpression(node) { + return node.kind === 187 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 188 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isCallExpression(node) { + return node.kind === 174 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isTemplate(node) { + var kind = node.kind; + return kind === 189 /* TemplateExpression */ + || kind === 11 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplate = isTemplate; + function isSpreadElementExpression(node) { + return node.kind === 191 /* SpreadElementExpression */; + } + ts.isSpreadElementExpression = isSpreadElementExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 194 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isLeftHandSideExpressionKind(kind) { + return kind === 172 /* PropertyAccessExpression */ + || kind === 173 /* ElementAccessExpression */ + || kind === 175 /* NewExpression */ + || kind === 174 /* CallExpression */ + || kind === 241 /* JsxElement */ + || kind === 242 /* JsxSelfClosingElement */ + || kind === 176 /* TaggedTemplateExpression */ + || kind === 170 /* ArrayLiteralExpression */ + || kind === 178 /* ParenthesizedExpression */ + || kind === 171 /* ObjectLiteralExpression */ + || kind === 192 /* ClassExpression */ + || kind === 179 /* FunctionExpression */ + || kind === 69 /* Identifier */ + || kind === 10 /* RegularExpressionLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 9 /* StringLiteral */ + || kind === 11 /* NoSubstitutionTemplateLiteral */ + || kind === 189 /* TemplateExpression */ + || kind === 84 /* FalseKeyword */ + || kind === 93 /* NullKeyword */ + || kind === 97 /* ThisKeyword */ + || kind === 99 /* TrueKeyword */ + || kind === 95 /* SuperKeyword */ + || kind === 196 /* NonNullExpression */; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 185 /* PrefixUnaryExpression */ + || kind === 186 /* PostfixUnaryExpression */ + || kind === 181 /* DeleteExpression */ + || kind === 182 /* TypeOfExpression */ + || kind === 183 /* VoidExpression */ + || kind === 184 /* AwaitExpression */ + || kind === 177 /* TypeAssertionExpression */ + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 188 /* ConditionalExpression */ + || kind === 190 /* YieldExpression */ + || kind === 180 /* ArrowFunction */ + || kind === 187 /* BinaryExpression */ + || kind === 191 /* SpreadElementExpression */ + || kind === 195 /* AsExpression */ + || kind === 193 /* OmittedExpression */ + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 177 /* TypeAssertionExpression */ + || kind === 195 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isOmittedExpression(node) { + return node.kind === 193 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + // Misc + function isTemplateSpan(node) { + return node.kind === 197 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + // Element + function isBlock(node) { + return node.kind === 199 /* Block */; + } + ts.isBlock = isBlock; + function isConciseBody(node) { + return isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isVariableDeclaration(node) { + return node.kind === 218 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 219 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isCaseBlock(node) { + return node.kind === 227 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isModuleBody(node) { + var kind = node.kind; + return kind === 226 /* ModuleBlock */ + || kind === 225 /* ModuleDeclaration */; + } + ts.isModuleBody = isModuleBody; + function isImportEqualsDeclaration(node) { + return node.kind === 229 /* ImportEqualsDeclaration */; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportClause(node) { + return node.kind === 231 /* ImportClause */; + } + ts.isImportClause = isImportClause; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 233 /* NamedImports */ + || kind === 232 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isImportSpecifier(node) { + return node.kind === 234 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isNamedExports(node) { + return node.kind === 237 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 238 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isModuleOrEnumDeclaration(node) { + return node.kind === 225 /* ModuleDeclaration */ || node.kind === 224 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 180 /* ArrowFunction */ + || kind === 169 /* BindingElement */ + || kind === 221 /* ClassDeclaration */ + || kind === 192 /* ClassExpression */ + || kind === 148 /* Constructor */ + || kind === 224 /* EnumDeclaration */ + || kind === 255 /* EnumMember */ + || kind === 238 /* ExportSpecifier */ + || kind === 220 /* FunctionDeclaration */ + || kind === 179 /* FunctionExpression */ + || kind === 149 /* GetAccessor */ + || kind === 231 /* ImportClause */ + || kind === 229 /* ImportEqualsDeclaration */ + || kind === 234 /* ImportSpecifier */ + || kind === 222 /* InterfaceDeclaration */ + || kind === 147 /* MethodDeclaration */ + || kind === 146 /* MethodSignature */ + || kind === 225 /* ModuleDeclaration */ + || kind === 228 /* NamespaceExportDeclaration */ + || kind === 232 /* NamespaceImport */ + || kind === 142 /* Parameter */ + || kind === 253 /* PropertyAssignment */ + || kind === 145 /* PropertyDeclaration */ + || kind === 144 /* PropertySignature */ + || kind === 150 /* SetAccessor */ + || kind === 254 /* ShorthandPropertyAssignment */ + || kind === 223 /* TypeAliasDeclaration */ + || kind === 141 /* TypeParameter */ + || kind === 218 /* VariableDeclaration */ + || kind === 279 /* JSDocTypedefTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 220 /* FunctionDeclaration */ + || kind === 239 /* MissingDeclaration */ + || kind === 221 /* ClassDeclaration */ + || kind === 222 /* InterfaceDeclaration */ + || kind === 223 /* TypeAliasDeclaration */ + || kind === 224 /* EnumDeclaration */ + || kind === 225 /* ModuleDeclaration */ + || kind === 230 /* ImportDeclaration */ + || kind === 229 /* ImportEqualsDeclaration */ + || kind === 236 /* ExportDeclaration */ + || kind === 235 /* ExportAssignment */ + || kind === 228 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 210 /* BreakStatement */ + || kind === 209 /* ContinueStatement */ + || kind === 217 /* DebuggerStatement */ + || kind === 204 /* DoStatement */ + || kind === 202 /* ExpressionStatement */ + || kind === 201 /* EmptyStatement */ + || kind === 207 /* ForInStatement */ + || kind === 208 /* ForOfStatement */ + || kind === 206 /* ForStatement */ + || kind === 203 /* IfStatement */ + || kind === 214 /* LabeledStatement */ + || kind === 211 /* ReturnStatement */ + || kind === 213 /* SwitchStatement */ + || kind === 215 /* ThrowStatement */ + || kind === 216 /* TryStatement */ + || kind === 200 /* VariableStatement */ + || kind === 205 /* WhileStatement */ + || kind === 212 /* WithStatement */ + || kind === 287 /* NotEmittedStatement */; + } + function isDeclaration(node) { + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 199 /* Block */; + } + ts.isStatement = isStatement; + // Module references + function isModuleReference(node) { + var kind = node.kind; + return kind === 240 /* ExternalModuleReference */ + || kind === 139 /* QualifiedName */ + || kind === 69 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + function isJsxOpeningElement(node) { + return node.kind === 243 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 245 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 97 /* ThisKeyword */ + || kind === 69 /* Identifier */ + || kind === 172 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 241 /* JsxElement */ + || kind === 248 /* JsxExpression */ + || kind === 242 /* JsxSelfClosingElement */ + || kind === 244 /* JsxText */; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 246 /* JsxAttribute */ + || kind === 247 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isJsxSpreadAttribute(node) { + return node.kind === 247 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxAttribute(node) { + return node.kind === 246 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 248 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 249 /* CaseClause */ + || kind === 250 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isHeritageClause(node) { + return node.kind === 251 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 252 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 253 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 254 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 255 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 256 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; function isWatchSet(options) { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); @@ -7913,30 +9910,2542 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 169 /* BindingElement */ || ts.isBindingPattern(node))) { + node = node.parent; + } + return node; } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return str.indexOf(suffix, expectedPos) === expectedPos; + function getCombinedModifierFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = ts.getModifierFlags(node); + if (node.kind === 218 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 219 /* VariableDeclarationList */) { + flags |= ts.getModifierFlags(node); + node = node.parent; + } + if (node && node.kind === 200 /* VariableStatement */) { + flags |= ts.getModifierFlags(node); + } + return flags; + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 218 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 219 /* VariableDeclarationList */) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 200 /* VariableStatement */) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + var NodeConstructor; + var SourceFileConstructor; + function createNode(kind, location, flags) { + var ConstructorForKind = kind === 256 /* SourceFile */ + ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) + : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); + var node = location + ? new ConstructorForKind(kind, location.pos, location.end) + : new ConstructorForKind(kind, /*pos*/ -1, /*end*/ -1); + node.flags = flags | 8 /* Synthesized */; + return node; + } + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + if (original.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + function createNodeArray(elements, location, hasTrailingComma) { + if (elements) { + if (ts.isNodeArray(elements)) { + return elements; + } + } + else { + elements = []; + } + var array = elements; + if (location) { + array.pos = location.pos; + array.end = location.end; + } + else { + array.pos = -1; + array.end = -1; + } + if (hasTrailingComma) { + array.hasTrailingComma = true; + } + return array; + } + ts.createNodeArray = createNodeArray; + function createSynthesizedNode(kind, startsOnNewLine) { + var node = createNode(kind, /*location*/ undefined); + node.startsOnNewLine = startsOnNewLine; + return node; + } + ts.createSynthesizedNode = createSynthesizedNode; + function createSynthesizedNodeArray(elements) { + return createNodeArray(elements, /*location*/ undefined); + } + ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + var clone = createNode(node.kind, /*location*/ undefined, node.flags); + clone.original = node; + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + function createLiteral(value, location) { + if (typeof value === "number") { + var node = createNode(8 /* NumericLiteral */, location, /*flags*/ undefined); + node.text = value.toString(); + return node; + } + else if (typeof value === "boolean") { + return createNode(value ? 99 /* TrueKeyword */ : 84 /* FalseKeyword */, location, /*flags*/ undefined); + } + else if (typeof value === "string") { + var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); + node.text = value; + return node; + } + else { + var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); + node.textSourceNode = value; + node.text = value.text; + return node; + } + } + ts.createLiteral = createLiteral; + // Identifiers + var nextAutoGenerateId = 0; + function createIdentifier(text, location) { + var node = createNode(69 /* Identifier */, location); + node.text = ts.escapeIdentifier(text); + node.originalKeywordKind = ts.stringToToken(text); + node.autoGenerateKind = 0 /* None */; + node.autoGenerateId = 0; + return node; + } + ts.createIdentifier = createIdentifier; + function createTempVariable(recordTempVariable, location) { + var name = createNode(69 /* Identifier */, location); + name.text = ""; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + return name; + } + ts.createTempVariable = createTempVariable; + function createLoopVariable(location) { + var name = createNode(69 /* Identifier */, location); + name.text = ""; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + function createUniqueName(text, location) { + var name = createNode(69 /* Identifier */, location); + name.text = text; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function getGeneratedNameForNode(node, location) { + var name = createNode(69 /* Identifier */, location); + name.original = node; + name.text = ""; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 4 /* Node */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation + function createToken(token) { + return createNode(token); + } + ts.createToken = createToken; + // Reserved words + function createSuper() { + var node = createNode(95 /* SuperKeyword */); + return node; + } + ts.createSuper = createSuper; + function createThis(location) { + var node = createNode(97 /* ThisKeyword */, location); + return node; + } + ts.createThis = createThis; + function createNull() { + var node = createNode(93 /* NullKeyword */); + return node; + } + ts.createNull = createNull; + // Names + function createComputedPropertyName(expression, location) { + var node = createNode(140 /* ComputedPropertyName */, location); + node.expression = expression; + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + if (node.expression !== expression) { + return updateNode(createComputedPropertyName(expression, node), node); + } + return node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements + function createParameter(name, initializer, location) { + return createParameterDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, + /*type*/ undefined, initializer, location); + } + ts.createParameter = createParameter; + function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(142 /* Parameter */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameterDeclaration = createParameterDeclaration; + function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); + } + return node; + } + ts.updateParameterDeclaration = updateParameterDeclaration; + // Type members + function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { + var node = createNode(145 /* PropertyDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer, node), node); + } + return node; + } + ts.updateProperty = updateProperty; + function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(147 /* MethodDeclaration */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createMethod(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body, location, flags) { + var node = createNode(148 /* Constructor */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body) { + return updateNode(createConstructor(decorators, modifiers, parameters, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { + var node = createNode(149 /* GetAccessor */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { + var node = createNode(150 /* SetAccessor */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body) { + return updateNode(createSetAccessor(decorators, modifiers, name, parameters, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateSetAccessor = updateSetAccessor; + // Binding Patterns + function createObjectBindingPattern(elements, location) { + var node = createNode(167 /* ObjectBindingPattern */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createObjectBindingPattern(elements, node), node); + } + return node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements, location) { + var node = createNode(168 /* ArrayBindingPattern */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayBindingPattern(elements, node), node); + } + return node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { + var node = createNode(169 /* BindingElement */, location); + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + } + return node; + } + ts.updateBindingElement = updateBindingElement; + // Expression + function createArrayLiteral(elements, location, multiLine) { + var node = createNode(170 /* ArrayLiteralExpression */, location); + node.elements = parenthesizeListElements(createNodeArray(elements)); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayLiteral(elements, node, node.multiLine), node); + } + return node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, location, multiLine) { + var node = createNode(171 /* ObjectLiteralExpression */, location); + node.properties = createNodeArray(properties); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + if (node.properties !== properties) { + return updateNode(createObjectLiteral(properties, node, node.multiLine), node); + } + return node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name, location, flags) { + var node = createNode(172 /* PropertyAccessExpression */, location, flags); + node.expression = parenthesizeForAccess(expression); + node.emitFlags = 1048576 /* NoIndentation */; + node.name = typeof name === "string" ? createIdentifier(name) : name; + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + if (node.expression !== expression || node.name !== name) { + var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); + // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess + propertyAccess.emitFlags = node.emitFlags; + return updateNode(propertyAccess, node); + } + return node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index, location) { + var node = createNode(173 /* ElementAccessExpression */, location); + node.expression = parenthesizeForAccess(expression); + node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + if (node.expression !== expression || node.argumentExpression !== argumentExpression) { + return updateNode(createElementAccess(expression, argumentExpression, node), node); + } + return node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(174 /* CallExpression */, location, flags); + node.expression = parenthesizeForAccess(expression); + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + node.arguments = parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + if (expression !== node.expression || typeArguments !== node.typeArguments || argumentsArray !== node.arguments) { + return updateNode(createCall(expression, typeArguments, argumentsArray, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(175 /* NewExpression */, location, flags); + node.expression = parenthesizeForNew(expression); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + if (node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray) { + return updateNode(createNew(expression, typeArguments, argumentsArray, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, template, location) { + var node = createNode(176 /* TaggedTemplateExpression */, location); + node.tag = parenthesizeForAccess(tag); + node.template = template; + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, template) { + if (node.tag !== tag || node.template !== template) { + return updateNode(createTaggedTemplate(tag, template, node), node); + } + return node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createParen(expression, location) { + var node = createNode(178 /* ParenthesizedExpression */, location); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + if (node.expression !== expression) { + return updateNode(createParen(expression, node), node); + } + return node; + } + ts.updateParen = updateParen; + function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(179 /* FunctionExpression */, location, flags); + node.modifiers = undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { + var node = createNode(180 /* ArrowFunction */, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.body = parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + if (node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression, location) { + var node = createNode(181 /* DeleteExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + if (node.expression !== expression) { + return updateNode(createDelete(expression, node), expression); + } + return node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression, location) { + var node = createNode(182 /* TypeOfExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + if (node.expression !== expression) { + return updateNode(createTypeOf(expression, node), expression); + } + return node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression, location) { + var node = createNode(183 /* VoidExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + if (node.expression !== expression) { + return updateNode(createVoid(expression, node), node); + } + return node; + } + ts.updateVoid = updateVoid; + function createAwait(expression, location) { + var node = createNode(184 /* AwaitExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + if (node.expression !== expression) { + return updateNode(createAwait(expression, node), node); + } + return node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand, location) { + var node = createNode(185 /* PrefixUnaryExpression */, location); + node.operator = operator; + node.operand = parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPrefix(node.operator, operand, node), node); + } + return node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator, location) { + var node = createNode(186 /* PostfixUnaryExpression */, location); + node.operand = parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPostfix(operand, node.operator, node), node); + } + return node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right, location) { + var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorKind = operatorToken.kind; + var node = createNode(187 /* BinaryExpression */, location); + node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); + node.operatorToken = operatorToken; + node.right = parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right) { + if (node.left !== left || node.right !== right) { + return updateNode(createBinary(left, node.operatorToken, right, /*location*/ node), node); + } + return node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { + var node = createNode(188 /* ConditionalExpression */, location); + node.condition = condition; + node.questionToken = questionToken; + node.whenTrue = whenTrue; + node.colonToken = colonToken; + node.whenFalse = whenFalse; + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, whenTrue, whenFalse) { + if (node.condition !== condition || node.whenTrue !== whenTrue || node.whenFalse !== whenFalse) { + return updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse, node), node); + } + return node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans, location) { + var node = createNode(189 /* TemplateExpression */, location); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + if (node.head !== head || node.templateSpans !== templateSpans) { + return updateNode(createTemplateExpression(head, templateSpans, node), node); + } + return node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createYield(asteriskToken, expression, location) { + var node = createNode(190 /* YieldExpression */, location); + node.asteriskToken = asteriskToken; + node.expression = expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, expression) { + if (node.expression !== expression) { + return updateNode(createYield(node.asteriskToken, expression, node), node); + } + return node; + } + ts.updateYield = updateYield; + function createSpread(expression, location) { + var node = createNode(191 /* SpreadElementExpression */, location); + node.expression = parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpread(expression, node), node); + } + return node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(192 /* ClassExpression */, location); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + if (node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression(location) { + var node = createNode(193 /* OmittedExpression */, location); + return node; + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression, location) { + var node = createNode(194 /* ExpressionWithTypeArguments */, location); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.expression = parenthesizeForAccess(expression); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + if (node.typeArguments !== typeArguments || node.expression !== expression) { + return updateNode(createExpressionWithTypeArguments(typeArguments, expression, node), node); + } + return node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + // Misc + function createTemplateSpan(expression, literal, location) { + var node = createNode(197 /* TemplateSpan */, location); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + if (node.expression !== expression || node.literal !== literal) { + return updateNode(createTemplateSpan(expression, literal, node), node); + } + return node; + } + ts.updateTemplateSpan = updateTemplateSpan; + // Element + function createBlock(statements, location, multiLine, flags) { + var block = createNode(199 /* Block */, location, flags); + block.statements = createNodeArray(statements); + if (multiLine) { + block.multiLine = true; + } + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + if (statements !== node.statements) { + return updateNode(createBlock(statements, /*location*/ node, node.multiLine, node.flags), node); + } + return node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList, location, flags) { + var node = createNode(200 /* VariableStatement */, location, flags); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + if (node.modifiers !== modifiers || node.declarationList !== declarationList) { + return updateNode(createVariableStatement(modifiers, declarationList, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateVariableStatement = updateVariableStatement; + function createVariableDeclarationList(declarations, location, flags) { + var node = createNode(219 /* VariableDeclarationList */, location, flags); + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + if (node.declarations !== declarations) { + return updateNode(createVariableDeclarationList(declarations, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createVariableDeclaration(name, type, initializer, location, flags) { + var node = createNode(218 /* VariableDeclaration */, location, flags); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.type = type; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + if (node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createVariableDeclaration(name, type, initializer, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createEmptyStatement(location) { + return createNode(201 /* EmptyStatement */, location); + } + ts.createEmptyStatement = createEmptyStatement; + function createStatement(expression, location, flags) { + var node = createNode(202 /* ExpressionStatement */, location, flags); + node.expression = parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createStatement = createStatement; + function updateStatement(node, expression) { + if (node.expression !== expression) { + return updateNode(createStatement(expression, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateStatement = updateStatement; + function createIf(expression, thenStatement, elseStatement, location) { + var node = createNode(203 /* IfStatement */, location); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + if (node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement) { + return updateNode(createIf(expression, thenStatement, elseStatement, /*location*/ node), node); + } + return node; + } + ts.updateIf = updateIf; + function createDo(statement, expression, location) { + var node = createNode(204 /* DoStatement */, location); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + if (node.statement !== statement || node.expression !== expression) { + return updateNode(createDo(statement, expression, node), node); + } + return node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement, location) { + var node = createNode(205 /* WhileStatement */, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWhile(expression, statement, node), node); + } + return node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement, location) { + var node = createNode(206 /* ForStatement */, location, /*flags*/ undefined); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + if (node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement) { + return updateNode(createFor(initializer, condition, incrementor, statement, node), node); + } + return node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement, location) { + var node = createNode(207 /* ForInStatement */, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForIn(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForIn = updateForIn; + function createForOf(initializer, expression, statement, location) { + var node = createNode(208 /* ForOfStatement */, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForOf(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForOf = updateForOf; + function createContinue(label, location) { + var node = createNode(209 /* ContinueStatement */, location); + if (label) { + node.label = label; + } + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + if (node.label !== label) { + return updateNode(createContinue(label, node), node); + } + return node; + } + ts.updateContinue = updateContinue; + function createBreak(label, location) { + var node = createNode(210 /* BreakStatement */, location); + if (label) { + node.label = label; + } + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + if (node.label !== label) { + return updateNode(createBreak(label, node), node); + } + return node; + } + ts.updateBreak = updateBreak; + function createReturn(expression, location) { + var node = createNode(211 /* ReturnStatement */, location); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + if (node.expression !== expression) { + return updateNode(createReturn(expression, /*location*/ node), node); + } + return node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement, location) { + var node = createNode(212 /* WithStatement */, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWith(expression, statement, node), node); + } + return node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock, location) { + var node = createNode(213 /* SwitchStatement */, location); + node.expression = parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + if (node.expression !== expression || node.caseBlock !== caseBlock) { + return updateNode(createSwitch(expression, caseBlock, node), node); + } + return node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement, location) { + var node = createNode(214 /* LabeledStatement */, location); + node.label = typeof label === "string" ? createIdentifier(label) : label; + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + if (node.label !== label || node.statement !== statement) { + return updateNode(createLabel(label, statement, node), node); + } + return node; + } + ts.updateLabel = updateLabel; + function createThrow(expression, location) { + var node = createNode(215 /* ThrowStatement */, location); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + if (node.expression !== expression) { + return updateNode(createThrow(expression, node), node); + } + return node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock, location) { + var node = createNode(216 /* TryStatement */, location); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + if (node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock) { + return updateNode(createTry(tryBlock, catchClause, finallyBlock, node), node); + } + return node; + } + ts.updateTry = updateTry; + function createCaseBlock(clauses, location) { + var node = createNode(227 /* CaseBlock */, location); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + if (node.clauses !== clauses) { + return updateNode(createCaseBlock(clauses, node), node); + } + return node; + } + ts.updateCaseBlock = updateCaseBlock; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(220 /* FunctionDeclaration */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionDeclaration(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(221 /* ClassDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { + var node = createNode(230 /* ImportDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings, location) { + var node = createNode(231 /* ImportClause */, location); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + if (node.name !== name || node.namedBindings !== namedBindings) { + return updateNode(createImportClause(name, namedBindings, node), node); + } + return node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name, location) { + var node = createNode(232 /* NamespaceImport */, location); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + if (node.name !== name) { + return updateNode(createNamespaceImport(name, node), node); + } + return node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements, location) { + var node = createNode(233 /* NamedImports */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedImports(elements, node), node); + } + return node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name, location) { + var node = createNode(234 /* ImportSpecifier */, location); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + if (node.propertyName !== propertyName || node.name !== name) { + return updateNode(createImportSpecifier(propertyName, name, node), node); + } + return node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { + var node = createNode(235 /* ExportAssignment */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.isExportEquals = isExportEquals; + node.expression = expression; + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.expression !== expression) { + return updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression, node), node); + } + return node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { + var node = createNode(236 /* ExportDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements, location) { + var node = createNode(237 /* NamedExports */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedExports(elements, node), node); + } + return node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(name, propertyName, location) { + var node = createNode(238 /* ExportSpecifier */, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, name, propertyName) { + if (node.name !== name || node.propertyName !== propertyName) { + return updateNode(createExportSpecifier(name, propertyName, node), node); + } + return node; + } + ts.updateExportSpecifier = updateExportSpecifier; + // JSX + function createJsxElement(openingElement, children, closingElement, location) { + var node = createNode(241 /* JsxElement */, location); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + if (node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement) { + return updateNode(createJsxElement(openingElement, children, closingElement, node), node); + } + return node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, attributes, location) { + var node = createNode(242 /* JsxSelfClosingElement */, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxSelfClosingElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, attributes, location) { + var node = createNode(243 /* JsxOpeningElement */, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxOpeningElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName, location) { + var node = createNode(245 /* JsxClosingElement */, location); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + if (node.tagName !== tagName) { + return updateNode(createJsxClosingElement(tagName, node), node); + } + return node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxAttribute(name, initializer, location) { + var node = createNode(246 /* JsxAttribute */, location); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createJsxAttribute(name, initializer, node), node); + } + return node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxSpreadAttribute(expression, location) { + var node = createNode(247 /* JsxSpreadAttribute */, location); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxSpreadAttribute(expression, node), node); + } + return node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(expression, location) { + var node = createNode(248 /* JsxExpression */, location); + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxExpression(expression, node), node); + } + return node; + } + ts.updateJsxExpression = updateJsxExpression; + // Clauses + function createHeritageClause(token, types, location) { + var node = createNode(251 /* HeritageClause */, location); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + if (node.types !== types) { + return updateNode(createHeritageClause(node.token, types, node), node); + } + return node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCaseClause(expression, statements, location) { + var node = createNode(249 /* CaseClause */, location); + node.expression = parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + if (node.expression !== expression || node.statements !== statements) { + return updateNode(createCaseClause(expression, statements, node), node); + } + return node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements, location) { + var node = createNode(250 /* DefaultClause */, location); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + if (node.statements !== statements) { + return updateNode(createDefaultClause(statements, node), node); + } + return node; + } + ts.updateDefaultClause = updateDefaultClause; + function createCatchClause(variableDeclaration, block, location) { + var node = createNode(252 /* CatchClause */, location); + node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + if (node.variableDeclaration !== variableDeclaration || node.block !== block) { + return updateNode(createCatchClause(variableDeclaration, block, node), node); + } + return node; + } + ts.updateCatchClause = updateCatchClause; + // Property assignments + function createPropertyAssignment(name, initializer, location) { + var node = createNode(253 /* PropertyAssignment */, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = undefined; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createPropertyAssignment(name, initializer, node), node); + } + return node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { + var node = createNode(254 /* ShorthandPropertyAssignment */, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { + return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); + } + return node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + // Top-level nodes + function updateSourceFileNode(node, statements) { + if (node.statements !== statements) { + var updated = createNode(256 /* SourceFile */, /*location*/ node, node.flags); + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.referencedFiles !== undefined) + updated.referencedFiles = node.referencedFiles; + if (node.typeReferenceDirectives !== undefined) + updated.typeReferenceDirectives = node.typeReferenceDirectives; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.isDeclarationFile !== undefined) + updated.isDeclarationFile = node.isDeclarationFile; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.hasNoDefaultLib !== undefined) + updated.hasNoDefaultLib = node.hasNoDefaultLib; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.externalHelpersModuleName !== undefined) + updated.externalHelpersModuleName = node.externalHelpersModuleName; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original) { + var node = createNode(287 /* NotEmittedStatement */, /*location*/ original); + node.original = original; + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression, original, location) { + var node = createNode(288 /* PartiallyEmittedExpression */, /*location*/ location || original); + node.expression = expression; + node.original = original; + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original, node), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + // Compound nodes + function createComma(left, right) { + return createBinary(left, 24 /* CommaToken */, right); + } + ts.createComma = createComma; + function createLessThan(left, right, location) { + return createBinary(left, 25 /* LessThanToken */, right, location); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right, location) { + return createBinary(left, 56 /* EqualsToken */, right, location); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 32 /* EqualsEqualsEqualsToken */, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 33 /* ExclamationEqualsEqualsToken */, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 35 /* PlusToken */, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 36 /* MinusToken */, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand, location) { + return createPostfix(operand, 41 /* PlusPlusToken */, location); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 51 /* AmpersandAmpersandToken */, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 52 /* BarBarToken */, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(49 /* ExclamationToken */, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return createElementAccess(target, memberName.expression, location); + } + else { + var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); + expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createRestParameter(name) { + return createParameterDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + ts.createRestParameter = createRestParameter; + function createFunctionCall(func, thisArg, argumentsList, location) { + return createCall(createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ + thisArg + ].concat(argumentsList), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return createCall(createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ + thisArg, + argumentsExpression + ], location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? createLiteral(start) : start); + } + return createCall(createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return createCall(createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return createCall(createPropertyAccess(createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right], location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. + var react = createIdentifier(reactNamespace || "React"); + react.flags &= ~8 /* Synthesized */; + react.parent = parent; + return react; + } + function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + child.startsOnNewLine = true; + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), + /*typeArguments*/ undefined, argumentsList, location); + } + ts.createReactCreateElement = createReactCreateElement; + function createLetDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 1 /* Let */); + } + ts.createLetDeclarationList = createLetDeclarationList; + function createConstDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 2 /* Const */); + } + ts.createConstDeclarationList = createConstDeclarationList; + // Helpers + function createHelperName(externalHelpersModuleName, name) { + return externalHelpersModuleName + ? createPropertyAccess(externalHelpersModuleName, name) + : createIdentifier(name); + } + ts.createHelperName = createHelperName; + function createExtendsHelper(externalHelpersModuleName, name) { + return createCall(createHelperName(externalHelpersModuleName, "__extends"), + /*typeArguments*/ undefined, [ + name, + createIdentifier("_super") + ]); + } + ts.createExtendsHelper = createExtendsHelper; + function createAssignHelper(externalHelpersModuleName, attributesSegments) { + return createCall(createHelperName(externalHelpersModuleName, "__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { + return createCall(createHelperName(externalHelpersModuleName, "__param"), + /*typeArguments*/ undefined, [ + createLiteral(parameterOffset), + expression + ], location); + } + ts.createParamHelper = createParamHelper; + function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { + return createCall(createHelperName(externalHelpersModuleName, "__metadata"), + /*typeArguments*/ undefined, [ + createLiteral(metadataKey), + metadataValue + ]); + } + ts.createMetadataHelper = createMetadataHelper; + function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return createCall(createHelperName(externalHelpersModuleName, "__decorate"), /*typeArguments*/ undefined, argumentsArray, location); + } + ts.createDecorateHelper = createDecorateHelper; + function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { + var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; + return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), + /*typeArguments*/ undefined, [ + createThis(), + hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), + promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), + generatorFunc + ]); + } + ts.createAwaiterHelper = createAwaiterHelper; + function createHasOwnProperty(target, propertyName) { + return createCall(createPropertyAccess(target, "hasOwnProperty"), + /*typeArguments*/ undefined, [propertyName]); + } + ts.createHasOwnProperty = createHasOwnProperty; + function createObjectCreate(prototype) { + return createCall(createPropertyAccess(createIdentifier("Object"), "create"), + /*typeArguments*/ undefined, [prototype]); + } + function createGeti(target) { + // name => super[name] + return createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, [createParameter("name")], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createElementAccess(target, createIdentifier("name"))); + } + function createSeti(target) { + // (name, value) => super[name] = value + return createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, [ + createParameter("name"), + createParameter("value") + ], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); + } + function createAdvancedAsyncSuperHelper() { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // const cache = Object.create(null); + var createCache = createVariableStatement( + /*modifiers*/ undefined, createConstDeclarationList([ + createVariableDeclaration("cache", + /*type*/ undefined, createObjectCreate(createNull())) + ])); + // get value() { return geti(name); } + var getter = createGetAccessor( + /*decorators*/ undefined, + /*modifiers*/ undefined, "value", + /*parameters*/ [], + /*type*/ undefined, createBlock([ + createReturn(createCall(createIdentifier("geti"), + /*typeArguments*/ undefined, [createIdentifier("name")])) + ])); + // set value(v) { seti(name, v); } + var setter = createSetAccessor( + /*decorators*/ undefined, + /*modifiers*/ undefined, "value", [createParameter("v")], createBlock([ + createStatement(createCall(createIdentifier("seti"), + /*typeArguments*/ undefined, [ + createIdentifier("name"), + createIdentifier("v") + ])) + ])); + // return name => cache[name] || ... + var getOrCreateAccessorsForName = createReturn(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, [createParameter("name")], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ + getter, + setter + ])))))); + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + return createVariableStatement( + /*modifiers*/ undefined, createConstDeclarationList([ + createVariableDeclaration("_super", + /*type*/ undefined, createCall(createParen(createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + createParameter("geti"), + createParameter("seti") + ], + /*type*/ undefined, createBlock([ + createCache, + getOrCreateAccessorsForName + ]))), + /*typeArguments*/ undefined, [ + createGeti(createSuper()), + createSeti(createSuper()) + ])) + ])); + } + ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; + function createSimpleAsyncSuperHelper() { + return createVariableStatement( + /*modifiers*/ undefined, createConstDeclarationList([ + createVariableDeclaration("_super", + /*type*/ undefined, createGeti(createSuper())) + ])); + } + ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = skipParentheses(node); + switch (target.kind) { + case 69 /* Identifier */: + return cacheIdentifiers; + case 97 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return false; + case 170 /* ArrayLiteralExpression */: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 171 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + var callee = skipOuterExpressions(expression, 7 /* All */); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = createThis(); + target = callee; + } + else if (callee.kind === 95 /* SuperKeyword */) { + thisArg = createThis(); + target = languageVersion < 2 /* ES6 */ ? createIdentifier("_super", /*location*/ callee) : callee; + } + else { + switch (callee.kind) { + case 172 /* PropertyAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` + thisArg = createTempVariable(recordTempVariable); + target = createPropertyAccess(createAssignment(thisArg, callee.expression, + /*location*/ callee.expression), callee.name, + /*location*/ callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 173 /* ElementAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` + thisArg = createTempVariable(recordTempVariable); + target = createElementAccess(createAssignment(thisArg, callee.expression, + /*location*/ callee.expression), callee.argumentExpression, + /*location*/ callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + // for `a()` target is `a` and thisArg is `void 0` + thisArg = createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + return ts.reduceLeft(expressions, createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = getMutableClone(node.right); + return createPropertyAccess(left, right, /*location*/ node); + } + else { + return getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return createLiteral(memberName, /*location*/ undefined); + } + else if (ts.isComputedPropertyName(memberName)) { + return getMutableClone(memberName.expression); + } + else { + return getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + case 253 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(property, receiver); + case 254 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 147 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_1 = []; + if (getAccessor) { + var getterFunction = createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body, + /*location*/ getAccessor); + setOriginalNode(getterFunction, getAccessor); + var getter = createPropertyAssignment("get", getterFunction); + properties_1.push(getter); + } + if (setAccessor) { + var setterFunction = createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body, + /*location*/ setAccessor); + setOriginalNode(setterFunction, setAccessor); + var setter = createPropertyAssignment("set", setterFunction); + properties_1.push(setter); + } + properties_1.push(createPropertyAssignment("enumerable", createLiteral(true))); + properties_1.push(createPropertyAssignment("configurable", createLiteral(true))); + var expression = createCall(createPropertyAccess(createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + receiver, + createExpressionForPropertyName(property.name), + createObjectLiteral(properties_1, /*location*/ undefined, multiLine) + ], + /*location*/ firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer, + /*location*/ property), + /*original*/ property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), getSynthesizedClone(property.name), + /*location*/ property), + /*original*/ property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body, + /*location*/ method), + /*original*/ method), + /*location*/ method), + /*original*/ method)); + } + // Utilities + function isUseStrictPrologue(node) { + return node.expression.text === "use strict"; + } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ + function addPrologueDirectives(target, source, ensureUseStrict, visitor) { + ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + foundUseStrict = true; + } + if (statement.emitFlags & 8388608 /* CustomPrologue */) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + } + statementOffset++; + } + return statementOffset; + } + ts.addPrologueDirectives = addPrologueDirectives; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = skipPartiallyEmittedExpressions(operand); + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 178 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(187 /* BinaryExpression */, binaryOperator); + var emittedOperand = skipPartiallyEmittedExpressions(operand); + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 190 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 35 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ + function operatorHasAssociativeProperty(binaryOperator) { + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 37 /* AsteriskToken */ + || binaryOperator === 47 /* BarToken */ + || binaryOperator === 46 /* AmpersandToken */ + || binaryOperator === 48 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ + function getLiteralKindOfBinaryPlusOperand(node) { + node = skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 35 /* PlusToken */) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ + function parenthesizeForNew(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + switch (emittedExpression.kind) { + case 174 /* CallExpression */: + return createParen(expression); + case 175 /* NewExpression */: + return emittedExpression.arguments + ? expression + : createParen(expression); + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ + function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exceptions are: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // NumericLiteral + // 1.x -> not the same as (1).x + // + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 175 /* NewExpression */ || emittedExpression.arguments) + && emittedExpression.kind !== 8 /* NumericLiteral */) { + return expression; + } + return createParen(expression, /*location*/ expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : createParen(operand, /*location*/ operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : createParen(operand, /*location*/ operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return createNodeArray(result, elements, elements.hasTrailingComma); + } + return elements; + } + function parenthesizeExpressionForList(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, 24 /* CommaToken */); + return expressionPrecedence > commaPrecedence + ? expression + : createParen(expression, /*location*/ expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = skipPartiallyEmittedExpressions(callee).kind; + if (kind === 179 /* FunctionExpression */ || kind === 180 /* ArrowFunction */) { + var mutableCall = getMutableClone(emittedExpression); + mutableCall.expression = createParen(callee, /*location*/ callee); + return recreatePartiallyEmittedExpressions(expression, mutableCall); + } + } + else { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 171 /* ObjectLiteralExpression */ || leftmostExpressionKind === 179 /* FunctionExpression */) { + return createParen(expression, /*location*/ expression); + } + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + /** + * Clones a series of not-emitted expressions with a new inner expression. + * + * @param originalOuterExpression The original outer expression. + * @param newInnerExpression The new inner expression. + */ + function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { + if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { + var clone_1 = getMutableClone(originalOuterExpression); + clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); + return clone_1; + } + return newInnerExpression; + } + function getLeftmostExpression(node) { + while (true) { + switch (node.kind) { + case 186 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 187 /* BinaryExpression */: + node = node.left; + continue; + case 188 /* ConditionalExpression */: + node = node.condition; + continue; + case 174 /* CallExpression */: + case 173 /* ElementAccessExpression */: + case 172 /* PropertyAccessExpression */: + node = node.expression; + continue; + case 288 /* PartiallyEmittedExpression */: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + var emittedBody = skipPartiallyEmittedExpressions(body); + if (emittedBody.kind === 171 /* ObjectLiteralExpression */) { + return createParen(body, /*location*/ body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + var OuterExpressionKinds = ts.OuterExpressionKinds; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + var previousNode; + do { + previousNode = node; + if (kinds & 1 /* Parentheses */) { + node = skipParentheses(node); + } + if (kinds & 2 /* Assertions */) { + node = skipAssertions(node); + } + if (kinds & 4 /* PartiallyEmittedExpressions */) { + node = skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipParentheses(node) { + while (node.kind === 178 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipAssertions(node) { + while (ts.isAssertionExpression(node)) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function startOnNewLine(node) { + node.startsOnNewLine = true; + return node; + } + ts.startOnNewLine = startOnNewLine; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; + if (emitFlags) + node.emitFlags = emitFlags; + if (commentRange) + node.commentRange = commentRange; + if (sourceMapRange) + node.sourceMapRange = sourceMapRange; + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function setTextRange(node, location) { + if (location) { + node.pos = location.pos; + node.end = location.end; + } + return node; + } + ts.setTextRange = setTextRange; + function setNodeFlags(node, flags) { + node.flags = flags; + return node; + } + ts.setNodeFlags = setNodeFlags; + function setMultiLine(node, multiLine) { + node.multiLine = multiLine; + return node; + } + ts.setMultiLine = setMultiLine; + function setHasTrailingComma(nodes, hasTrailingComma) { + nodes.hasTrailingComma = hasTrailingComma; + return nodes; + } + ts.setHasTrailingComma = setHasTrailingComma; + /** + * Get the name of that target module from an import or export declaration + */ + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name_9 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_9) ? name_9 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + } + if (node.kind === 230 /* ImportDeclaration */ && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 236 /* ExportDeclaration */ && node.moduleSpecifier) { + return getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); + if (moduleName.kind === 9 /* StringLiteral */) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName, sourceFile) { + if (sourceFile.renamedDependencies && ts.hasProperty(sourceFile.renamedDependencies, moduleName.text)) { + return createLiteral(sourceFile.renamedDependencies[moduleName.text]); + } + return undefined; + } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return createLiteral(file.moduleName); + } + if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + return createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } - ts.endsWith = endsWith; })(ts || (ts = {})); /// /// +/// var ts; (function (ts) { - /* @internal */ ts.parseTime = 0; var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } + else if (kind === 69 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (kind < 139 /* FirstNode */) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -8052,6 +12561,8 @@ var ts; return visitNodes(cbNodes, node.types); case 164 /* ParenthesizedType */: return visitNode(cbNode, node.type); + case 166 /* LiteralType */: + return visitNode(cbNode, node.literal); case 167 /* ObjectBindingPattern */: case 168 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); @@ -8291,7 +12802,7 @@ var ts; case 263 /* JSDocNullableType */: return visitNode(cbNode, node.type); case 265 /* JSDocRecordType */: - return visitNodes(cbNodes, node.members); + return visitNode(cbNode, node.literal); case 267 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); @@ -8330,14 +12841,19 @@ var ts; case 280 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + case 288 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + case 282 /* JSDocLiteralType */: + return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - var start = new Date().getTime(); + ts.performance.mark("beforeParse"); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); - ts.parseTime += new Date().getTime() - start; + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; } ts.createSourceFile = createSourceFile; @@ -8361,10 +12877,10 @@ var ts; /* @internal */ function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDocComment) { + if (result && result.jsDoc) { // because the jsDocComment was parsed out of the source file, it might // not be covered by the fixupParentReferences. - Parser.fixupParentReferences(result.jsDocComment); + Parser.fixupParentReferences(result.jsDoc); } return result; } @@ -8383,14 +12899,16 @@ var ts; // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */; + var disallowInAndDecoratorContext = 32768 /* DisallowInContext */ | 131072 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -8485,15 +13003,17 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 1048576 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); @@ -8516,10 +13036,10 @@ var ts; sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; // Prime the scanner. - token = nextToken(); + nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); - ts.Debug.assert(token === 1 /* EndOfFileToken */); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -8532,20 +13052,18 @@ var ts; return sourceFile; } function addJSDocComment(node) { - if (contextFlags & 134217728 /* JavaScriptFile */) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDocComment) { - continue; - } - if (!node.jsDocComments) { - node.jsDocComments = []; - } - node.jsDocComments.push(jsDocComment); + var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; } + if (!node.jsDocComments) { + node.jsDocComments = []; + } + node.jsDocComments.push(jsDoc); } } return node; @@ -8603,16 +13121,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 4194304 /* DisallowInContext */); + setContextFlag(val, 32768 /* DisallowInContext */); } function setYieldContext(val) { - setContextFlag(val, 8388608 /* YieldContext */); + setContextFlag(val, 65536 /* YieldContext */); } function setDecoratorContext(val) { - setContextFlag(val, 16777216 /* DecoratorContext */); + setContextFlag(val, 131072 /* DecoratorContext */); } function setAwaitContext(val) { - setContextFlag(val, 33554432 /* AwaitContext */); + setContextFlag(val, 262144 /* AwaitContext */); } function doOutsideOfContext(context, func) { // contextFlagsToClear will contain only the context flags that are @@ -8653,40 +13171,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(4194304 /* DisallowInContext */, func); + return doOutsideOfContext(32768 /* DisallowInContext */, func); } function disallowInAnd(func) { - return doInsideOfContext(4194304 /* DisallowInContext */, func); + return doInsideOfContext(32768 /* DisallowInContext */, func); } function doInYieldContext(func) { - return doInsideOfContext(8388608 /* YieldContext */, func); + return doInsideOfContext(65536 /* YieldContext */, func); } function doInDecoratorContext(func) { - return doInsideOfContext(16777216 /* DecoratorContext */, func); + return doInsideOfContext(131072 /* DecoratorContext */, func); } function doInAwaitContext(func) { - return doInsideOfContext(33554432 /* AwaitContext */, func); + return doInsideOfContext(262144 /* AwaitContext */, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(33554432 /* AwaitContext */, func); + return doOutsideOfContext(262144 /* AwaitContext */, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(8388608 /* YieldContext */ | 33554432 /* AwaitContext */, func); + return doInsideOfContext(65536 /* YieldContext */ | 262144 /* AwaitContext */, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(8388608 /* YieldContext */); + return inContext(65536 /* YieldContext */); } function inDisallowInContext() { - return inContext(4194304 /* DisallowInContext */); + return inContext(32768 /* DisallowInContext */); } function inDecoratorContext() { - return inContext(16777216 /* DecoratorContext */); + return inContext(131072 /* DecoratorContext */); } function inAwaitContext() { - return inContext(33554432 /* AwaitContext */); + return inContext(262144 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -8713,34 +13231,46 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } function nextToken() { - return token = scanner.scan(); + return currentToken = scanner.scan(); } function reScanGreaterToken() { - return token = scanner.reScanGreaterToken(); + return currentToken = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return token = scanner.reScanSlashToken(); + return currentToken = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return token = scanner.reScanTemplateToken(); + return currentToken = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return token = scanner.scanJsxIdentifier(); + return currentToken = scanner.scanJsxIdentifier(); } function scanJsxText() { - return token = scanner.scanJsxToken(); + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); } function speculationHelper(callback, isLookAhead) { // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; // Note: it is not actually necessary to save/restore the context flags here. That's // because the saving/restoring of these flags happens naturally through the recursive // descent nature of our parser. However, we still store this here just so we can - // assert that that invariant holds. + // assert that invariant holds. var saveContextFlags = contextFlags; // If we're only looking ahead, then tell the scanner to only lookahead as well. // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the @@ -8752,7 +13282,7 @@ var ts; // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -8775,24 +13305,24 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token === 69 /* Identifier */) { + if (token() === 69 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token === 114 /* YieldKeyword */ && inYieldContext()) { + if (token() === 114 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token === 119 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token > 105 /* LastReservedWord */; + return token() > 105 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token === kind) { + if (token() === kind) { if (shouldAdvance) { nextToken(); } @@ -8808,14 +13338,14 @@ var ts; return false; } function parseOptional(t) { - if (token === t) { + if (token() === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token === t) { + if (token() === t) { return parseTokenNode(); } return undefined; @@ -8825,21 +13355,21 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token); + var node = createNode(token()); nextToken(); return finishNode(node); } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token === 16 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 16 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } @@ -8855,7 +13385,18 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new NodeConstructor(kind, pos, pos); + return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : + kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -8867,7 +13408,7 @@ var ts; // flag so that we don't mark any subsequent nodes. if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 67108864 /* ThisNodeHasError */; + node.flags |= 524288 /* ThisNodeHasError */; } return node; } @@ -8884,7 +13425,7 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); + return identifiers[text] || (identifiers[text] = text); } // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for @@ -8894,8 +13435,8 @@ var ts; if (isIdentifier) { var node = createNode(69 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token !== 69 /* Identifier */) { - node.originalKeywordKind = token; + if (token() !== 69 /* Identifier */) { + node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -8907,18 +13448,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token) || - token === 9 /* StringLiteral */ || - token === 8 /* NumericLiteral */; + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */) { + if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { return parseLiteralNode(/*internName*/ true); } - if (allowComputedPropertyNames && token === 19 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 19 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -8930,7 +13471,7 @@ var ts; return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { - return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { // PropertyName [Yield]: @@ -8946,7 +13487,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8956,40 +13497,40 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token === 74 /* ConstKeyword */) { + if (token() === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. return nextToken() === 81 /* EnumKeyword */; } - if (token === 82 /* ExportKeyword */) { + if (token() === 82 /* ExportKeyword */) { nextToken(); - if (token === 77 /* DefaultKeyword */) { + if (token() === 77 /* DefaultKeyword */) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token !== 37 /* AsteriskToken */ && token !== 116 /* AsKeyword */ && token !== 15 /* OpenBraceToken */ && canFollowModifier(); + return token() !== 37 /* AsteriskToken */ && token() !== 116 /* AsKeyword */ && token() !== 15 /* OpenBraceToken */ && canFollowModifier(); } - if (token === 77 /* DefaultKeyword */) { + if (token() === 77 /* DefaultKeyword */) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token === 113 /* StaticKeyword */) { + if (token() === 113 /* StaticKeyword */) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token === 19 /* OpenBracketToken */ - || token === 15 /* OpenBraceToken */ - || token === 37 /* AsteriskToken */ - || token === 22 /* DotDotDotToken */ + return token() === 19 /* OpenBracketToken */ + || token() === 15 /* OpenBraceToken */ + || token() === 37 /* AsteriskToken */ + || token() === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token === 73 /* ClassKeyword */ || token === 87 /* FunctionKeyword */ || - (token === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 73 /* ClassKeyword */ || token() === 87 /* FunctionKeyword */ || + (token() === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -9007,9 +13548,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; + return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -9017,19 +13558,19 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token === 23 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); + return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -9044,23 +13585,23 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); case 17 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 18 /* TypeArguments */: case 19 /* TupleElementTypes */: - return token === 24 /* CommaToken */ || isStartOfType(); + return token() === 24 /* CommaToken */ || isStartOfType(); case 20 /* HeritageClauses */: return isHeritageClause(); case 21 /* ImportOrExportSpecifiers */: - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token) || token === 15 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; case 22 /* JSDocFunctionParameters */: @@ -9073,7 +13614,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token === 15 /* OpenBraceToken */); + ts.Debug.assert(token() === 15 /* OpenBraceToken */); if (nextToken() === 16 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: @@ -9093,11 +13634,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token === 106 /* ImplementsKeyword */ || - token === 83 /* ExtendsKeyword */) { + if (token() === 106 /* ImplementsKeyword */ || + token() === 83 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -9108,7 +13649,7 @@ var ts; } // True if positioned at a list terminator function isListTerminator(kind) { - if (token === 1 /* EndOfFileToken */) { + if (token() === 1 /* EndOfFileToken */) { // Being at the end of the file ends all lists. return true; } @@ -9121,43 +13662,43 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 21 /* ImportOrExportSpecifiers */: - return token === 16 /* CloseBraceToken */; + return token() === 16 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; + return token() === 16 /* CloseBraceToken */ || token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + return token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 17 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */ || token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */; + return token() === 18 /* CloseParenToken */ || token() === 23 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 19 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token === 20 /* CloseBracketToken */; + return token() === 20 /* CloseBracketToken */; case 16 /* Parameters */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: // Tokens other than '>' are here for better error recovery - return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */; + return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; case 20 /* HeritageClauses */: - return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */; + return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */; + return token() === 27 /* GreaterThanToken */ || token() === 39 /* SlashToken */; case 14 /* JsxChildren */: - return token === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); case 22 /* JSDocFunctionParameters */: - return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */; + return token() === 18 /* CloseParenToken */ || token() === 54 /* ColonToken */ || token() === 16 /* CloseBraceToken */; case 23 /* JSDocTypeArguments */: - return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */; + return token() === 27 /* GreaterThanToken */ || token() === 16 /* CloseBraceToken */; case 25 /* JSDocTupleTypes */: - return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */; + return token() === 20 /* CloseBracketToken */ || token() === 16 /* CloseBraceToken */; case 24 /* JSDocRecordMembers */: - return token === 16 /* CloseBraceToken */; + return token() === 16 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -9168,14 +13709,14 @@ var ts; } // in the case where we're parsing the variable declarator of a 'for-in' statement, we // are done if we see an 'in' keyword in front of us. Same with for-of - if (isInOrOfKeyword(token)) { + if (isInOrOfKeyword(token())) { return true; } // ERROR RECOVERY TWEAK: // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token === 34 /* EqualsGreaterThanToken */) { + if (token() === 34 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -9196,8 +13737,7 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); @@ -9259,7 +13799,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 197132288 /* ContextFlags */; + var nodeContextFlags = node.flags & 1540096 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -9494,8 +14034,7 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { @@ -9516,7 +14055,7 @@ var ts; // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimiter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9542,11 +14081,7 @@ var ts; return result; } function createMissingList() { - var pos = getNodePos(); - var result = []; - result.pos = pos; - result.end = pos; - return result; + return createNodeArray(); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -9587,7 +14122,7 @@ var ts; // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". // In the first case though, ASI will not take effect because there is not a // line terminator after the identifier or keyword. - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, @@ -9602,8 +14137,7 @@ var ts; var template = createNode(189 /* TemplateExpression */); template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); - var templateSpans = []; - templateSpans.pos = getNodePos(); + var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); } while (ts.lastOrUndefined(templateSpans).literal.kind === 13 /* TemplateMiddle */); @@ -9615,7 +14149,7 @@ var ts; var span = createNode(197 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16 /* CloseBraceToken */) { + if (token() === 16 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -9625,14 +14159,11 @@ var ts; span.literal = literal; return finishNode(span); } - function parseStringLiteralTypeNode() { - return parseLiteralLikeNode(166 /* StringLiteralType */, /*internName*/ true); - } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token, internName); + return parseLiteralLikeNode(token(), internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token, /*internName*/ false); + return parseLiteralLikeNode(token(), /*internName*/ false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -9665,7 +14196,7 @@ var ts; var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); var node = createNode(155 /* TypeReference */, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token === 25 /* LessThanToken */) { + if (!scanner.hasPrecedingLineBreak() && token() === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); @@ -9713,7 +14244,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { return parseBracketedList(17 /* TypeParameters */, parseTypeParameter, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } } @@ -9724,28 +14255,22 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */ || token === 97 /* ThisKeyword */; - } - function setModifiers(node, modifiers) { - if (modifiers) { - node.flags |= modifiers.flags; - node.modifiers = modifiers; - } + return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; } function parseParameter() { var node = createNode(142 /* Parameter */); - if (token === 97 /* ThisKeyword */) { + if (token() === 97 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { // in cases like // 'use strict' // function foo(static) @@ -9837,10 +14362,10 @@ var ts; } fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token !== 19 /* OpenBracketToken */) { + if (token() !== 19 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -9863,10 +14388,10 @@ var ts; // [] // nextToken(); - if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { + if (token() === 22 /* DotDotDotToken */ || token() === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { nextToken(); if (isIdentifier()) { return true; @@ -9882,23 +14407,23 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */) { + if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token !== 53 /* QuestionToken */) { + if (token() !== 53 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; + return token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || token() === 20 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153 /* IndexSignature */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); @@ -9907,69 +14432,70 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { var method = createNode(146 /* MethodSignature */, fullStart); - setModifiers(method, modifiers); + method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); parseTypeMemberSemicolon(); - return finishNode(method); + return addJSDocComment(finishNode(method)); } else { var property = createNode(144 /* PropertySignature */, fullStart); - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56 /* EqualsToken */) { + if (token() === 56 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } } function isTypeMemberStart() { var idToken; // Return true if we have the start of a signature member - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); nextToken(); } // Index signatures and computed property names are type members - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token === 17 /* OpenParenToken */ || - token === 25 /* LessThanToken */ || - token === 53 /* QuestionToken */ || - token === 54 /* ColonToken */ || + return token() === 17 /* OpenParenToken */ || + token() === 25 /* LessThanToken */ || + token() === 53 /* QuestionToken */ || + token() === 54 /* ColonToken */ || + token() === 24 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return parseSignatureMember(151 /* CallSignature */); } - if (token === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + if (token() === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152 /* ConstructSignature */); } var fullStart = getNodePos(); @@ -9981,7 +14507,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; + return token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */; } function parseTypeLiteral() { var node = createNode(159 /* TypeLiteral */); @@ -10021,10 +14547,19 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token === 21 /* DotToken */ ? undefined : node; + return token() === 21 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(166 /* LiteralType */); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8 /* NumericLiteral */; } function parseNonArrayType() { - switch (token) { + switch (token()) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10036,13 +14571,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9 /* StringLiteral */: - return parseStringLiteralTypeNode(); + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 36 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); case 103 /* VoidKeyword */: case 93 /* NullKeyword */: return parseTokenNode(); case 97 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -10062,7 +14602,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10079,7 +14619,12 @@ var ts; case 25 /* LessThanToken */: case 92 /* NewKeyword */: case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: return true; + case 36 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral); case 17 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. @@ -10090,7 +14635,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10104,9 +14649,8 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { - var types = [type]; - types.pos = type.pos; + if (token() === operator) { + var types = createNodeArray([type], type.pos); while (parseOptional(operator)) { types.push(parseConstituentType()); } @@ -10124,21 +14668,21 @@ var ts; return parseUnionOrIntersectionType(162 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); } function isStartOfFunctionType() { - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { return true; } - return token === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token === 97 /* ThisKeyword */) { + if (isIdentifier() || token() === 97 /* ThisKeyword */) { nextToken(); return true; } - if (token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */) { + if (token() === 19 /* OpenBracketToken */ || token() === 15 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -10148,7 +14692,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { + if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -10156,17 +14700,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || - token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */) { + if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || + token() === 53 /* QuestionToken */ || token() === 56 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token === 18 /* CloseParenToken */) { + if (token() === 18 /* CloseParenToken */) { nextToken(); - if (token === 34 /* EqualsGreaterThanToken */) { + if (token() === 34 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -10189,7 +14733,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10197,13 +14741,13 @@ var ts; function parseType() { // The rules about 'yield' only apply to actual code/expression contexts. They don't // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(41943040 /* TypeExcludesFlags */, parseTypeWorker); + return doOutsideOfContext(327680 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156 /* FunctionType */); } - if (token === 92 /* NewKeyword */) { + if (token() === 92 /* NewKeyword */) { return parseFunctionOrConstructorType(157 /* ConstructorType */); } return parseUnionTypeOrHigher(); @@ -10213,7 +14757,7 @@ var ts; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: case 93 /* NullKeyword */: @@ -10241,7 +14785,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10271,10 +14815,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token !== 15 /* OpenBraceToken */ && - token !== 87 /* FunctionKeyword */ && - token !== 73 /* ClassKeyword */ && - token !== 55 /* AtToken */ && + return token() !== 15 /* OpenBraceToken */ && + token() !== 87 /* FunctionKeyword */ && + token() !== 73 /* ClassKeyword */ && + token() !== 55 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -10297,7 +14841,7 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token !== 56 /* EqualsToken */) { + if (token() !== 56 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse // this as an equals-value clause with a missing equals. @@ -10306,7 +14850,7 @@ var ts; // it's more likely that a { would be a allowed (as an object literal). While this // is also allowed for parameters, the risk is that we consume the { as an object // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15 /* OpenBraceToken */) || !isStartOfExpression()) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15 /* OpenBraceToken */) || !isStartOfExpression()) { // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - // do not try to parse initializer return undefined; @@ -10328,7 +14872,7 @@ var ts; // // Note: for ease of implementation we treat productions '2' and '3' as the same thing. // (i.e. they're both BinaryExpressions with an assignment operator in it). - // First, do the simple check if we have a YieldExpression (production '5'). + // First, do the simple check if we have a YieldExpression (production '6'). if (isYieldExpression()) { return parseYieldExpression(); } @@ -10360,7 +14904,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { + if (expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -10376,7 +14920,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114 /* YieldKeyword */) { + if (token() === 114 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -10412,7 +14956,7 @@ var ts; // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token === 37 /* AsteriskToken */ || isStartOfExpression())) { + (token() === 37 /* AsteriskToken */ || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -10424,11 +14968,11 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180 /* ArrowFunction */, asyncModifier.pos); - setModifiers(node, asyncModifier); + node.modifiers = asyncModifier; } else { node = createNode(180 /* ArrowFunction */, identifier.pos); @@ -10436,12 +14980,11 @@ var ts; var parameter = createNode(142 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = [parameter]; - node.parameters.pos = parameter.pos; + node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function tryParseParenthesizedArrowFunctionExpression() { var triState = isParenthesizedArrowFunctionExpression(); @@ -10460,25 +15003,25 @@ var ts; // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = !!(arrowFunction.flags & 256 /* Async */); + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. - var lastToken = token; + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 /* EqualsGreaterThanToken */ || lastToken === 15 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return finishNode(arrowFunction); + return addJSDocComment(finishNode(arrowFunction)); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */ || token === 118 /* AsyncKeyword */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */ || token() === 118 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token === 34 /* EqualsGreaterThanToken */) { + if (token() === 34 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -10488,16 +15031,16 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token !== 17 /* OpenParenToken */ && token !== 25 /* LessThanToken */) { + if (token() !== 17 /* OpenParenToken */ && token() !== 25 /* LessThanToken */) { return 0 /* False */; } } - var first = token; + var first = token(); var second = nextToken(); if (first === 17 /* OpenParenToken */) { if (second === 18 /* CloseParenToken */) { @@ -10586,7 +15129,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); @@ -10600,16 +15143,16 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token === 34 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 34 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { return 1 /* True */; } } @@ -10617,8 +15160,8 @@ var ts; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(180 /* ArrowFunction */); - setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 256 /* Async */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -10639,19 +15182,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token !== 34 /* EqualsGreaterThanToken */ && token !== 15 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 34 /* EqualsGreaterThanToken */ && token() !== 15 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); } - if (token !== 23 /* SemicolonToken */ && - token !== 87 /* FunctionKeyword */ && - token !== 73 /* ClassKeyword */ && + if (token() !== 23 /* SemicolonToken */ && + token() !== 87 /* FunctionKeyword */ && + token() !== 73 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -10724,16 +15267,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token === 38 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 38 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token === 90 /* InKeyword */ && inDisallowInContext()) { + if (token() === 90 /* InKeyword */ && inDisallowInContext()) { break; } - if (token === 116 /* AsKeyword */) { + if (token() === 116 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -10754,13 +15297,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token === 90 /* InKeyword */) { + if (inDisallowInContext() && token() === 90 /* InKeyword */) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token) { + switch (token()) { case 52 /* BarBarToken */: return 1; case 51 /* AmpersandAmpersandToken */: @@ -10817,7 +15360,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -10841,7 +15384,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119 /* AwaitKeyword */) { + if (token() === 119 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -10857,25 +15400,42 @@ var ts; return finishNode(node); } /** - * Parse ES7 unary expression and await expression + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] * - * ES7 UnaryExpression: - * 1) SimpleUnaryExpression[?yield] - * 2) IncrementExpression[?yield] ** UnaryExpression[?yield] */ function parseUnaryExpressionOrHigher() { - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - if (isIncrementExpression()) { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token === 38 /* AsteriskAsteriskToken */ ? + return token() === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token; + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token === 38 /* AsteriskAsteriskToken */) { + if (token() === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -10889,8 +15449,8 @@ var ts; /** * Parse ES7 simple-unary expression or higher: * - * ES7 SimpleUnaryExpression: - * 1) IncrementExpression[?yield] + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] * 2) delete UnaryExpression[?yield] * 3) void UnaryExpression[?yield] * 4) typeof UnaryExpression[?yield] @@ -10898,9 +15458,10 @@ var ts; * 6) - UnaryExpression[?yield] * 7) ~ UnaryExpression[?yield] * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] */ function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10917,6 +15478,10 @@ var ts; // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); + case 119 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } @@ -10924,17 +15489,17 @@ var ts; /** * Check if the current token can possibly be an ES7 increment expression. * - * ES7 IncrementExpression: + * ES7 UpdateExpression: * LeftHandSideExpression[?Yield] * LeftHandSideExpression[?Yield][no LineTerminator here]++ * LeftHandSideExpression[?Yield][no LineTerminator here]-- * ++LeftHandSideExpression[?Yield] * --LeftHandSideExpression[?Yield] */ - function isIncrementExpression() { + function isUpdateExpression() { // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10942,6 +15507,7 @@ var ts; case 78 /* DeleteKeyword */: case 101 /* TypeOfKeyword */: case 103 /* VoidKeyword */: + case 119 /* AwaitKeyword */: return false; case 25 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression @@ -10966,23 +15532,23 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseIncrementExpression() { - if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { + if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; - node.operator = token; + node.operator = token(); nextToken(); return finishNode(node); } @@ -11019,7 +15585,7 @@ var ts; // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - var expression = token === 95 /* SuperKeyword */ + var expression = token() === 95 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); // Now, we *may* be complete. However, we might have consumed the start of a @@ -11079,7 +15645,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token === 17 /* OpenParenToken */ || token === 21 /* DotToken */ || token === 19 /* OpenBracketToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 21 /* DotToken */ || token() === 19 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. @@ -11131,7 +15697,7 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token === 25 /* LessThanToken */) { + if (inExpressionContext && token() === 25 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -11148,11 +15714,11 @@ var ts; } function parseJsxText() { var node = createNode(244 /* JsxText */, scanner.getStartPos()); - token = scanner.scanJsxToken(); + currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token) { + switch (token()) { case 244 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: @@ -11160,20 +15726,19 @@ var ts; case 25 /* LessThanToken */: return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); } - ts.Debug.fail("Unknown JSX child kind " + token); + ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = []; - result.pos = scanner.getStartPos(); + var result = createNodeArray(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - token = scanner.reScanJsxToken(); - if (token === 26 /* LessThanSlashToken */) { + currentToken = scanner.reScanJsxToken(); + if (token() === 26 /* LessThanSlashToken */) { // Closing tag break; } - else if (token === 1 /* EndOfFileToken */) { + else if (token() === 1 /* EndOfFileToken */) { // If we hit EOF, issue the error at the tag that lacks the closing element // rather than at the end of the file (which is useless) parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); @@ -11191,7 +15756,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute); var node; - if (token === 27 /* GreaterThanToken */) { + if (token() === 27 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors @@ -11220,7 +15785,7 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token === 97 /* ThisKeyword */ ? + var expression = token() === 97 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21 /* DotToken */)) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); @@ -11233,7 +15798,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); - if (token !== 16 /* CloseBraceToken */) { + if (token() !== 16 /* CloseBraceToken */) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -11246,14 +15811,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246 /* JsxAttribute */); node.name = parseIdentifierName(); - if (parseOptional(56 /* EqualsToken */)) { - switch (token) { + if (token() === 56 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); break; @@ -11303,7 +15868,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; @@ -11316,7 +15881,7 @@ var ts; indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. - if (token !== 20 /* CloseBracketToken */) { + if (token() !== 20 /* CloseBracketToken */) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { var literal = indexedAccess.argumentExpression; @@ -11327,10 +15892,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { + if (token() === 11 /* NoSubstitutionTemplateLiteral */ || token() === 12 /* TemplateHead */) { var tagExpression = createNode(176 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; - tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -11342,7 +15907,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -11358,7 +15923,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token === 17 /* OpenParenToken */) { + else if (token() === 17 /* OpenParenToken */) { var callExpr = createNode(174 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -11390,7 +15955,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17 /* OpenParenToken */: // foo( // this case are the only case where this token can legally follow a type argument // list. So we definitely want to treat this as a type arg list. @@ -11426,7 +15991,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: @@ -11482,8 +16047,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : + return token() === 22 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -11501,7 +16066,7 @@ var ts; } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123 /* GetKeyword */)) { - return addJSDocComment(parseAccessorDeclaration(149 /* GetAccessor */, fullStart, decorators, modifiers)); + return parseAccessorDeclaration(149 /* GetAccessor */, fullStart, decorators, modifiers); } else if (parseContextualModifier(131 /* SetKeyword */)) { return parseAccessorDeclaration(150 /* SetAccessor */, fullStart, decorators, modifiers); @@ -11521,7 +16086,7 @@ var ts; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } // check if it is short-hand property assignment or normal property assignment @@ -11529,7 +16094,7 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 /* CommaToken */ || token === 16 /* CloseBraceToken */ || token === 56 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 /* CommaToken */ || token() === 16 /* CloseBraceToken */ || token() === 56 /* EqualsToken */); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; @@ -11572,11 +16137,11 @@ var ts; setDecoratorContext(/*val*/ false); } var node = createNode(179 /* FunctionExpression */); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256 /* Async */); + var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -11597,7 +16162,7 @@ var ts; parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token === 17 /* OpenParenToken */) { + if (node.typeArguments || token() === 17 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -11606,6 +16171,9 @@ var ts; function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var node = createNode(199 /* Block */); if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); } @@ -11677,8 +16245,8 @@ var ts; parseExpected(86 /* ForKeyword */); parseExpected(17 /* OpenParenToken */); var initializer = undefined; - if (token !== 23 /* SemicolonToken */) { - if (token === 102 /* VarKeyword */ || token === 108 /* LetKeyword */ || token === 74 /* ConstKeyword */) { + if (token() !== 23 /* SemicolonToken */) { + if (token() === 102 /* VarKeyword */ || token() === 108 /* LetKeyword */ || token() === 74 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -11704,11 +16272,11 @@ var ts; var forStatement = createNode(206 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); - if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { + if (token() !== 23 /* SemicolonToken */ && token() !== 18 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23 /* SemicolonToken */); - if (token !== 18 /* CloseParenToken */) { + if (token() !== 18 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18 /* CloseParenToken */); @@ -11760,7 +16328,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213 /* SwitchStatement */); @@ -11794,10 +16362,10 @@ var ts; var node = createNode(216 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token === 85 /* FinallyKeyword */) { + if (!node.catchClause || token() === 85 /* FinallyKeyword */) { parseExpected(85 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } @@ -11840,19 +16408,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token) || token === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token) { + switch (token()) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -11902,16 +16470,16 @@ var ts; continue; case 137 /* GlobalKeyword */: nextToken(); - return token === 15 /* OpenBraceToken */ || token === 69 /* Identifier */ || token === 82 /* ExportKeyword */; + return token() === 15 /* OpenBraceToken */ || token() === 69 /* Identifier */ || token() === 82 /* ExportKeyword */; case 89 /* ImportKeyword */: nextToken(); - return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || - token === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 /* StringLiteral */ || token() === 37 /* AsteriskToken */ || + token() === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); case 82 /* ExportKeyword */: nextToken(); - if (token === 56 /* EqualsToken */ || token === 37 /* AsteriskToken */ || - token === 15 /* OpenBraceToken */ || token === 77 /* DefaultKeyword */ || - token === 116 /* AsKeyword */) { + if (token() === 56 /* EqualsToken */ || token() === 37 /* AsteriskToken */ || + token() === 15 /* OpenBraceToken */ || token() === 77 /* DefaultKeyword */ || + token() === 116 /* AsKeyword */) { return true; } continue; @@ -11927,7 +16495,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55 /* AtToken */: case 23 /* SemicolonToken */: case 15 /* OpenBraceToken */: @@ -11980,7 +16548,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */; + return isIdentifier() || token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -11988,7 +16556,7 @@ var ts; return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token) { + switch (token()) { case 23 /* SemicolonToken */: return parseEmptyStatement(); case 15 /* OpenBraceToken */: @@ -12061,7 +16629,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -12084,7 +16652,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82 /* ExportKeyword */: nextToken(); - switch (token) { + switch (token()) { case 77 /* DefaultKeyword */: case 56 /* EqualsToken */: return parseExportAssignment(fullStart, decorators, modifiers); @@ -12100,17 +16668,17 @@ var ts; var node = createMissingNode(239 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; return finishNode(node); } } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token !== 15 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 15 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -12118,7 +16686,7 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { return createNode(193 /* OmittedExpression */); } var node = createNode(169 /* BindingElement */); @@ -12131,7 +16699,7 @@ var ts; var node = createNode(169 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token !== 54 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 54 /* ColonToken */) { node.name = propertyName; } else { @@ -12157,13 +16725,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */ || isIdentifier(); + return token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -12172,21 +16740,21 @@ var ts; var node = createNode(218 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token)) { + if (!isInOrOfKeyword(token())) { node.initializer = parseInitializer(/*inParameter*/ false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219 /* VariableDeclarationList */); - switch (token) { + switch (token()) { case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: - node.flags |= 1024 /* Let */; + node.flags |= 1 /* Let */; break; case 74 /* ConstKeyword */: - node.flags |= 2048 /* Const */; + node.flags |= 2 /* Const */; break; default: ts.Debug.fail(); @@ -12201,7 +16769,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -12218,7 +16786,7 @@ var ts; function parseVariableStatement(fullStart, decorators, modifiers) { var node = createNode(200 /* VariableStatement */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return addJSDocComment(finishNode(node)); @@ -12226,12 +16794,12 @@ var ts; function parseFunctionDeclaration(fullStart, decorators, modifiers) { var node = createNode(220 /* FunctionDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); - node.name = node.flags & 512 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256 /* Async */); + var isAsync = ts.hasModifier(node, 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); @@ -12239,7 +16807,7 @@ var ts; function parseConstructorDeclaration(pos, decorators, modifiers) { var node = createNode(148 /* Constructor */, pos); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(121 /* ConstructorKeyword */); fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); @@ -12248,12 +16816,12 @@ var ts; function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { var method = createNode(147 /* MethodDeclaration */, fullStart); method.decorators = decorators; - setModifiers(method, modifiers); + method.modifiers = modifiers; method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 256 /* Async */); + var isAsync = ts.hasModifier(method, 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); @@ -12261,7 +16829,7 @@ var ts; function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { var property = createNode(145 /* PropertyDeclaration */, fullStart); property.decorators = decorators; - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -12274,11 +16842,11 @@ var ts; // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = modifiers && modifiers.flags & 32 /* Static */ + property.initializer = ts.hasModifier(property, 32 /* Static */) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(8388608 /* YieldContext */ | 4194304 /* DisallowInContext */, parseNonParameterInitializer); + : doOutsideOfContext(65536 /* YieldContext */ | 32768 /* DisallowInContext */, parseNonParameterInitializer); parseSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); @@ -12286,7 +16854,7 @@ var ts; // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -12299,11 +16867,11 @@ var ts; function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.name = parsePropertyName(); fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -12319,12 +16887,12 @@ var ts; } function isClassMemberStart() { var idToken; - if (token === 55 /* AtToken */) { + if (token() === 55 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); // If the idToken is a class modifier (protected, private, public, and static), it is // certain that we are starting to parse class member. This allows better error recovery // Example: @@ -12336,17 +16904,17 @@ var ts; } nextToken(); } - if (token === 37 /* AsteriskToken */) { + if (token() === 37 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. // This can either be an identifier or the 'get' or 'set' keywords. if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... @@ -12357,7 +16925,7 @@ var ts; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. - switch (token) { + switch (token()) { case 17 /* OpenParenToken */: // Method declaration case 25 /* LessThanToken */: // Generic Method declaration case 54 /* ColonToken */: // Type Annotation for declaration @@ -12382,13 +16950,15 @@ var ts; if (!parseOptional(55 /* AtToken */)) { break; } - if (!decorators) { - decorators = []; - decorators.pos = decoratorStart; - } var decorator = createNode(143 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - decorators.push(finishNode(decorator)); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } } if (decorators) { decorators.end = getNodeEnd(); @@ -12403,12 +16973,11 @@ var ts; * In such situations, 'permitInvalidConstAsModifier' should be set to true. */ function parseModifiers(permitInvalidConstAsModifier) { - var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; - if (token === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + var modifierKind = token(); + if (token() === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { // We need to ensure that any subsequent modifiers appear on the same line // so that when 'const' is a standalone declaration, we don't issue an error. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { @@ -12420,37 +16989,33 @@ var ts; break; } } + var modifier = finishNode(createNode(modifierKind, modifierStart)); if (!modifiers) { - modifiers = []; - modifiers.pos = modifierStart; + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); } - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); } if (modifiers) { - modifiers.flags = flags; modifiers.end = scanner.getStartPos(); } return modifiers; } function parseModifiersForArrowFunction() { - var flags = 0; var modifiers; - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; + var modifierKind = token(); nextToken(); - modifiers = []; - modifiers.pos = modifierStart; - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); - modifiers.flags = flags; + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); modifiers.end = scanner.getStartPos(); } return modifiers; } function parseClassElement() { - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { var result = createNode(198 /* SemicolonClassElement */); nextToken(); return finishNode(result); @@ -12462,7 +17027,7 @@ var ts; if (accessor) { return accessor; } - if (token === 121 /* ConstructorKeyword */) { + if (token() === 121 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -12470,17 +17035,17 @@ var ts; } // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name - if (ts.tokenIsIdentifierOrKeyword(token) || - token === 9 /* StringLiteral */ || - token === 8 /* NumericLiteral */ || - token === 37 /* AsteriskToken */ || - token === 19 /* OpenBracketToken */) { + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 37 /* AsteriskToken */ || + token() === 19 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { // treat this as a property declaration with a missing name. - var name_7 = createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, /*questionToken*/ undefined); + var name_10 = createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, /*questionToken*/ undefined); } // 'isClassMemberStart' should have hinted not to attempt parsing. ts.Debug.fail("Should not have attempted to parse class member declaration."); @@ -12497,7 +17062,7 @@ var ts; function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(73 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -12511,7 +17076,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseNameOfClassDeclarationOrExpression() { // implements is a future reserved word so @@ -12524,7 +17089,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -12535,9 +17100,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { + if (token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */) { var node = createNode(251 /* HeritageClause */); - node.token = token; + node.token = token(); nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); @@ -12547,13 +17112,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); } function isHeritageClause() { - return token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + return token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); @@ -12561,18 +17126,18 @@ var ts; function parseInterfaceDeclaration(fullStart, decorators, modifiers) { var node = createNode(222 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(107 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ false); node.members = parseObjectTypeMembers(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { var node = createNode(223 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(134 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -12589,12 +17154,12 @@ var ts; var node = createNode(255 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { var node = createNode(224 /* EnumDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(81 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(15 /* OpenBraceToken */)) { @@ -12604,7 +17169,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseModuleBlock() { var node = createNode(226 /* ModuleBlock */, scanner.getStartPos()); @@ -12621,29 +17186,29 @@ var ts; var node = createNode(225 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 4096 /* Namespace */; + var namespaceFlag = flags & 16 /* Namespace */; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 1 /* Export */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { var node = createNode(225 /* ModuleDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); - if (token === 137 /* GlobalKeyword */) { + node.modifiers = modifiers; + if (token() === 137 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); - node.flags |= 131072 /* GlobalAugmentation */; + node.flags |= 512 /* GlobalAugmentation */; } else { node.name = parseLiteralNode(/*internName*/ true); } - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -12652,24 +17217,24 @@ var ts; return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = modifiers ? modifiers.flags : 0; - if (token === 137 /* GlobalKeyword */) { + var flags = 0; + if (token() === 137 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126 /* NamespaceKeyword */)) { - flags |= 4096 /* Namespace */; + flags |= 16 /* Namespace */; } else { parseExpected(125 /* ModuleKeyword */); - if (token === 9 /* StringLiteral */) { + if (token() === 9 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 129 /* RequireKeyword */ && + return token() === 129 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -12694,30 +17259,30 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 /* CommaToken */ && token !== 136 /* FromKeyword */) { + if (token() !== 24 /* CommaToken */ && token() !== 136 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; var importEqualsDeclaration = createNode(229 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; - setModifiers(importEqualsDeclaration, modifiers); + importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; parseExpected(56 /* EqualsToken */); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); - return finishNode(importEqualsDeclaration); + return addJSDocComment(finishNode(importEqualsDeclaration)); } } // Import statement var importDeclaration = createNode(230 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; - setModifiers(importDeclaration, modifiers); + importDeclaration.modifiers = modifiers; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || - token === 37 /* AsteriskToken */ || - token === 15 /* OpenBraceToken */) { + token() === 37 /* AsteriskToken */ || + token() === 15 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136 /* FromKeyword */); } @@ -12742,7 +17307,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); + importClause.namedBindings = token() === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); } return finishNode(importClause); } @@ -12760,7 +17325,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9 /* StringLiteral */) { + if (token() === 9 /* StringLiteral */) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -12807,14 +17372,14 @@ var ts; // ExportSpecifier: // IdentifierName // IdentifierName as IdentifierName - var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token === 116 /* AsKeyword */) { + if (token() === 116 /* AsKeyword */) { node.propertyName = identifierName; parseExpected(116 /* AsKeyword */); - checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -12831,7 +17396,7 @@ var ts; function parseExportDeclaration(fullStart, decorators, modifiers) { var node = createNode(236 /* ExportDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(37 /* AsteriskToken */)) { parseExpected(136 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); @@ -12841,7 +17406,7 @@ var ts; // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token === 136 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { parseExpected(136 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } @@ -12852,7 +17417,7 @@ var ts; function parseExportAssignment(fullStart, decorators, modifiers) { var node = createNode(235 /* ExportAssignment */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(56 /* EqualsToken */)) { node.isExportEquals = true; } @@ -12931,7 +17496,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 /* Export */ + return ts.hasModifier(node, 1 /* Export */) || node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 240 /* ExternalModuleReference */ || node.kind === 230 /* ImportDeclaration */ || node.kind === 235 /* ExportAssignment */ @@ -12979,7 +17544,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: case 53 /* QuestionToken */: case 17 /* OpenParenToken */: @@ -12992,13 +17557,14 @@ var ts; case 97 /* ThisKeyword */: return true; } - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 2 /* Latest */, 1 /* JS */); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -13018,12 +17584,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token === 47 /* BarToken */) { + if (token() === 47 /* BarToken */) { var unionType = createNode(261 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token === 56 /* EqualsToken */) { + if (token() === 56 /* EqualsToken */) { var optionalType = createNode(268 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; @@ -13034,20 +17600,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { var arrayType = createNode(260 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } - else if (token === 53 /* QuestionToken */) { + else if (token() === 53 /* QuestionToken */) { var nullableType = createNode(263 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token === 49 /* ExclamationToken */) { + else if (token() === 49 /* ExclamationToken */) { var nonNullableType = createNode(264 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); @@ -13060,7 +17626,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: return parseJSDocAllType(); case 53 /* QuestionToken */: @@ -13087,9 +17653,16 @@ var ts; case 120 /* BooleanKeyword */: case 133 /* SymbolKeyword */: case 103 /* VoidKeyword */: + case 93 /* NullKeyword */: + case 135 /* UndefinedKeyword */: + case 127 /* NeverKeyword */: return parseTokenNode(); + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return parseJSDocLiteralType(); } - // TODO (drosen): Parse string literal types in JSDoc as well. return parseJSDocTypeReference(); } function parseJSDocThisType() { @@ -13119,7 +17692,7 @@ var ts; result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18 /* CloseParenToken */); - if (token === 54 /* ColonToken */) { + if (token() === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13136,12 +17709,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21 /* DotToken */)) { - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); break; } @@ -13176,19 +17749,7 @@ var ts; } function parseJSDocRecordType() { var result = createNode(265 /* JSDocRecordType */); - nextToken(); - result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); - checkForTrailingComma(result.members); - parseExpected(16 /* CloseBraceToken */); - return finishNode(result); - } - function parseJSDocRecordMember() { - var result = createNode(266 /* JSDocRecordMember */); - result.name = parseSimplePropertyName(); - if (token === 54 /* ColonToken */) { - nextToken(); - result.type = parseJSDocType(); - } + result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { @@ -13220,9 +17781,7 @@ var ts; } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); - var types = []; - types.pos = firstType.pos; - types.push(firstType); + var types = createNodeArray([firstType], firstType.pos); while (parseOptional(47 /* BarToken */)) { types.push(parseJSDocType()); } @@ -13234,6 +17793,11 @@ var ts; nextToken(); return finishNode(result); } + function parseJSDocLiteralType() { + var result = createNode(282 /* JSDocLiteralType */); + result.literal = parseLiteralTypeNode(); + return finishNode(result); + } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); // skip the ? @@ -13247,12 +17811,12 @@ var ts; // Foo // Foo(?= // (?| - if (token === 24 /* CommaToken */ || - token === 16 /* CloseBraceToken */ || - token === 18 /* CloseParenToken */ || - token === 27 /* GreaterThanToken */ || - token === 56 /* EqualsToken */ || - token === 47 /* BarToken */) { + if (token() === 24 /* CommaToken */ || + token() === 16 /* CloseBraceToken */ || + token() === 18 /* CloseParenToken */ || + token() === 27 /* GreaterThanToken */ || + token() === 56 /* EqualsToken */ || + token() === 47 /* BarToken */) { var result = createNode(259 /* JSDocUnknownType */, pos); return finishNode(result); } @@ -13265,26 +17829,32 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); sourceFile = { languageVariant: 0 /* Standard */, text: content }; - var jsDocComment = parseJSDocCommentWorker(start, length); + var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); - return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -13294,123 +17864,260 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var comments = []; var result; // Check for /** (JSDoc opening part) - if (content.charCodeAt(start) === 47 /* slash */ && - content.charCodeAt(start + 1) === 42 /* asterisk */ && - content.charCodeAt(start + 2) === 42 /* asterisk */ && - content.charCodeAt(start + 3) !== 42 /* asterisk */) { - // + 3 for leading /**, - 5 in total for /** */ - scanner.scanRange(start + 3, length - 5, function () { - // Initially we can parse out a tag. We also have seen a starting asterisk. - // This is so that /** * @type */ doesn't parse. - var canParseTag = true; - var seenAsterisk = true; + if (!isJsDocStart(content, start)) { + return result; + } + // + 3 for leading /**, - 5 in total for /** */ + scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var advanceToken = true; + var state = 1 /* SawAsterisk */; + var margin = undefined; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5 /* WhitespaceTrivia */) { nextJSDocToken(); - while (token !== 1 /* EndOfFileToken */) { - switch (token) { - case 55 /* AtToken */: - if (canParseTag) { - parseTag(); - } - // This will take us to the end of the line, so it's OK to parse a tag on the next pass through the loop - seenAsterisk = false; - break; - case 4 /* NewLineTrivia */: - // After a line break, we can parse a tag, and we haven't seen an asterisk on the next line yet - canParseTag = true; - seenAsterisk = false; - break; - case 37 /* AsteriskToken */: - if (seenAsterisk) { - // If we've already seen an asterisk, then we can no longer parse a tag on this line - canParseTag = false; - } + } + if (token() === 4 /* NewLineTrivia */) { + state = 0 /* BeginningOfLine */; + nextJSDocToken(); + } + while (token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 55 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingNewlines(comments); + parseTag(indent); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 37 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { // Ignore the first asterisk on a line - seenAsterisk = true; - break; - case 69 /* Identifier */: - // Anything else is doc comment text. We can't do anything with it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - canParseTag = false; - break; - case 1 /* EndOfFileToken */: - break; - } + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 69 /* Identifier */: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + pushComment(scanner.getTokenText()); + state = 2 /* SavingComments */; + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */ || margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break; + default: + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { nextJSDocToken(); } - result = createJSDocComment(); - }); - } - return result; - function createJSDocComment() { - if (!tags) { - return undefined; + else { + advanceToken = true; + } } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */; + } + function createJSDocComment() { var result = createNode(273 /* JSDocComment */, start); result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 /* WhitespaceTrivia */ || token === 4 /* NewLineTrivia */) { + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } } - function parseTag() { - ts.Debug.assert(token === 55 /* AtToken */); + function parseTag(indent) { + ts.Debug.assert(token() === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return; } - var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); - addTag(tag); - } - function handleTag(atToken, tagName) { + var tag; if (tagName) { switch (tagName.text) { case "param": - return handleParamTag(atToken, tagName); + tag = parseParamTag(atToken, tagName); + break; case "return": case "returns": - return handleReturnTag(atToken, tagName); + tag = parseReturnTag(atToken, tagName); + break; case "template": - return handleTemplateTag(atToken, tagName); + tag = parseTemplateTag(atToken, tagName); + break; case "type": - return handleTypeTag(atToken, tagName); + tag = parseTypeTag(atToken, tagName); + break; case "typedef": - return handleTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; } } - return undefined; + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + // a badly malformed tag should not be added to the list of tags + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); } - function handleUnknownTag(atToken, tagName) { + function parseTagComments(indent) { + var comments = []; + var state = 1 /* SawAsterisk */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 55 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 55 /* AtToken */: + // Done + break; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 37 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += scanner.getTokenText().length; + break; + } + // FALLTHROUGH otherwise to record the * as a comment + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + if (token() === 55 /* AtToken */) { + // Done + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { var result = createNode(274 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } - function addTag(tag) { - if (tag) { - if (!tags) { - tags = []; - tags.pos = tag.pos; - } - tags.push(tag); - tags.end = tag.end; + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); } + else { + tags.push(tag); + } + tags.end = tag.end; } function tryParseTypeExpression() { - if (token !== 15 /* OpenBraceToken */) { - return undefined; - } - var typeExpression = parseJSDocTypeExpression(); - return typeExpression; + return tryParse(function () { + skipWhitespace(); + if (token() !== 15 /* OpenBraceToken */) { + return undefined; + } + return parseJSDocTypeExpression(); + }); } - function handleParamTag(atToken, tagName) { + function parseParamTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name; @@ -13418,6 +18125,7 @@ var ts; // Looking for something like '[foo]' or 'foo' if (parseOptionalToken(19 /* OpenBracketToken */)) { name = parseJSDocIdentifierName(); + skipWhitespace(); isBracketed = true; // May have an optional default, e.g. '[foo = 42]' if (parseOptionalToken(56 /* EqualsToken */)) { @@ -13425,7 +18133,7 @@ var ts; } parseExpected(20 /* CloseBracketToken */); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -13448,10 +18156,11 @@ var ts; result.preParameterName = preName; result.typeExpression = typeExpression; result.postParameterName = postName; + result.parameterName = postName || preName; result.isBracketed = isBracketed; return finishNode(result); } - function handleReturnTag(atToken, tagName) { + function parseReturnTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 276 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -13461,7 +18170,7 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handleTypeTag(atToken, tagName) { + function parseTypeTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 277 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -13471,10 +18180,11 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handlePropertyTag(atToken, tagName) { + function parsePropertyTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name = parseJSDocIdentifierName(); + skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, ts.Diagnostics.Identifier_expected); return undefined; @@ -13486,7 +18196,7 @@ var ts; result.typeExpression = typeExpression; return finishNode(result); } - function handleTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var typedefTag = createNode(279 /* JSDocTypedefTag */, atToken.pos); @@ -13494,12 +18204,13 @@ var ts; typedefTag.tagName = tagName; typedefTag.name = parseJSDocIdentifierName(); typedefTag.typeExpression = typeExpression; + skipWhitespace(); if (typeExpression) { if (typeExpression.type.kind === 267 /* JSDocTypeReference */) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69 /* Identifier */) { - var name_8 = jsDocTypeReference.name; - if (name_8.text === "Object") { + var name_11 = jsDocTypeReference.name; + if (name_11.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -13518,12 +18229,15 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token !== 1 /* EndOfFileToken */ && !parentTagTerminated) { + while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { nextJSDocToken(); - switch (token) { + switch (token()) { case 55 /* AtToken */: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); + if (!parentTagTerminated) { + resumePos = scanner.getStartPos(); + } } seenAsterisk = false; break; @@ -13549,11 +18263,12 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token === 55 /* AtToken */); + ts.Debug.assert(token() === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return false; } @@ -13563,38 +18278,39 @@ var ts; // already has a @type tag, terminate the parent tag now. return false; } - parentTag.jsDocTypeTag = handleTypeTag(atToken, tagName); + parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); return true; case "prop": case "property": if (!parentTag.jsDocPropertyTags) { parentTag.jsDocPropertyTags = []; } - var propertyTag = handlePropertyTag(atToken, tagName); + var propertyTag = parsePropertyTag(atToken, tagName); parentTag.jsDocPropertyTags.push(propertyTag); return true; } return false; } - function handleTemplateTag(atToken, tagName) { + function parseTemplateTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 278 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } // Type parameter list looks like '@template T,U,V' - var typeParameters = []; - typeParameters.pos = scanner.getStartPos(); + var typeParameters = createNodeArray(); while (true) { - var name_9 = parseJSDocIdentifierName(); - if (!name_9) { + var name_12 = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name_12) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141 /* TypeParameter */, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(141 /* TypeParameter */, name_12.pos); + typeParameter.name = name_12; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { nextJSDocToken(); + skipWhitespace(); } else { break; @@ -13609,10 +18325,10 @@ var ts; return result; } function nextJSDocToken() { - return token = scanner.scanJSDocToken(); + return currentToken = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -14111,7 +18827,6 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.bindTime = 0; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; @@ -14127,7 +18842,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } else if (node.kind === 226 /* ModuleBlock */) { @@ -14183,9 +18898,10 @@ var ts; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { - var start = new Date().getTime(); + ts.performance.mark("beforeBind"); binder(file, options); - ts.bindTime += new Date().getTime() - start; + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -14218,13 +18934,17 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; function bindSourceFile(f, opts) { file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; + skipTransformFlagAggregation = ts.isDeclarationFile(file); Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -14248,6 +18968,7 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; } return bindSourceFile; function createSymbol(flags, name) { @@ -14262,10 +18983,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = {}; + symbol.exports = ts.createMap(); } if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = {}; + symbol.members = ts.createMap(); } if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; @@ -14326,7 +19047,7 @@ var ts; break; case 220 /* FunctionDeclaration */: case 221 /* ClassDeclaration */: - return node.flags & 512 /* Default */ ? "default" : undefined; + return ts.hasModifier(node, 512 /* Default */) ? "default" : undefined; case 269 /* JSDocFunctionType */: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; case 142 /* Parameter */: @@ -14335,7 +19056,7 @@ var ts; ts.Debug.assert(node.parent.kind === 269 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); - return "p" + index; + return "arg" + index; case 279 /* JSDocTypedefTag */: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; @@ -14363,11 +19084,14 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512 /* Default */; + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name !== undefined) { + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing"); + } + else { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict @@ -14379,6 +19103,11 @@ var ts; // declaration we have for this symbol, and then create a new symbol for this // declaration. // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. @@ -14386,42 +19115,44 @@ var ts; // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. - symbol = ts.hasProperty(symbolTable, name) - ? symbolTable[name] - : (symbolTable[name] = createSymbol(0 /* None */, name)); + symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0 /* None */, name)); if (name && (includes & 788448 /* Classifiable */)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (node.name) { - node.name.parent = node; + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbol = symbolTable[name] = createSymbol(0 /* None */, name); } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512 /* Default */) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + else { + if (node.name) { + node.name.parent = node; } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (ts.hasModifier(declaration, 512 /* Default */)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); + } } } - else { - symbol = createSymbol(0 /* None */, "__missing"); - } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 8388608 /* Alias */) { if (node.kind === 238 /* ExportSpecifier */ || (node.kind === 229 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -14446,10 +19177,10 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192 /* ExportContext */)) { + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); + (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | + (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -14489,7 +19220,7 @@ var ts; if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -14524,11 +19255,11 @@ var ts; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) // Reset all emit helper flags on node (for incremental scenarios) - node.flags &= ~4030464 /* ReachabilityAndEmitFlags */; + node.flags &= ~32128 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { - node.flags |= 32768 /* HasImplicitReturn */; + node.flags |= 128 /* HasImplicitReturn */; if (hasExplicitReturn) - node.flags |= 65536 /* HasExplicitReturn */; + node.flags |= 256 /* HasExplicitReturn */; } if (node.kind === 256 /* SourceFile */) { node.flags |= emitFlags; @@ -14549,7 +19280,7 @@ var ts; else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 16384 /* ContainsThis */ : node.flags & ~16384 /* ContainsThis */; + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; } else { bindChildren(node); @@ -14558,14 +19289,27 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindChildrenWorker(node) { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - bind(jsDocComment); - } + ts.forEach(node.jsDocComments, bind); } if (checkUnreachable(node)) { ts.forEachChild(node, bind); @@ -14614,6 +19358,9 @@ var ts; case 185 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; + case 186 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; case 187 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; @@ -14671,15 +19418,9 @@ var ts; } return false; } - function isNarrowingNullCheckOperands(expr1, expr2) { - return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); - } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } - function isNarrowingDiscriminant(expr) { - return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -14688,9 +19429,8 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || - isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 91 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); case 24 /* CommaToken */: @@ -14712,10 +19452,6 @@ var ts; } return isNarrowableReference(expr); } - function isNarrowingSwitchStatement(switchStatement) { - var expr = switchStatement.expression; - return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -14760,7 +19496,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -15104,6 +19840,15 @@ var ts; } else { ts.forEachChild(node, bind); + if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + ts.forEachChild(node, bind); + if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { @@ -15145,7 +19890,7 @@ var ts; currentFlow = finishFlowLabel(postExpressionLabel); } function bindInitializedVariableFlow(node) { - var name = node.name; + var name = !ts.isOmittedExpression(node) ? node.name : undefined; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var child = _a[_i]; @@ -15304,7 +20049,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 32 /* Static */ + return ts.hasModifier(node, 32 /* Static */) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -15329,16 +20074,16 @@ var ts; // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular // declarations with export modifiers) is an export context in which declarations are implicitly exported. if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 8192 /* ExportContext */; + node.flags |= 32 /* ExportContext */; } else { - node.flags &= ~8192 /* ExportContext */; + node.flags &= ~32 /* ExportContext */; } } function bindModuleDeclaration(node) { setExportContextFlag(node); if (ts.isAmbientModule(node)) { - if (node.flags & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (ts.isExternalModuleAugmentation(node)) { @@ -15398,8 +20143,8 @@ var ts; addDeclarationToSymbol(symbol, node, 131072 /* Signature */); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; + typeLiteralSymbol.members = ts.createMap(); + typeLiteralSymbol.members[symbol.name] = symbol; } function bindObjectLiteralExpression(node) { var ElementKind; @@ -15408,7 +20153,7 @@ var ts; ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; })(ElementKind || (ElementKind = {})); if (inStrictMode) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69 /* Identifier */) { @@ -15432,8 +20177,8 @@ var ts; continue; } if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -15456,7 +20201,7 @@ var ts; // fall through. default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -15509,8 +20254,8 @@ var ts; if (inStrictMode && node.expression.kind === 69 /* Identifier */) { // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its // UnaryExpression is a direct reference to a variable, function argument, or function name - var span = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -15523,8 +20268,8 @@ var ts; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. - var span = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } } } @@ -15638,6 +20383,9 @@ var ts; } parent = saveParent; } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } inStrictMode = saveInStrictMode; } function updateStrictModeStatementList(statements) { @@ -15717,7 +20465,7 @@ var ts; case 154 /* TypePredicate */: return checkTypePredicate(node); case 141 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); case 142 /* Parameter */: return bindParameter(node); case 218 /* VariableDeclaration */: @@ -15733,9 +20481,9 @@ var ts; case 254 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 255 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); case 247 /* JsxSpreadAttribute */: - emitFlags |= 1073741824 /* HasJsxSpreadAttribute */; + emitFlags |= 16384 /* HasJsxSpreadAttributes */; return; case 151 /* CallSignature */: case 152 /* ConstructSignature */: @@ -15781,10 +20529,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); case 279 /* JSDocTypedefTag */: case 223 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); case 224 /* EnumDeclaration */: return bindEnumDeclaration(node); case 225 /* ModuleDeclaration */: @@ -15835,18 +20583,15 @@ var ts; bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 235 /* ExportAssignment */ ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { // Export assignment in some sort of block construct bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } - else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 235 /* ExportAssignment */) { - // An export default clause with an identifier exports all meanings of that identifier - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); - } else { - // An export default clause with an expression exports a value - declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + ? 8388608 /* Alias */ + : 4 /* Property */; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } } function bindNamespaceExportDeclaration(node) { @@ -15868,7 +20613,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || {}; + file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); } function bindExportDeclaration(node) { @@ -15904,20 +20649,25 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 7340032 /* Export */ | 512 /* ValueModule */, 0 /* None */); } function bindThisPropertyAssignment(node) { - // Declare a 'member' in case it turns out the container was an ES5 class or ES6 constructor - var assignee; - if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 220 /* FunctionDeclaration */) { - assignee = container; + ts.Debug.assert(ts.isInJavaScriptFile(node)); + // Declare a 'member' if the container is an ES5 class or ES6 constructor + if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 179 /* FunctionExpression */) { + container.symbol.members = container.symbol.members || ts.createMap(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } else if (container.kind === 148 /* Constructor */) { - assignee = container.parent; + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var saveContainer = container; + container = container.parent; + var symbol = bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* None */); + if (symbol) { + // constructor-declared symbols can be overwritten by subsequent method declarations + symbol.isReplaceableByMethod = true; + } + container = saveContainer; } - else { - return; - } - assignee.symbol.members = assignee.symbol.members || {}; - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(assignee.symbol.members, assignee.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } function bindPrototypePropertyAssignment(node) { // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. @@ -15936,7 +20686,7 @@ var ts; } // Set up the members collection if it doesn't exist already if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } // Declare the method/property declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 0 /* PropertyExcludes */); @@ -15951,10 +20701,10 @@ var ts; function bindClassLikeDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 262144 /* HasClassExtends */; + emitFlags |= 1024 /* HasClassExtends */; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288 /* HasDecorators */; + emitFlags |= 2048 /* HasDecorators */; } } if (node.kind === 221 /* ClassDeclaration */) { @@ -15979,7 +20729,7 @@ var ts; // module might have an exported variable called 'prototype'. We can't allow that as // that would clash with the built-in 'prototype' for the class. var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (symbol.exports[prototypeSymbol.name]) { if (node.name) { node.name.parent = node; } @@ -16022,7 +20772,7 @@ var ts; if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node) && ts.nodeIsDecorated(node)) { - emitFlags |= (524288 /* HasDecorators */ | 1048576 /* HasParamDecorators */); + emitFlags |= (2048 /* HasDecorators */ | 4096 /* HasParamDecorators */); } if (inStrictMode) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a @@ -16045,7 +20795,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152 /* HasAsyncFunctions */; + emitFlags |= 8192 /* HasAsyncFunctions */; } } checkStrictModeFunctionName(node); @@ -16060,7 +20810,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152 /* HasAsyncFunctions */; + emitFlags |= 8192 /* HasAsyncFunctions */; } } if (currentFlow) { @@ -16073,10 +20823,10 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152 /* HasAsyncFunctions */; + emitFlags |= 8192 /* HasAsyncFunctions */; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288 /* HasDecorators */; + emitFlags |= 2048 /* HasDecorators */; } } return ts.hasDynamicName(node) @@ -16098,7 +20848,7 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatement(node) && node.kind !== 201 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 201 /* EmptyStatement */) || // report error on class declarations node.kind === 221 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set @@ -16119,7 +20869,7 @@ var ts; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && (node.kind !== 200 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3072 /* BlockScoped */ || + ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); @@ -16129,11 +20879,632 @@ var ts; return true; } } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 174 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 225 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 178 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 187 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 202 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 142 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 180 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 179 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 220 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 218 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 219 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 200 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 214 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 221 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 192 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 251 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 194 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 148 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 145 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 147 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 229 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 172 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */ + || isSuperOrSuperProperty(expression, expressionKind)) { + // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES6 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537133909 /* ArrayLiteralOrCallOrNewExcludes */; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 95 /* SuperKeyword */: + return true; + case 172 /* PropertyAccessExpression */: + case 173 /* ElementAccessExpression */: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 95 /* SuperKeyword */; + } + return false; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 56 /* EqualsToken */ + && (leftKind === 171 /* ObjectLiteralExpression */ + || leftKind === 170 /* ArrayLiteralExpression */)) { + // Destructuring assignments are ES6 syntax. + transformFlags |= 192 /* AssertES6 */ | 256 /* DestructuringAssignment */; + } + else if (operatorTokenKind === 38 /* AsteriskAsteriskToken */ + || operatorTokenKind === 60 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES7 syntax. + transformFlags |= 48 /* AssertES7 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // If the parameter has a question token, then it is TypeScript syntax. + if (node.questionToken) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the parameter's name is 'this', then it is TypeScript syntax. + if (subtreeFlags & 2048 /* ContainsDecorators */ + || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (modifierFlags & 92 /* ParameterPropertyModifier */) { + transformFlags |= 3 /* AssertTypeScript */ | 131072 /* ContainsParameterPropertyAssignments */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES6 */ | 65536 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~538968917 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 195 /* AsExpression */ + || expressionKind === 177 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 256 /* DestructuringAssignment */) { + transformFlags |= 256 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2 /* Ambient */) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES6 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax. + if ((subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) + || (modifierFlags & 1 /* Export */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537590613 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537590613 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 83 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES6 */; + break; + case 106 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var body = node.body; + if (body === undefined) { + // An overload constructor is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550593365 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var typeParameters = node.typeParameters; + var asteriskToken = node.asteriskToken; + // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // generic, or has a decorator. + if (!body + || typeParameters + || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) + || (subtreeFlags & 2048 /* ContainsDecorators */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // Currently, we only support generators that were originally async function bodies. + if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + transformFlags |= 1536 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // generic, or has a decorator. + if (!body + || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) + || (subtreeFlags & 2048 /* ContainsDecorators */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer) { + transformFlags |= 4096 /* ContainsPropertyInitializer */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var asteriskToken = node.asteriskToken; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. + if (modifierFlags & 1 /* Export */) { + transformFlags |= 3 /* AssertTypeScript */ | 192 /* AssertES6 */; + } + // If a FunctionDeclaration is async, then it is TypeScript syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES6 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + transformFlags |= 1536 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550726485 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var asteriskToken = node.asteriskToken; + // An async function expression is TypeScript syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES6 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + transformFlags |= 1536 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550726485 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var modifierFlags = ts.getModifierFlags(node); + // An async arrow function is TypeScript syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550710101 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionKind === 95 /* SuperKeyword */) { + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var nameKind = node.name.kind; + // A VariableDeclaration with a binding pattern is ES6 syntax. + if (nameKind === 167 /* ObjectBindingPattern */ || nameKind === 168 /* ArrayBindingPattern */) { + transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (modifierFlags & 2 /* Ambient */) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. + if (modifierFlags & 1 /* Export */) { + transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; + } + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES6 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES6 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 256 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES6 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~546335573 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES6 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES6 */ | 1048576 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~538968917 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 536871765 /* NodeExcludes */; + switch (kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 115 /* AbstractKeyword */: + case 122 /* DeclareKeyword */: + case 118 /* AsyncKeyword */: + case 74 /* ConstKeyword */: + case 184 /* AwaitExpression */: + case 224 /* EnumDeclaration */: + case 255 /* EnumMember */: + case 177 /* TypeAssertionExpression */: + case 195 /* AsExpression */: + case 196 /* NonNullExpression */: + case 128 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 241 /* JsxElement */: + case 242 /* JsxSelfClosingElement */: + case 243 /* JsxOpeningElement */: + case 244 /* JsxText */: + case 245 /* JsxClosingElement */: + case 246 /* JsxAttribute */: + case 247 /* JsxSpreadAttribute */: + case 248 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 12 /* AssertJsx */; + break; + case 82 /* ExportKeyword */: + // This node is both ES6 and TypeScript syntax. + transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; + break; + case 77 /* DefaultKeyword */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* TemplateHead */: + case 13 /* TemplateMiddle */: + case 14 /* TemplateTail */: + case 189 /* TemplateExpression */: + case 176 /* TaggedTemplateExpression */: + case 254 /* ShorthandPropertyAssignment */: + case 208 /* ForOfStatement */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES6 */; + break; + case 190 /* YieldExpression */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES6 */ | 4194304 /* ContainsYield */; + break; + case 117 /* AnyKeyword */: + case 130 /* NumberKeyword */: + case 127 /* NeverKeyword */: + case 132 /* StringKeyword */: + case 120 /* BooleanKeyword */: + case 133 /* SymbolKeyword */: + case 103 /* VoidKeyword */: + case 141 /* TypeParameter */: + case 144 /* PropertySignature */: + case 146 /* MethodSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 153 /* IndexSignature */: + case 154 /* TypePredicate */: + case 155 /* TypeReference */: + case 156 /* FunctionType */: + case 157 /* ConstructorType */: + case 158 /* TypeQuery */: + case 159 /* TypeLiteral */: + case 160 /* ArrayType */: + case 161 /* TupleType */: + case 162 /* UnionType */: + case 163 /* IntersectionType */: + case 164 /* ParenthesizedType */: + case 222 /* InterfaceDeclaration */: + case 223 /* TypeAliasDeclaration */: + case 165 /* ThisType */: + case 166 /* LiteralType */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 140 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 191 /* SpreadElementExpression */: + // This node is ES6 syntax, but is handled by a containing node. + transformFlags |= 262144 /* ContainsSpreadElementExpression */; + break; + case 95 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES6 */; + break; + case 97 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 8192 /* ContainsLexicalThis */; + break; + case 167 /* ObjectBindingPattern */: + case 168 /* ArrayBindingPattern */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + break; + case 143 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 2048 /* ContainsDecorators */; + break; + case 171 /* ObjectLiteralExpression */: + excludeFlags = 537430869 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES6 */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + break; + case 170 /* ArrayLiteralExpression */: + case 175 /* NewExpression */: + excludeFlags = 537133909 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */) { + // If the this node contains a SpreadElementExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES6 */; + } + break; + case 204 /* DoStatement */: + case 205 /* WhileStatement */: + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES6 */; + } + break; + case 256 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES6 */; + } + break; + case 211 /* ReturnStatement */: + case 209 /* ContinueStatement */: + case 210 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -16146,7 +21517,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -16172,7 +21542,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = {}; + var emptySymbols = ts.createMap(); var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -16224,36 +21594,47 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, + getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var stringLiteralTypes = ts.createMap(); + var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(4096 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 33554432 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); - var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); - var esSymbolType = createIntrinsicType(16777216 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(16 /* Void */, "void"); - var undefinedType = createIntrinsicType(32 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(64 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 /* Null */ | 2097152 /* ContainsWideningType */, "null"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var neverType = createIntrinsicType(134217728 /* Never */, "never"); + var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); + var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(1024 /* Void */, "void"); + var neverType = createIntrinsicType(8192 /* Never */, "never"); + var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = {}; + emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 134217728 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var globals = {}; + var globals = ts.createMap(); /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -16262,6 +21643,7 @@ var ts; var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; + var tryGetGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; @@ -16297,10 +21679,8 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var tupleTypes = {}; - var unionTypes = {}; - var intersectionTypes = {}; - var stringLiteralTypes = {}; + var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); + var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -16341,26 +21721,45 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; + TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; + TypeFacts[TypeFacts["All"] = 8388607] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; + TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; + TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; + TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1 /* TypeofEQString */, "number": 2 /* TypeofEQNumber */, "boolean": 4 /* TypeofEQBoolean */, @@ -16368,8 +21767,8 @@ var ts; "undefined": 16384 /* EQUndefined */, "object": 16 /* TypeofEQObject */, "function": 32 /* TypeofEQFunction */ - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128 /* TypeofNEString */, "number": 256 /* TypeofNENumber */, "boolean": 512 /* TypeofNEBoolean */, @@ -16377,17 +21776,17 @@ var ts; "undefined": 131072 /* NEUndefined */, "object": 2048 /* TypeofNEObject */, "function": 4096 /* TypeofNEFunction */ - }; - var typeofTypesByName = { + }); + var typeofTypesByName = ts.createMap({ "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }; + }); var jsxElementType; /** Things we lazy load from the JSX namespace */ - var jsxTypes = {}; + var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -16397,10 +21796,11 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = {}; - var assignableRelation = {}; - var comparableRelation = {}; - var identityRelation = {}; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; var TypeSystemPropertyName; @@ -16410,10 +21810,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -16441,13 +21839,13 @@ var ts; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) - result |= 107455 /* EnumMemberExcludes */; + result |= 900095 /* EnumMemberExcludes */; if (flags & 16 /* Function */) result |= 106927 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 899519 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 792960 /* InterfaceExcludes */; + result |= 792968 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) @@ -16461,9 +21859,9 @@ var ts; if (flags & 65536 /* SetAccessor */) result |= 74687 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 530912 /* TypeParameterExcludes */; + result |= 530920 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 793056 /* TypeAliasExcludes */; + result |= 793064 /* TypeAliasExcludes */; if (flags & 8388608 /* Alias */) result |= 8388608 /* AliasExcludes */; return result; @@ -16484,9 +21882,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = cloneSymbolTable(symbol.members); + result.members = ts.cloneMap(symbol.members); if (symbol.exports) - result.exports = cloneSymbolTable(symbol.exports); + result.exports = ts.cloneMap(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -16508,12 +21906,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = {}; + target.members = ts.createMap(); mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = {}; + target.exports = ts.createMap(); mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -16529,28 +21927,17 @@ var ts; }); } } - function cloneSymbolTable(symbolTable) { - var result = {}; - for (var id in symbolTable) { - if (ts.hasProperty(symbolTable, id)) { - result[id] = symbolTable[id]; - } - } - return result; - } function mergeSymbolTable(target, source) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (!ts.hasProperty(target, id)) { - target[id] = source[id]; - } - else { - var symbol = target[id]; - if (!(symbol.flags & 33554432 /* Merged */)) { - target[id] = symbol = cloneSymbol(symbol); - } - mergeSymbol(symbol, source[id]); + var targetSymbol = target[id]; + if (!targetSymbol) { + target[id] = source[id]; + } + else { + if (!(targetSymbol.flags & 33554432 /* Merged */)) { + target[id] = targetSymbol = cloneSymbol(targetSymbol); } + mergeSymbol(targetSymbol, source[id]); } } } @@ -16578,7 +21965,7 @@ var ts; } // obtain item referenced by 'export=' mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1536 /* Namespace */) { + if (mainModule.flags & 1920 /* Namespace */) { // if module symbol has already been merged - it is safe to use it. // otherwise clone it mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); @@ -16591,14 +21978,12 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (ts.hasProperty(target, id)) { - // Error on redeclarations - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; - } + if (target[id]) { + // Error on redeclarations + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; } } function addDeclarationDiagnostic(id, message) { @@ -16613,24 +21998,26 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { return node.kind === 256 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning && ts.hasProperty(symbols, name)) { + if (meaning) { var symbol = symbols[name]; - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608 /* Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + if (symbol) { + ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { return symbol; } + if (symbol.flags & 8388608 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } } } // return undefined if we can't find a symbol. @@ -16707,7 +22094,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 145 /* PropertyDeclaration */ && - (current.parent.flags & 32 /* Static */) === 0 && + (ts.getModifierFlags(current.parent) & 32 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -16739,7 +22126,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793056 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 142 /* Parameter */ || @@ -16793,7 +22180,7 @@ var ts; // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, // which is not the desired behavior. - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 /* Alias */ && ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) { break; @@ -16816,7 +22203,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(location.flags & 32 /* Static */)) { + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -16829,8 +22216,8 @@ var ts; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 222 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { - if (lastLocation && lastLocation.flags & 32 /* Static */) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -16859,7 +22246,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -16924,8 +22311,10 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16957,8 +22346,8 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - // If we're in an external module, we can't reference symbols created from UMD export declarations - if (result && isInExternalModule) { + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -16968,7 +22357,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if (!errorLocation || (errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); @@ -16987,7 +22376,7 @@ var ts; } // No static member is present. // Check if we're in an instance method and look for a relevant instance member. - if (location === container && !(location.flags & 32 /* Static */)) { + if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); @@ -17000,25 +22389,36 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var parentClassExpression = errorLocation; - while (parentClassExpression) { - var kind = parentClassExpression.kind; - if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { - parentClassExpression = parentClassExpression.parent; - continue; - } - if (kind === 194 /* ExpressionWithTypeArguments */) { - break; - } - return false; - } - if (!parentClassExpression) { - return false; - } - var expression = parentClassExpression.expression; - if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); + if (isError) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - return true; + } + return isError; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 69 /* Identifier */: + case 172 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 194 /* ExpressionWithTypeArguments */: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } } return false; } @@ -17027,7 +22427,7 @@ var ts; // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -17069,7 +22469,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -17106,7 +22506,7 @@ var ts; // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' // property with the type/namespace side interface 'Point'. function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793056 /* Type */ | 1536 /* Namespace */)) { + if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -17122,9 +22522,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536 /* Module */) { - var exports = getExportsOfSymbol(symbol); - if (ts.hasProperty(exports, name)) { - return resolveSymbol(exports[name]); + var exportedSymbol = getExportsOfSymbol(symbol)[name]; + if (exportedSymbol) { + return resolveSymbol(exportedSymbol); } } } @@ -17140,27 +22540,31 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { - if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + var name_13 = specifier.propertyName || specifier.name; + if (name_13.text) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); } // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); } return symbol; } @@ -17175,10 +22579,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); + return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -17199,7 +22603,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); @@ -17207,6 +22611,7 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -17239,6 +22644,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); @@ -17266,27 +22672,27 @@ var ts; } // Check for case 1 and 3 in the above example if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { - return resolveEntityName(entityName, 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); } // Resolves a qualified name and any involved aliases - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias) { + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } var symbol; if (name.kind === 69 /* Identifier */) { - var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); + var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } @@ -17294,7 +22700,7 @@ var ts; else if (name.kind === 139 /* QualifiedName */ || name.kind === 172 /* PropertyAccessExpression */) { var left = name.kind === 139 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 139 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); + var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -17304,7 +22710,7 @@ var ts; symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); } return undefined; } @@ -17323,9 +22729,12 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. - var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); + var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } @@ -17337,7 +22746,7 @@ var ts; return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { @@ -17346,7 +22755,7 @@ var ts; } if (moduleNotFoundError) { // report errors only if it was requested - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return undefined; } @@ -17358,7 +22767,14 @@ var ts; } if (moduleNotFoundError) { // report errors only if it was requested - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } return undefined; } @@ -17397,7 +22813,7 @@ var ts; */ function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !ts.hasProperty(target, id)) { + if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -17405,7 +22821,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -17425,12 +22841,12 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = cloneSymbolTable(symbol.exports); + var symbols = ts.cloneMap(symbol.exports); // All export * declarations are collected in an __export symbol by the binder var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = {}; - var lookupTable = {}; + var nestedSymbols = ts.createMap(); + var lookupTable = ts.createMap(); for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -17440,7 +22856,7 @@ var ts; for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -17495,8 +22911,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount; typeCount++; + result.id = typeCount; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -17504,6 +22920,12 @@ var ts; type.intrinsicName = intrinsicName; return type; } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -17522,14 +22944,12 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (ts.hasProperty(members, id)) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); } } } @@ -17547,7 +22967,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(2097152 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -17574,7 +22994,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1536 /* Namespace */; + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -17597,11 +23017,11 @@ var ts; } } // If symbol is directly available by its name in the symbol table - if (isAccessible(ts.lookUp(symbols, symbol.name))) { + if (isAccessible(symbols[symbol.name])) { return [symbol]; } // Check if symbol is any of the alias - return ts.forEachValue(symbols, function (symbolFromSymbolTable) { + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) { @@ -17632,12 +23052,12 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - if (!ts.hasProperty(symbolTable, symbol.name)) { + var symbolFromSymbolTable = symbolTable[symbol.name]; + if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; } // If the symbol with this name is present it should refer to the symbol - var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { // No need to qualify return true; @@ -17671,7 +23091,15 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { var initialSymbol = symbol; var meaningToLook = meaning; @@ -17679,12 +23107,12 @@ var ts; // Symbol is accessible if it by itself is accessible var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536 /* Namespace */) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined }; } return hasAccessibleDeclarations; @@ -17736,7 +23164,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -17748,16 +23176,21 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1 /* Export */) && + !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -17778,16 +23211,16 @@ var ts; entityName.parent.kind === 229 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration - meaning = 1536 /* Namespace */; + meaning = 1920 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 793056 /* Type */; + meaning = 793064 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* NotAccessible */, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -17834,6 +23267,31 @@ var ts; ts.releaseStringWriter(writer); return result; } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144 /* Nullable */)) { + if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } + } + result.push(t); + } + } + if (flags & 4096 /* Null */) + result.push(nullType); + if (flags & 2048 /* Undefined */) + result.push(undefinedType); + return result || types; + } function visibilityToString(flags) { if (flags === 8 /* Private */) { return "private"; @@ -17860,6 +23318,9 @@ var ts; node.parent.kind === 226 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } + function literalTypeToString(type) { + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -17932,7 +23393,7 @@ var ts; } parentSymbol = symbol; } - // const the writer know we just wrote out a symbol. The declaration emitter writer uses + // Let the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // @@ -17940,32 +23401,32 @@ var ts; // up front (for example, during checking) could determine if we need to emit the imports // and we could then access that data during declaration emit. writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning) { - if (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_7) { + walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else { - // If we didn't find accessible symbol chain for this symbol, break if this is external module - if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { - return; - } - // if this is anonymous type break - if (symbol.flags & 2048 /* TypeLiteral */ || symbol.flags & 4096 /* ObjectLiteral */) { - return; - } - appendParentTypeArgumentsAndSymbolName(symbol); + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } + else if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } } // Get qualified name if the symbol is not a type parameter // and there is an enclosing declaration or we specifically @@ -17973,47 +23434,57 @@ var ts; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; var typeFormatFlag = 128 /* UseFullyQualifiedType */ & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning); - return; + walkSymbol(symbol, meaning, /*endOfChain*/ true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); } - return appendParentTypeArgumentsAndSymbolName(symbol); } function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16 /* WriteOwnNameForAnyLike */; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { + var nextFlags = flags & ~512 /* InTypeAlias */; // Write undefined/null type as any - if (type.flags & 150995071 /* Intrinsic */) { + if (type.flags & 16015 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 33554432 /* ThisType */) { + else if (type.flags & 268435456 /* ThisType */) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 4096 /* Reference */) { - writeTypeReference(type, flags); + else if (type.flags & 131072 /* Reference */) { + writeTypeReference(type, nextFlags); } - else if (type.flags & (1024 /* Class */ | 2048 /* Interface */ | 128 /* Enum */ | 512 /* TypeParameter */)) { + else if (type.flags & 256 /* EnumLiteral */) { + buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + writePunctuation(writer, 21 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } + else if (type.flags & (32768 /* Class */ | 65536 /* Interface */ | 16 /* Enum */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (type.flags & 8192 /* Tuple */) { - writeTupleType(type); + else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + // Only write out inferred type with its corresponding type-alias if type-alias is visible + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } - else if (type.flags & 49152 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, flags); + else if (type.flags & 1572864 /* UnionOrIntersection */) { + writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & 65536 /* Anonymous */) { - writeAnonymousType(type, flags); + else if (type.flags & 2097152 /* Anonymous */) { + writeAnonymousType(type, nextFlags); } - else if (type.flags & 256 /* StringLiteral */) { - writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); + else if (type.flags & 96 /* StringOrNumberLiteral */) { + writer.writeStringLiteral(literalTypeToString(type)); } else { // Should never get here @@ -18040,7 +23511,7 @@ var ts; function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); @@ -18062,6 +23533,11 @@ var ts; writePunctuation(writer, 19 /* OpenBracketToken */); writePunctuation(writer, 20 /* CloseBracketToken */); } + else if (type.target.flags & 262144 /* Tuple */) { + writePunctuation(writer, 19 /* OpenBracketToken */); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24 /* CommaToken */); + writePunctuation(writer, 20 /* CloseBracketToken */); + } else { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those @@ -18073,14 +23549,14 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_7 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_7); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_7, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -18089,16 +23565,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } - function writeTupleType(type) { - writePunctuation(writer, 19 /* OpenBracketToken */); - writeTypeList(type.elementTypes, 24 /* CommaToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); - } function writeUnionOrIntersectionType(type, flags) { if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - writeTypeList(type.types, type.flags & 16384 /* Union */ ? 47 /* BarToken */ : 46 /* AmpersandToken */); + if (type.flags & 524288 /* Union */) { + writeTypeList(formatUnionTypes(type.types), 47 /* BarToken */); + } + else { + writeTypeList(type.types, 46 /* AmpersandToken */); + } if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -18118,7 +23594,7 @@ var ts; var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } else { // Recursive usage, use any @@ -18142,7 +23618,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32 /* Static */; })); + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -18331,7 +23807,7 @@ var ts; } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingElement.kind === 193 /* OmittedExpression */) { + if (ts.isOmittedExpression(bindingElement)) { return; } ts.Debug.assert(bindingElement.kind === 169 /* BindingElement */); @@ -18484,21 +23960,21 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_8 = getDeclarationContainer(node); + var parent_9 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_8.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_8))) { - return isGlobalSourceFile(parent_8); + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { + return isGlobalSourceFile(parent_9); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_8); + return isDeclarationVisible(parent_9); case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.flags & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } @@ -18527,8 +24003,9 @@ var ts; return false; // Type parameters are always visible case 141 /* TypeParameter */: - // Source file is always visible + // Source file and namespace export are always visible case 256 /* SourceFile */: + case 228 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module case 235 /* ExportAssignment */: @@ -18541,13 +24018,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -18565,7 +24042,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -18618,7 +24095,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - ts.Debug.assert(!!(target.flags & 1024 /* Class */)); + ts.Debug.assert(!!(target.flags & 32768 /* Class */)); return target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { @@ -18667,7 +24144,7 @@ var ts; return type && (type.flags & 1 /* Any */) !== 0; } function isTypeNever(type) { - return type && (type.flags & 134217728 /* Never */) !== 0; + return type && (type.flags & 8192 /* Never */) !== 0; } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. @@ -18705,15 +24182,15 @@ var ts; // undefined or any type of the parent. if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { - return checkExpressionCached(declaration.initializer); + return checkDeclarationInitializer(declaration); } return parentType; } var type; if (pattern.kind === 167 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + var name_14 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_14)) { // computed properties with non-literal names are treated as 'any' return anyType; } @@ -18722,12 +24199,12 @@ var ts; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_14); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); return unknownType; } } @@ -18744,7 +24221,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -18759,10 +24236,12 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } - return type; + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -18796,11 +24275,11 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? addTypeKind(type, 32 /* Undefined */) : type; + return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 134217728 /* JavaScriptFile */) { + if (declaration.flags & 1048576 /* JavaScriptFile */) { // If this is a variable in a JavaScript file, then use the JSDoc type (if it has // one as its type), otherwise fallback to the below standard TS codepaths to // try to figure it out. @@ -18844,16 +24323,22 @@ var ts; } } // Use contextual parameter type if one is available - var type = declaration.symbol.name === "this" - ? getContextuallyTypedThisType(func) - : getContextuallyTypedParameterType(declaration); + var type = void 0; + if (declaration.symbol.name === "this") { + var thisParameter = getContextualThisParameter(func); + type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + } + else { + type = getContextuallyTypedParameterType(declaration); + } if (type) { return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ declaration.questionToken && includeOptionality); + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } // If it is a short-hand property assignment, use the type of the identifier if (declaration.kind === 254 /* ShorthandPropertyAssignment */) { @@ -18861,7 +24346,7 @@ var ts; } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); } // No type specified and nothing can be inferred return undefined; @@ -18869,23 +24354,21 @@ var ts; // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. - function getTypeFromBindingElement(element, includePatternInType) { + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - var type = checkExpressionCached(element.initializer); - reportErrorsFromWidening(element, type); - return getWidenedType(type); + return checkDeclarationInitializer(element); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType); + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } // Return the type implied by an object binding pattern - function getTypeFromObjectBindingPattern(pattern, includePatternInType) { - var members = {}; + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createMap(); var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -18897,7 +24380,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -18906,24 +24389,25 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */; + result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; } return result; } // Return the type implied by an array binding pattern - function getTypeFromArrayBindingPattern(pattern, includePatternInType) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; - if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); if (includePatternInType) { - var result = createNewTupleType(elementTypes); + result = cloneTypeReference(result); result.pattern = pattern; - return result; } - return createTupleType(elementTypes); + return result; } // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself // and without regard to its context (i.e. without regard any type annotation or initializer associated with the @@ -18932,10 +24416,10 @@ var ts; // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. - function getTypeFromBindingPattern(pattern, includePatternInType) { + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { return pattern.kind === 167 /* ObjectBindingPattern */ - ? getTypeFromObjectBindingPattern(pattern, includePatternInType) - : getTypeFromArrayBindingPattern(pattern, includePatternInType); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it @@ -18991,24 +24475,34 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } + if (declaration.flags & 1048576 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = undefined; - // Handle module.exports = expr or this.p = expr - if (declaration.kind === 187 /* BinaryExpression */) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - else if (declaration.kind === 172 /* PropertyAccessExpression */) { - // Declarations only exist for property access expressions for certain - // special assignment kinds - if (declaration.parent.kind === 187 /* BinaryExpression */) { - // Handle exports.p = expr or className.prototype.method = expr - type = checkExpressionCached(declaration.parent.right); + var type = void 0; + // Handle certain special assignment kinds, which happen to union across multiple declarations: + // * module.exports = expr + // * exports.p = expr + // * this.p = expr + // * className.prototype.method = expr + if (declaration.kind === 187 /* BinaryExpression */ || + declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { + // Use JS Doc type if present on parent expression statement + if (declaration.flags & 1048576 /* JavaScriptFile */) { + var typeTag = ts.getJSDocTypeTag(declaration.parent); + if (typeTag && typeTag.typeExpression) { + return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + } } + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? + checkExpressionCached(decl.right) : + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, /*subtypeReduction*/ true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { @@ -19053,7 +24547,7 @@ var ts; if (!links.type) { var getter = ts.getDeclarationOfKind(symbol, 149 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 150 /* SetAccessor */); - if (getter && getter.flags & 134217728 /* JavaScriptFile */) { + if (getter && getter.flags & 1048576 /* JavaScriptFile */) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -19081,7 +24575,13 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } type = anyType; } @@ -19101,13 +24601,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(65536 /* Anonymous */, symbol); + var type = createObjectType(2097152 /* Anonymous */, symbol); links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - addTypeKind(type, 32 /* Undefined */) : type; + includeFalsyTypes(type, 2048 /* Undefined */) : type; } } return links.type; @@ -19115,7 +24615,7 @@ var ts; function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.type = getDeclaredTypeOfEnumMember(symbol); } return links.type; } @@ -19163,7 +24663,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 4096 /* Reference */ ? type.target : type; + return type.flags & 131072 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -19234,7 +24734,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -19246,7 +24746,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -19266,7 +24766,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896 /* ObjectType */) { + if (baseConstructorType.flags & 2588672 /* ObjectType */) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -19284,25 +24784,28 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { - var isClass = type.symbol.flags & 32 /* Class */; - var isInterface = type.symbol.flags & 64 /* Interface */; if (!type.resolvedBaseTypes) { - if (!isClass && !isInterface) { + if (type.flags & 262144 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { ts.Debug.fail("type must be class or interface"); } - if (isClass) { - resolveBaseTypesOfClass(type); - } - if (isInterface) { - resolveBaseTypesOfInterface(type); - } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 80896 /* ObjectType */)) { + if (!(baseConstructorType.flags & 2588672 /* ObjectType */)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -19329,7 +24832,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */))) { + if (!(getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -19364,7 +24867,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { + if (getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -19392,15 +24895,15 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 222 /* InterfaceDeclaration */) { - if (declaration.flags & 16384 /* ContainsThis */) { + if (declaration.flags & 64 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isSupportedExpressionWithTypeArguments(node)) { - var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -19414,7 +24917,7 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 1024 /* Class */ : 2048 /* Interface */; + var kind = symbol.flags & 32 /* Class */ ? 32768 /* Class */ : 65536 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -19423,16 +24926,16 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 1024 /* Class */ || !isIndependentInterface(symbol)) { - type.flags |= 4096 /* Reference */; + if (outerTypeParameters || localTypeParameters || kind === 32768 /* Class */ || !isIndependentInterface(symbol)) { + type.flags |= 131072 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = {}; + type.instantiations = ts.createMap(); type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -19447,8 +24950,9 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var type = void 0; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); + var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -19459,14 +24963,14 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type); + type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); } if (popTypeResolution()) { - links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (links.typeParameters) { + links.typeParameters = typeParameters; + if (typeParameters) { // Initialize the instantiation cache for generic type aliases. The declared type corresponds to // an instantiation of the type alias with the type parameters supplied as type arguments. - links.instantiations = {}; + links.instantiations = ts.createMap(); links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -19478,19 +24982,84 @@ var ts; } return links.declaredType; } + function isLiteralEnumMember(symbol, member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + return expr.kind === 8 /* NumericLiteral */ || + expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */ || + expr.kind === 69 /* Identifier */ && !!symbol.exports[expr.text]; + } + function enumHasLiteralMembers(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (!isLiteralEnumMember(symbol, member)) { + return false; + } + } + } + } + return true; + } + function createEnumLiteralType(symbol, baseType, text) { + var type = createType(256 /* EnumLiteral */); + type.symbol = symbol; + type.baseType = baseType; + type.text = text; + return type; + } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(128 /* Enum */); - type.symbol = symbol; - links.declaredType = type; + var enumType = links.declaredType = createType(16 /* Enum */); + enumType.symbol = symbol; + if (enumHasLiteralMembers(symbol)) { + var memberTypeList = []; + var memberTypes = ts.createMap(); + for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224 /* EnumDeclaration */) { + computeEnumMemberValues(declaration); + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberSymbol = getSymbolOfNode(member); + var value = getEnumMemberValue(member); + if (!memberTypes[value]) { + var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); + memberTypeList.push(memberType); + } + } + } + } + enumType.memberTypes = memberTypes; + if (memberTypeList.length > 1) { + enumType.flags |= 524288 /* Union */; + enumType.types = memberTypeList; + unionTypes[getTypeListId(memberTypeList)] = enumType; + } + } + } + return links.declaredType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.declaredType = enumType.flags & 524288 /* Union */ ? + enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : + enumType; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(512 /* TypeParameter */); + var type = createType(16384 /* TypeParameter */); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */).constraint) { type.constraint = noConstraintType; @@ -19514,11 +25083,14 @@ var ts; if (symbol.flags & 524288 /* TypeAlias */) { return getDeclaredTypeOfTypeAlias(symbol); } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } if (symbol.flags & 384 /* Enum */) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 262144 /* TypeParameter */) { - return getDeclaredTypeOfTypeParameter(symbol); + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); } if (symbol.flags & 8388608 /* Alias */) { return getDeclaredTypeOfAlias(symbol); @@ -19551,7 +25123,7 @@ var ts; case 135 /* UndefinedKeyword */: case 93 /* NullKeyword */: case 127 /* NeverKeyword */: - case 166 /* StringLiteralType */: + case 166 /* LiteralType */: return true; case 160 /* ArrayType */: return isIndependentType(node.elementType); @@ -19602,7 +25174,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -19612,7 +25184,7 @@ var ts; // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -19622,7 +25194,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!ts.hasProperty(symbols, s.name)) { + if (!symbols[s.name]) { symbols[s.name] = s; } } @@ -19639,19 +25211,27 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 4096 /* Reference */) { + if (type.flags & 131072 /* Reference */) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper = identityMapper; - var members = source.symbol.members; - var callSignatures = source.declaredCallSignatures; - var constructSignatures = source.declaredConstructSignatures; - var stringIndexInfo = source.declaredStringIndexInfo; - var numberIndexInfo = source.declaredNumberIndexInfo; - if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -19661,7 +25241,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (members === source.symbol.members) { + if (source.symbol && members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -19687,7 +25267,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -19697,20 +25277,20 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasStringLiterals = hasStringLiterals; + sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -19725,23 +25305,6 @@ var ts; } return result; } - function createTupleTypeMemberSymbols(memberTypes) { - var members = {}; - for (var i = 0; i < memberTypes.length; i++) { - var symbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); - symbol.type = memberTypes[i]; - members[i] = symbol; - } - return members; - } - function resolveTupleTypeMembers(type) { - var arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); - // Make the tuple type itself the 'this' type by including an extra type argument - var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); - var members = createTupleTypeMemberSymbols(type.elementTypes); - addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); - } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -19796,7 +25359,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature @@ -19822,7 +25385,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union @@ -19887,7 +25450,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 80896 /* ObjectType */) { + if (baseConstructorType.flags & 2588672 /* ObjectType */) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -19905,22 +25468,19 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 4096 /* Reference */) { + if (type.flags & 131072 /* Reference */) { resolveTypeReferenceMembers(type); } - else if (type.flags & (1024 /* Class */ | 2048 /* Interface */)) { + else if (type.flags & (32768 /* Class */ | 65536 /* Interface */)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 65536 /* Anonymous */) { + else if (type.flags & 2097152 /* Anonymous */) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 8192 /* Tuple */) { - resolveTupleTypeMembers(type); - } - else if (type.flags & 16384 /* Union */) { + else if (type.flags & 524288 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 32768 /* Intersection */) { + else if (type.flags & 1048576 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -19928,7 +25488,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; @@ -19936,13 +25496,11 @@ var ts; /** If the given type is an object type and that type has a property by the given name, * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } } } @@ -19955,7 +25513,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { break; } } @@ -19963,7 +25521,7 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 1572864 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } /** * The apparent type of a type parameter is the base constraint instantiated with the type parameter @@ -19972,7 +25530,7 @@ var ts; function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 512 /* TypeParameter */) { + while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -19985,19 +25543,19 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - if (type.flags & 512 /* TypeParameter */) { + if (type.flags & 16384 /* TypeParameter */) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 258 /* StringLike */) { + if (type.flags & 34 /* StringLike */) { type = globalStringType; } - else if (type.flags & 132 /* NumberLike */) { + else if (type.flags & 340 /* NumberLike */) { type = globalNumberType; } - else if (type.flags & 8 /* Boolean */) { + else if (type.flags & 136 /* BooleanLike */) { type = globalBooleanType; } - else if (type.flags & 16777216 /* ESSymbol */) { + else if (type.flags & 512 /* ESSymbol */) { type = getGlobalESSymbolType(); } return type; @@ -20006,14 +25564,14 @@ var ts; var types = containingType.types; var props; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 32768 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; + var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))) { + if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -20025,7 +25583,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384 /* Union */) { + else if (containingType.flags & 524288 /* Union */) { // A union type requires the property to be present in all constituent types return undefined; } @@ -20039,11 +25597,20 @@ var ts; } var propTypes = []; var declarations = []; + var commonType = undefined; + var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + hasCommonType = false; + } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 /* Property */ | @@ -20051,50 +25618,54 @@ var ts; 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; + result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = {}); - if (ts.hasProperty(properties, name)) { - return properties[name]; - } - var property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; + var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); + var property = properties[name]; + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; + } } return property; } - // Return the symbol for the property with the given name in the given type. Creates synthetic union properties when - // necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from - // Object and Function as appropriate. + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol = getPropertyOfObjectType(globalFunctionType, name); - if (symbol) { - return symbol; + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 49152 /* UnionOrIntersection */) { + if (type.flags & 1572864 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 130048 /* StructuredType */) { + if (type.flags & 4161536 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -20108,7 +25679,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 130048 /* StructuredType */) { + if (type.flags & 4161536 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -20137,13 +25708,13 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, /*subtypeReduction*/ true); } } return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 134217728 /* JavaScriptFile */) { + if (declaration.flags & 1048576 /* JavaScriptFile */) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -20173,7 +25744,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 134217728 /* JavaScriptFile */) { + if (node.flags & 1048576 /* JavaScriptFile */) { if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { return true; } @@ -20222,7 +25793,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasStringLiterals = false; + var hasLiteralTypes = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -20245,8 +25816,8 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166 /* StringLiteralType */) { - hasStringLiterals = true; + if (param.type && param.type.kind === 166 /* LiteralType */) { + hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -20274,6 +25845,9 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } + if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { + thisParameter = getContextualThisParameter(declaration); + } var classType = declaration.kind === 148 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -20284,7 +25858,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } @@ -20298,7 +25872,7 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 134217728 /* JavaScriptFile */) { + if (declaration.flags & 1048576 /* JavaScriptFile */) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -20374,7 +25948,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } else { type = getReturnTypeFromBody(signature.declaration); @@ -20398,7 +25972,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { + if (type.flags & 131072 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -20422,7 +25996,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 /* Constructor */ || signature.declaration.kind === 152 /* ConstructSignature */; - var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); + var type = createObjectType(2097152 /* Anonymous */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -20457,7 +26031,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64 /* Readonly */) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); } return undefined; } @@ -20466,7 +26040,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 33554432 /* ThisType */) && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -20498,24 +26072,27 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141 /* TypeParameter */).parent); } function getTypeListId(types) { + var result = ""; if (types) { - switch (types.length) { - case 1: - return "" + types[0].id; - case 2: - return types[0].id + "," + types[1].id; - default: - var result = ""; - for (var i = 0; i < types.length; i++) { - if (i > 0) { - result += ","; - } - result += types[i].id; - } - return result; + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; } } - return ""; + return result; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type @@ -20529,20 +26106,29 @@ var ts; result |= type.flags; } } - return result & 14680064 /* PropagatingFlags */; + return result & 234881024 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - var flags = 4096 /* Reference */ | propagatedFlags; + var flags = 131072 /* Reference */ | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } + function cloneTypeReference(source) { + var type = createObjectType(source.flags, source.symbol); + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return type.target.typeParameters ? type.target.typeParameters.length : 0; + } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); @@ -20555,7 +26141,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -20575,7 +26161,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); var id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } @@ -20602,8 +26188,9 @@ var ts; case 194 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. - if (ts.isSupportedExpressionWithTypeArguments(node)) { - return node.expression; + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; } } return undefined; @@ -20612,7 +26199,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056 /* Type */) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -20641,15 +26228,15 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); - links.resolvedSymbol = symbol; - links.resolvedType = type; } else { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 155 /* TypeReference */ ? node.typeName : - ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : - undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 /* TypeReference */ + ? node.typeName + : ts.isEntityNameExpression(node.expression) + ? node.expression + : undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : @@ -20690,7 +26277,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 80896 /* ObjectType */)) { + if (!(type.flags & 2588672 /* ObjectType */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -20704,7 +26291,7 @@ var ts; return getGlobalSymbol(name, 107455 /* Value */, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793056 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793064 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -20718,8 +26305,8 @@ var ts; * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type */ function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056 /* Type */); + var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } /** @@ -20753,49 +26340,124 @@ var ts; } return links.resolvedType; } - function createTupleType(elementTypes) { - var id = getTypeListId(elementTypes); - return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); - } - function createNewTupleType(elementTypes) { - var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, /*excludeKinds*/ 0); - var type = createObjectType(8192 /* Tuple */ | propagatedFlags); - type.elementTypes = elementTypes; + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384 /* TypeParameter */); + typeParameters.push(typeParameter); + var property = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(262144 /* Tuple */ | 131072 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; return type; } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); } return links.resolvedType; } - function addTypeToSet(typeSet, type, typeSetKind) { - if (type.flags & typeSetKind) { - addTypesToSet(typeSet, type.types, typeSetKind); + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } } - else if (type.flags & (1 /* Any */ | 32 /* Undefined */ | 64 /* Null */)) { - if (type.flags & 1 /* Any */) - typeSet.containsAny = true; - if (type.flags & 32 /* Undefined */) + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 524288 /* Union */) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144 /* Nullable */) { + if (flags & 2048 /* Undefined */) typeSet.containsUndefined = true; - if (type.flags & 64 /* Null */) + if (flags & 4096 /* Null */) typeSet.containsNull = true; - if (!(type.flags & 2097152 /* ContainsWideningType */)) + if (!(flags & 33554432 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(flags & 8192 /* Never */)) { + if (flags & 2 /* String */) + typeSet.containsString = true; + if (flags & 4 /* Number */) + typeSet.containsNumber = true; + if (flags & 96 /* StringOrNumberLiteral */) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } } } // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToSet(typeSet, types, typeSetKind) { + function addTypesToUnion(typeSet, types) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToSet(typeSet, type, typeSetKind); + addTypeToUnion(typeSet, type); } } + function containsIdenticalType(types, type) { + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -20809,18 +26471,31 @@ var ts; while (i > 0) { i--; if (isSubtypeOfAny(types[i], types)) { - types.splice(i, 1); + ts.orderedRemoveItemAt(types, i); } } } - // We reduce the constituent type set to only include types that aren't subtypes of other types, unless - // the noSubtypeReduction flag is specified, in which case we perform a simple deduplication based on - // object identity. Subtype reduction is possible only when union types are known not to circularly - // reference themselves (as is the case with union types created by expression constructs such as array - // literals and the || and ?: operators). Named types can circularly reference themselves and therefore - // cannot be deduplicated during their declaration. For example, "type Item = string | (() => Item" is - // a named type that circularly references itself. - function getUnionType(types, noSubtypeReduction) { + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 /* StringLiteral */ && types.containsString || + t.flags & 64 /* NumberLiteral */ && types.containsNumber || + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 16777216 /* FreshLiteral */ && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -20828,102 +26503,141 @@ var ts; return types[0]; } var typeSet = []; - addTypesToSet(typeSet, types, 16384 /* Union */); + addTypesToUnion(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } - if (!noSubtypeReduction) { + if (subtypeReduction) { removeSubtypes(typeSet); } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - else if (typeSet.length === 1) { - return typeSet[0]; + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; } - var id = getTypeListId(typeSet); + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); - type = unionTypes[id] = createObjectType(16384 /* Union */ | propagatedFlags); - type.types = typeSet; + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); + type = unionTypes[id] = createObjectType(524288 /* Union */ | propagatedFlags); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node) { + function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); } return links.resolvedType; } + function addTypeToIntersection(typeSet, type) { + if (type.flags & 1048576 /* Intersection */) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + addTypeToIntersection(typeSet, type); + } + } // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToSet(typeSet, types, 32768 /* Intersection */); + addTypesToIntersection(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); - type = intersectionTypes[id] = createObjectType(32768 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); + type = intersectionTypes[id] = createObjectType(1048576 /* Intersection */ | propagatedFlags); type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node) { + function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers - links.resolvedType = createObjectType(65536 /* Anonymous */, node.symbol); + var type = createObjectType(2097152 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + links.resolvedType = type; } return links.resolvedType; } - function getStringLiteralTypeForText(text) { - if (ts.hasProperty(stringLiteralTypes, text)) { - return stringLiteralTypes[text]; - } - var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */); + function createLiteralType(flags, text) { + var type = createType(flags); type.text = text; return type; } - function getTypeFromStringLiteralTypeNode(node) { + function getFreshTypeOfLiteralType(type) { + if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 16777216 /* FreshLiteral */)) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags | 16777216 /* FreshLiteral */, type.text); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? type.regularType : type; + } + function getLiteralTypeForText(flags, text) { + var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; + return map[text] || (map[text] = createLiteralType(flags, text)); + } + function getTypeFromLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); } return links.resolvedType; } @@ -20938,7 +26652,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); + var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -20947,8 +26661,8 @@ var ts; var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 222 /* InterfaceDeclaration */)) { - if (!(container.flags & 32 /* Static */) && - (container.kind !== 148 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { + if (!(ts.getModifierFlags(container) & 32 /* Static */) && + (container.kind !== 148 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -20962,7 +26676,10 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNodeNoAlias(type) { + return getTypeFromTypeNode(type, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined); + } + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117 /* AnyKeyword */: case 258 /* JSDocAllType */: @@ -20984,11 +26701,19 @@ var ts; return nullType; case 127 /* NeverKeyword */: return neverType; + case 283 /* JSDocNullKeyword */: + return nullType; + case 284 /* JSDocUndefinedKeyword */: + return undefinedType; + case 285 /* JSDocNeverKeyword */: + return neverType; case 165 /* ThisType */: case 97 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 166 /* StringLiteralType */: - return getTypeFromStringLiteralTypeNode(node); + case 166 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 282 /* JSDocLiteralType */: + return getTypeFromLiteralTypeNode(node.literal); case 155 /* TypeReference */: case 267 /* JSDocTypeReference */: return getTypeFromTypeReference(node); @@ -21005,9 +26730,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162 /* UnionType */: case 261 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node); + return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); case 163 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node); + return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); case 164 /* ParenthesizedType */: case 263 /* JSDocNullableType */: case 264 /* JSDocNonNullableType */: @@ -21015,13 +26740,14 @@ var ts; case 272 /* JSDocThisType */: case 268 /* JSDocOptionalType */: return getTypeFromTypeNode(node.type); + case 265 /* JSDocRecordType */: + return getTypeFromTypeNode(node.literal); case 156 /* FunctionType */: case 157 /* ConstructorType */: case 159 /* TypeLiteral */: case 281 /* JSDocTypeLiteral */: case 269 /* JSDocFunctionType */: - case 265 /* JSDocRecordType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 69 /* Identifier */: @@ -21069,6 +26795,7 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; + mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -21077,7 +26804,7 @@ var ts; function getInferenceMapper(context) { if (!context.mapper) { var mapper = function (t) { - var typeParameters = context.typeParameters; + var typeParameters = context.signature.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (t === typeParameters[i]) { context.inferences[i].isFixed = true; @@ -21086,7 +26813,7 @@ var ts; } return t; }; - mapper.mappedTypes = context.typeParameters; + mapper.mappedTypes = context.signature.typeParameters; mapper.context = context; context.mapper = mapper; } @@ -21101,7 +26828,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(512 /* TypeParameter */); + var result = createType(16384 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -21139,7 +26866,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -21176,9 +26903,11 @@ var ts; mapper.instantiations = []; } // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - var result = createObjectType(65536 /* Anonymous */ | 131072 /* Instantiated */, type.symbol); + var result = createObjectType(2097152 /* Anonymous */ | 4194304 /* Instantiated */, type.symbol); result.target = type; result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -21233,10 +26962,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 512 /* TypeParameter */) { + if (type.flags & 16384 /* TypeParameter */) { return mapper(type); } - if (type.flags & 65536 /* Anonymous */) { + if (type.flags & 2097152 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. We skip instantiation @@ -21245,20 +26974,17 @@ var ts; // instantiation. return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.flags & 131072 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 4194304 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 4096 /* Reference */) { + if (type.flags & 131072 /* Reference */) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 8192 /* Tuple */) { - return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); + if (type.flags & 524288 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); } - if (type.flags & 16384 /* Union */) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), /*noSubtypeReduction*/ true); - } - if (type.flags & 32768 /* Intersection */) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); + if (type.flags & 1048576 /* Intersection */) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); } } return type; @@ -21303,10 +27029,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(65536 /* Anonymous */, type.symbol); + var result = createObjectType(2097152 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -21318,26 +27044,32 @@ var ts; } // TYPE CHECKING function isTypeIdenticalTo(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, identityRelation); } function compareTypesIdentical(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; } function compareTypesAssignable(source, target) { - return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } function isTypeSubtypeOf(source, target) { - return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, subtypeRelation); } function isTypeAssignableTo(source, target) { - return checkTypeAssignableTo(source, target, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, assignableRelation); + } + // A type S is considered to be an instance of a type T if S and T are the same type or if S is a + // subtype of T but not structurally identical to T. This specifically means that two distinct but + // structurally identical types (such as two classes) are not considered instances of each other. + function isTypeInstanceOf(source, target) { + return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); } /** * This is *not* a bi-directional relationship. * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. */ function isTypeComparableTo(source, target) { - return checkTypeComparableTo(source, target, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, comparableRelation); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -21463,8 +27195,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) - || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); } return false; @@ -21493,6 +27225,94 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + var id = source.id + "," + target.id; + if (enumRelation[id] !== undefined) { + return enumRelation[id]; + } + if (source.symbol.name !== target.symbol.name || + !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || + (source.flags & 524288 /* Union */) !== (target.flags & 524288 /* Union */)) { + return enumRelation[id] = false; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + } + return enumRelation[id] = false; + } + } + } + return enumRelation[id] = true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + if (target.flags & 8192 /* Never */) + return false; + if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + return true; + if (source.flags & 34 /* StringLike */ && target.flags & 2 /* String */) + return true; + if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + return true; + if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + return true; + if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + return true; + if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + return true; + if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + return true; + if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1 /* Any */) + return true; + if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + return true; + if (source.flags & 256 /* EnumLiteral */ && + target.flags & 256 /* EnumLiteral */ && + source.text === target.text && + isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + return true; + } + if (source.flags & 256 /* EnumLiteral */ && + target.flags & 16 /* Enum */ && + isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { + return true; + } + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation[id]; + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 4177920 /* StructuredOrTypeParameter */ || target.flags & 4177920 /* StructuredOrTypeParameter */) { + return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + } + return false; + } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -21541,49 +27361,37 @@ var ts; } reportError(message, sourceType, targetType); } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType() === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or // Ternary.False if they are not related. function isRelatedTo(source, target, reportErrors, headMessage) { var result; + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + target = target.regularType; + } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) return -1 /* True */; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (!(target.flags & 134217728 /* Never */)) { - if (target.flags & 1 /* Any */ || source.flags & 134217728 /* Never */) - return -1 /* True */; - if (source.flags & 32 /* Undefined */) { - if (!strictNullChecks || target.flags & (32 /* Undefined */ | 16 /* Void */)) - return -1 /* True */; - } - if (source.flags & 64 /* Null */) { - if (!strictNullChecks || target.flags & 64 /* Null */) - return -1 /* True */; - } - if (source.flags & 128 /* Enum */ && target === numberType) - return -1 /* True */; - if (source.flags & 128 /* Enum */ && target.flags & 128 /* Enum */) { - if (result = enumRelatedTo(source, target, reportErrors)) { - return result; - } - } - if (source.flags & 256 /* StringLiteral */ && target === stringType) - return -1 /* True */; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) - return -1 /* True */; - if (source === numberType && target.flags & 128 /* Enum */) - return -1 /* True */; - } - if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { - return -1 /* True */; - } - } - if (source.flags & 1048576 /* FreshObjectLiteral */) { + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + if (source.flags & 8388608 /* ObjectLiteral */ && source.flags & 16777216 /* FreshLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -21594,24 +27402,24 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 49152 /* UnionOrIntersection */) { + if (target.flags & 1572864 /* UnionOrIntersection */) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; // Note that these checks are specifically ordered to produce correct results. - if (source.flags & 16384 /* Union */) { + if (source.flags & 524288 /* Union */) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors); + result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); } else { - result = eachTypeRelatedToType(source, target, reportErrors); + result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); } if (result) { return result; } } - else if (target.flags & 32768 /* Intersection */) { + else if (target.flags & 1048576 /* Intersection */) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; @@ -21621,7 +27429,7 @@ var ts; // It is necessary to try these "some" checks on both sides because there may be nested "each" checks // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). - if (source.flags & 32768 /* Intersection */) { + if (source.flags & 1048576 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -21639,13 +27447,13 @@ var ts; return result; } } - if (target.flags & 16384 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726 /* Primitive */))) { + if (target.flags & 524288 /* Union */) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { return result; } } } - if (source.flags & 512 /* TypeParameter */) { + if (source.flags & 16384 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1 /* Any */) { constraint = emptyObjectType; @@ -21660,7 +27468,7 @@ var ts; } } else { - if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; @@ -21672,9 +27480,9 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentSource.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { + if (apparentSource.flags & (2588672 /* ObjectType */ | 1048576 /* Intersection */) && target.flags & 2588672 /* ObjectType */) { // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726 /* Primitive */); + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190 /* Primitive */); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -21682,14 +27490,20 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 2588672 /* ObjectType */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } reportRelationError(headMessage, source, target); } return 0 /* False */; } function isIdenticalTo(source, target) { var result; - if (source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */) { - if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { + if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; @@ -21697,8 +27511,8 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || - source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ || + source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { if (result &= eachTypeRelatedToSomeType(target, source, /*reportErrors*/ false)) { return result; @@ -21712,7 +27526,7 @@ var ts; // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type, name) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -21721,7 +27535,7 @@ var ts; return true; } } - else if (type.flags & 49152 /* UnionOrIntersection */) { + else if (type.flags & 1572864 /* UnionOrIntersection */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -21739,7 +27553,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 80896 /* ObjectType */)) { + if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -21772,18 +27586,10 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - var len = targetTypes.length; - // The null and undefined types are guaranteed to be at the end of the constituent type list. In order - // to produce the best possible errors we first check the nullable types, such that the last type we - // check and report errors from is a non-nullable type if one is present. - while (len >= 2 && targetTypes[len - 1].flags & 96 /* Nullable */) { - var related = isRelatedTo(source, targetTypes[len - 1], /*reportErrors*/ false); - if (related) { - return related; - } - len--; + if (target.flags & 524288 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; } - // Now check the non-nullable types and report errors on the last one. + var len = targetTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -21807,18 +27613,10 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - var len = sourceTypes.length; - // The null and undefined types are guaranteed to be at the end of the constituent type list. In order - // to produce the best possible errors we first check the nullable types, such that the last type we - // check and report errors from is a non-nullable type if one is present. - while (len >= 2 && sourceTypes[len - 1].flags & 96 /* Nullable */) { - var related = isRelatedTo(sourceTypes[len - 1], target, /*reportErrors*/ false); - if (related) { - return related; - } - len--; + if (source.flags & 524288 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; } - // Now check the non-nullable types and report errors on the last one. + var len = sourceTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -21898,7 +27696,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; @@ -21931,7 +27729,7 @@ var ts; var maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyMap(maybeCache, destinationCache); + ts.copyProperties(maybeCache, destinationCache); } else { // A false result goes straight into global cache (when something is false under assumptions it @@ -21946,9 +27744,9 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); - for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { - var targetProp = properties_1[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -21960,8 +27758,8 @@ var ts; } } else if (!(targetProp.flags & 134217728 /* Prototype */)) { - var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -22019,7 +27817,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */)) { + if (!(source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -22140,7 +27938,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */))) { + if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 8190 /* Primitive */))) { // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } @@ -22178,33 +27976,12 @@ var ts; } return 0 /* False */; } - function enumRelatedTo(source, target, reportErrors) { - if (source.symbol.name !== target.symbol.name || - source.symbol.flags & 128 /* ConstEnum */ || - target.symbol.flags & 128 /* ConstEnum */) { - return 0 /* False */; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8 /* EnumMember */) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); - } - return 0 /* False */; - } - } - } - return -1 /* True */; - } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = sourceSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); - var targetAccessibility = targetSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; // A public, protected and private signature is assignable to a private signature. if (targetAccessibility === 8 /* Private */) { return true; @@ -22225,11 +28002,11 @@ var ts; } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { - if (type.flags & 65536 /* Anonymous */) { + if (type.flags & 2097152 /* Anonymous */) { var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && declaration.flags & 128 /* Abstract */) { + if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { return true; } } @@ -22243,12 +28020,12 @@ var ts; // some level beyond that. function isDeeplyNestedGeneric(type, stack, depth) { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) - if (type.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && depth >= 5) { + if (type.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && t.symbol === symbol) { + if (t.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -22267,8 +28044,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 /* Private */ | 16 /* Protected */); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 /* Private */ | 16 /* Protected */); + var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -22298,8 +28075,10 @@ var ts; // A source signature partially matches a target signature if the target signature has no fewer required // parameters and no more overall parameters than the source signature (where a signature with a rest // parameter is always considered to have more overall parameters than one without). - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || - source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -22360,31 +28139,43 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } - function getCombinedFlagsOfTypes(types) { - var flags = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - flags |= t.flags; + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } } - return flags; + return true; + } + // When the candidate types are all literal types with the same base type, the common + // supertype is a union of those literal types. Otherwise, the common supertype is the + // first type that is a supertype of each of the other types. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } function getCommonSupertype(types) { if (!strictNullChecks) { - return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); if (!primaryTypes.length) { - return getUnionType(types); + return getUnionType(types, /*subtypeReduction*/ true); } - var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96 /* Nullable */); + var supertype = getSupertypeOrUnion(primaryTypes); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -22420,50 +28211,89 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 4096 /* Reference */ && type.target === globalArrayType; + return type.flags & 131072 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return type.flags & 4096 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 96 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 131072 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralUnionType(type) { - return type.flags & 256 /* StringLiteral */ ? true : - type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : - false; + function isUnitType(type) { + return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 /* Boolean */ ? true : + type.flags & 524288 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* EnumLiteral */ ? type.baseType : + type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 32 /* StringLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* EnumLiteral */ ? type.baseType : + type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type; } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(type.flags & 8192 /* Tuple */); + return !!(type.flags & 131072 /* Reference */ && type.target.flags & 262144 /* Tuple */); } - function getCombinedTypeFlags(type) { - return type.flags & 16384 /* Union */ ? getCombinedFlagsOfTypes(type.types) : type.flags; + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; } - function addTypeKind(type, kind) { - if ((getCombinedTypeFlags(type) & kind) === kind) { + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). + function getFalsyFlags(type) { + return type.flags & 524288 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : + type.flags & 7406 /* PossiblyFalsy */; + } + function includeFalsyTypes(type, flags) { + if ((getFalsyFlags(type) & flags) === flags) { return type; } var types = [type]; - if (kind & 2 /* String */) - types.push(stringType); - if (kind & 4 /* Number */) - types.push(numberType); - if (kind & 8 /* Boolean */) - types.push(booleanType); - if (kind & 16 /* Void */) + if (flags & 34 /* StringLike */) + types.push(emptyStringType); + if (flags & 340 /* NumberLike */) + types.push(zeroType); + if (flags & 136 /* BooleanLike */) + types.push(falseType); + if (flags & 1024 /* Void */) types.push(voidType); - if (kind & 32 /* Undefined */) + if (flags & 2048 /* Undefined */) types.push(undefinedType); - if (kind & 64 /* Null */) + if (flags & 4096 /* Null */) types.push(nullType); - return getUnionType(types); + return getUnionType(types, /*subtypeReduction*/ true); + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : + type; } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; @@ -22489,7 +28319,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = {}; + var members = ts.createMap(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -22505,7 +28335,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576 /* FreshObjectLiteral */)) { + if (!(type.flags & 8388608 /* ObjectLiteral */ && type.flags & 16777216 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -22515,7 +28345,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576 /* FreshObjectLiteral */; + regularNew.flags = resolved.flags & ~16777216 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -22529,24 +28359,21 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 96 /* Nullable */ ? type : getWidenedType(type); + return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { - if (type.flags & 96 /* Nullable */) { + if (type.flags & 100663296 /* RequiresWidening */) { + if (type.flags & 6144 /* Nullable */) { return anyType; } - if (type.flags & 524288 /* ObjectLiteral */) { + if (type.flags & 8388608 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.map(type.types, getWidenedConstituentType), /*noSubtypeReduction*/ true); + if (type.flags & 524288 /* Union */) { + return getUnionType(ts.map(type.types, getWidenedConstituentType)); } - if (isArrayType(type)) { - return createArrayType(getWidenedType(type.typeArguments[0])); - } - if (isTupleType(type)) { - return createTupleType(ts.map(type.elementTypes, getWidenedType)); + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); } } return type; @@ -22564,7 +28391,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -22572,22 +28399,19 @@ var ts; } } } - if (isArrayType(type)) { - return reportWideningErrorsInType(type.typeArguments[0]); - } - if (isTupleType(type)) { - for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 524288 /* ObjectLiteral */) { + if (type.flags & 8388608 /* ObjectLiteral */) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 2097152 /* ContainsWideningType */) { + if (t.flags & 33554432 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -22632,7 +28456,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -22659,29 +28483,49 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = ts.map(typeParameters, createTypeInferencesObject); + function createInferenceContext(signature, inferUnionTypes) { + var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); return { - typeParameters: typeParameters, + signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length) }; } function createTypeInferencesObject() { return { primary: undefined, secondary: undefined, + topLevel: true, isFixed: false }; } - function inferTypes(context, source, target) { + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeParameters(type) { + return !!(type.flags & 16384 /* TypeParameter */ || + type.flags & 131072 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeParameters) || + type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + type.flags & 1572864 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeParameters(type)); + } + function couldUnionOrIntersectionContainTypeParameters(type) { + if (type.couldContainTypeParameters === undefined) { + type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + } + return type.couldContainTypeParameters; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 1572864 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypes(context, originalSource, originalTarget) { + var typeParameters = context.signature.typeParameters; var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; - inferFromTypes(source, target); + var visited = ts.createMap(); + inferFromTypes(originalSource, originalTarget); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { if (source === sourceStack[i] && target === targetStack[i]) { @@ -22691,20 +28535,39 @@ var ts; return false; } function inferFromTypes(source, target) { - if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || - source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { - // Source and target are both unions or both intersections. First, find each - // target constituent type that has an identically matching source constituent - // type, and for each such target constituent type infer from the type to itself. - // When inferring from a type to itself we effectively find all type parameter - // occurrences within that type and infer themselves as their type arguments. + if (!couldContainTypeParameters(target)) { + return; + } + if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. var matchingTypes = void 0; - for (var _i = 0, _a = target.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (typeIdenticalToSomeType(t, source.types)) { + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } + else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } } // Next, to improve the quality of inferences, reduce the source and target types by // removing the identically matched constituents. For example, when inferring from @@ -22714,17 +28577,16 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 512 /* TypeParameter */) { + if (target.flags & 16384 /* TypeParameter */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round // of inference. - if (source.flags & 8388608 /* ContainsAnyFunctionType */) { + if (source.flags & 134217728 /* ContainsAnyFunctionType */) { return; } - var typeParameters = context.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { var inferences = context.inferences[i]; @@ -22741,12 +28603,15 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } + if (!isTypeParameterAtTopLevel(originalTarget, target)) { + inferences.topLevel = false; + } } return; } } } - else if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + else if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; @@ -22755,22 +28620,14 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (source.flags & 8192 /* Tuple */ && target.flags & 8192 /* Tuple */ && source.elementTypes.length === target.elementTypes.length) { - // If source and target are tuples of the same size, infer from element types - var sourceTypes = source.elementTypes; - var targetTypes = target.elementTypes; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 49152 /* UnionOrIntersection */) { + else if (target.flags & 1572864 /* UnionOrIntersection */) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; // First infer to each type in union or intersection that isn't a type parameter - for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { - var t = targetTypes_2[_b]; - if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { + for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { + var t = targetTypes_2[_d]; + if (t.flags & 16384 /* TypeParameter */ && ts.contains(typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -22787,21 +28644,17 @@ var ts; inferiority--; } } - else if (source.flags & 49152 /* UnionOrIntersection */) { + else if (source.flags & 1572864 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { - var sourceType = sourceTypes_3[_c]; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 /* ObjectType */ && (target.flags & 4096 /* Reference */ && target.typeArguments || - target.flags & 8192 /* Tuple */ || - target.flags & 65536 /* Anonymous */ && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { - // If source is an object type, and target is a type reference with type arguments, a tuple type, - // the type of a method, or a type literal, infer from members + if (source.flags & 2588672 /* ObjectType */) { if (isInProcess(source, target)) { return; } @@ -22809,7 +28662,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -22830,8 +28683,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -22848,8 +28701,11 @@ var ts; inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } + function inferFromParameterTypes(source, target) { + return inferFromTypes(source, target); + } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromParameterTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -22878,8 +28734,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -22898,20 +28754,33 @@ var ts; reducedTypes.push(t); } } - return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + return type.flags & 524288 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */); + } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; var inferenceSucceeded; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { + // We widen inferred literal types if + // all inferences were made to top-level ocurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var signature = context.signature; + var widenLiteralTypes = context.inferences[index].topLevel && + !hasPrimitiveConstraint(signature.typeParameters[index]) && + (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); + var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; // Infer widened union or supertype, or the unknown type for no common supertype - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -22926,7 +28795,7 @@ var ts; context.inferredTypes[index] = inferredType; // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -22993,10 +28862,6 @@ var ts; } return undefined; } - function isNullOrUndefinedLiteral(node) { - return node.kind === 93 /* NullKeyword */ || - node.kind === 69 /* Identifier */ && getResolvedSymbol(node) === undefinedSymbol; - } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69 /* Identifier */: @@ -23008,16 +28873,17 @@ var ts; return undefined; } function isMatchingReference(source, target) { - if (source.kind === target.kind) { - switch (source.kind) { - case 69 /* Identifier */: - return getResolvedSymbol(source) === getResolvedSymbol(target); - case 97 /* ThisKeyword */: - return true; - case 172 /* PropertyAccessExpression */: - return source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } + switch (source.kind) { + case 69 /* Identifier */: + return target.kind === 69 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 218 /* VariableDeclaration */ || target.kind === 169 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 97 /* ThisKeyword */: + return target.kind === 97 /* ThisKeyword */; + case 172 /* PropertyAccessExpression */: + return target.kind === 172 /* PropertyAccessExpression */ && + source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); } return false; } @@ -23030,6 +28896,48 @@ var ts; } return false; } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 172 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 69 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 172 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.text); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 524288 /* Union */) { + var prop = getPropertyOfType(type, name); + if (!prop) { + // The type may be a union that includes nullable or primitive types. If filtering + // those out produces a different type, get the property from that type instead. + // Effectively, we're checking if this *could* be a discriminant property once nullable + // and primitive types are removed by other type guards. + var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); + if (filteredType !== type && filteredType.flags & 524288 /* Union */) { + prop = getPropertyOfType(filteredType, name); + } + } + if (prop && prop.flags & 268435456 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !prop.hasCommonType && + isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -23056,7 +28964,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 16384 /* Union */)) { + if (!(source.flags & 524288 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -23071,70 +28979,84 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType && declaredType.flags & 16384 /* Union */) { - var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedTypes.length) { - return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); + if (declaredType !== assignedType) { + if (assignedType.flags & 8192 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192 /* Never */)) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); + } function getTypeFacts(type) { var flags = type.flags; - if (flags & 258 /* StringLike */) { + if (flags & 2 /* String */) { return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } - if (flags & 132 /* NumberLike */) { + if (flags & 32 /* StringLiteral */) { + return strictNullChecks ? + type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + } + if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } + if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { + var isZero = type.text === "0"; + return strictNullChecks ? + isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : + isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + } if (flags & 8 /* Boolean */) { return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; } - if (flags & 80896 /* ObjectType */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 136 /* BooleanLike */) { + return strictNullChecks ? + type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & (16 /* Void */ | 32 /* Undefined */)) { + if (flags & 2588672 /* ObjectType */) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : + strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + } + if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 64 /* Null */) { + if (flags & 4096 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 16777216 /* ESSymbol */) { + if (flags & 512 /* ESSymbol */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 512 /* TypeParameter */) { + if (flags & 16384 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(type); - return constraint ? getTypeFacts(constraint) : 4194303 /* All */; + return getTypeFacts(constraint || emptyObjectType); } - if (flags & 32768 /* Intersection */) { - return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0 /* None */); + if (flags & 1572864 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); } - return 4194303 /* All */; + return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (!(type.flags & 16384 /* Union */)) { - return getTypeFacts(type) & include ? type : neverType; - } - var firstType; - var types; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (getTypeFacts(t) & include) { - if (!firstType) { - firstType = t; - } - else { - if (!types) { - types = [firstType]; - } - types.push(t); - } - } - } - return firstType ? types ? getUnionType(types, /*noSubtypeReduction*/ true) : firstType : neverType; + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -23231,26 +29153,31 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getReferenceFromExpression(node) { + function getInitialOrAssignedType(node) { + return node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node); + } + function getReferenceCandidate(node) { switch (node.kind) { case 178 /* ParenthesizedExpression */: - return getReferenceFromExpression(node.expression); + return getReferenceCandidate(node.expression); case 187 /* BinaryExpression */: switch (node.operatorToken.kind) { case 56 /* EqualsToken */: - return getReferenceFromExpression(node.left); + return getReferenceCandidate(node.left); case 24 /* CommaToken */: - return getReferenceFromExpression(node.right); + return getReferenceCandidate(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249 /* CaseClause */) { - var expr = clause.expression; - return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; } - return undefined; + return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); @@ -23258,28 +29185,58 @@ var ts; // If all case clauses specify expressions that have unit types, we return an array // of those unit types. Otherwise we return an empty array. var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; + links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 524288 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 524288 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 524288 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + return true; + } + return containsType(target.types, source); } function filterType(type, f) { - return type.flags & 16384 /* Union */ ? - getUnionType(ts.filter(type.types, f)) : - f(type) ? type : neverType; + if (type.flags & 524288 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32 /* Undefined */); + var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; - var result = getTypeAtFlowNode(reference.flowNode); + var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */) === neverType) { + if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { return declaredType; } return result; @@ -23321,7 +29278,7 @@ var ts; else if (flow.flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && includeOuterFunctions) { + if (container && container !== flowContainer && reference.kind !== 172 /* PropertyAccessExpression */) { flow = container.flowNode; continue; } @@ -23346,19 +29303,10 @@ var ts; var node = flow.node; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. - if ((node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) && - reference.kind === 69 /* Identifier */ && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { - return declaredType.flags & 16384 /* Union */ ? - getAssignmentReducedType(declaredType, getInitialType(node)) : - declaredType; - } - // If the node is not a variable declaration or binding element, it is an identifier - // or a dotted name that is the target of an assignment. If we have a match, reduce - // the declared type by the assigned type. if (isMatchingReference(reference, node)) { - return declaredType.flags & 16384 /* Union */ ? - getAssignmentReducedType(declaredType, getAssignedType(node)) : + var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; + return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this @@ -23372,32 +29320,44 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - if (type !== neverType) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (!(type.flags & 8192 /* Never */)) { // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the nothing type, then - // we take the type guard as an indication that control could reach here in a - // manner not understood by the control flow analyzer (e.g. a function argument - // has an invalid type, or a nested function has possibly made an assignment to a - // captured variable). We proceed by reverting to the declared type and then - // narrow that. + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { - type = narrowType(declaredType, flow.expression, assumeTrue); + if (type.flags & 8192 /* Never */ && isIncomplete(flowType)) { + type = silentNeverType; } } - return type; + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtSwitchClause(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the // reference is known to always be assigned (i.e. when declared and initial types // are the same), there is no reason to process more antecedents since the only @@ -23408,14 +29368,23 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } } - return getUnionType(antecedentTypes); + return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at // this flow loop junction, return the cached type. var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); if (!key) { key = getFlowCacheKey(reference); } @@ -23423,25 +29392,31 @@ var ts; return cache[key]; } // If this flow loop junction and reference are already being processed, return - // the union of the types computed for each branch so far. We should never see - // an empty array here because the first antecedent of a loop junction is always - // the non-looping control flow path that leads to the top. + // the union of the types computed for each branch so far, marked as incomplete. + // We should never see an empty array here because the first antecedent of a loop + // junction is always the non-looping control flow path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return getUnionType(flowLoopTypes[i]); + return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze // each antecedent code path. var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. @@ -23451,6 +29426,12 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } // If the type at a particular antecedent path is the declared type there is no // reason to process more antecedents since the only possible outcome is subtypes // that will be removed in the final union type anyway. @@ -23458,10 +29439,37 @@ var ts; break; } } - return cache[key] = getUnionType(antecedentTypes); + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + return cache[key] = result; + } + function isMatchingReferenceDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && + declaredType.flags & 524288 /* Union */ && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(declaredType, expr.name.text); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */) : type; + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -23471,26 +29479,29 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - var left = expr.left; - var operator = expr.operatorToken.kind; - var right = expr.right; - if (isNullOrUndefinedLiteral(right)) { - return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 182 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (isNullOrUndefinedLiteral(left)) { - return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + if (right_1.kind === 182 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } - if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } - if (left.kind === 172 /* PropertyAccessExpression */) { - return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + if (isMatchingReferenceDiscriminant(left_1)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (right.kind === 172 /* PropertyAccessExpression */) { - return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); + if (isMatchingReferenceDiscriminant(right_1)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; } break; case 91 /* InstanceOfKeyword */: @@ -23500,25 +29511,42 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { + var valueType = checkExpression(value); + if (valueType.flags & 6144 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : + value.kind === 93 /* NullKeyword */ ? + assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : + assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 2589191 /* NotUnionOrUnit */) { return type; } - var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; - var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - literal.kind === 93 /* NullKeyword */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; - return getTypeWithFacts(type, facts); + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands - var target = getReferenceFromExpression(typeOfExpr.expression); + var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. @@ -23530,72 +29558,38 @@ var ts; if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 16384 /* Union */)) { + if (assumeTrue && !(type.flags & 524288 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primtive type. For example, type 'any' can be narrowed + // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = ts.getProperty(typeofTypesByName, literal.text); + var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : - ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; + typeofEQFacts[literal.text] || 64 /* TypeofEQHostObject */ : + typeofNEFacts[literal.text] || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } - function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with property access as target - if (!isMatchingReference(reference, propAccess.expression)) { - return type; - } - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } - var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); - if (!isStringLiteralUnionType(discriminantType)) { - return type; - } - if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } - if (assumeTrue) { - return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); - } - if (discriminantType.flags & 256 /* StringLiteral */) { - return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); - } - return type; - } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - // We have switch statement with property access expression - if (!isMatchingReference(reference, switchStatement.expression.expression)) { - return type; - } - var propName = switchStatement.expression.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } + // We only narrow if all case expressions specify values with unit types var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); - var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; - var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; - var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); - return caseType ? getUnionType([caseType, defaultType]) : defaultType; + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left); + var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. @@ -23604,10 +29598,6 @@ var ts; } return type; } - // We never narrow type any in an instanceof guard - if (isTypeAny(type)) { - return type; - } // Check that right operand is a function type with a prototype property var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { @@ -23622,13 +29612,17 @@ var ts; targetType = prototypePropertyType; } } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (rightType.flags & 2048 /* Interface */) { + if (rightType.flags & 65536 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 65536 /* Anonymous */) { + else if (rightType.flags & 2097152 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -23642,28 +29636,29 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return type.flags & 16384 /* Union */ ? - getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : - type; + return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); } - // If the current type is a union type, remove all constituents that aren't assignable to + // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 16384 /* Union */) { - var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); - if (assignableConstituents.length) { - return getUnionType(assignableConstituents); + if (type.flags & 524288 /* Union */) { + var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (!(assignableType.flags & 8192 /* Never */)) { + return assignableType; } } - // If the candidate type is assignable to the target type, narrow to the candidate type. - // Otherwise, if the current type is assignable to the candidate, keep the current type. - // Otherwise, the types are completely unrelated, so narrow to the empty type. - var targetType = type.flags & 512 /* TypeParameter */ ? getApparentType(type) : type; - return isTypeAssignableTo(candidate, targetType) ? candidate : + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + var targetType = type.flags & 16384 /* TypeParameter */ ? getApparentType(type) : type; + return isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : - getIntersectionType([type, candidate]); + isTypeAssignableTo(candidate, targetType) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (type.flags & 1 /* Any */ || !hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -23671,6 +29666,10 @@ var ts; if (!predicate) { return type; } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -23739,7 +29738,7 @@ var ts; // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the - // hypotherical reference (control flow information is created and attached by the + // hypothetical reference (control flow information is created and attached by the // binder), we simply return the declared type of the symbol. return getTypeOfSymbol(symbol); } @@ -23752,20 +29751,49 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) || node.kind === 226 /* ModuleBlock */ || node.kind === 256 /* SourceFile */ || node.kind === 145 /* PropertyDeclaration */) { + if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 226 /* ModuleBlock */ || + node.kind === 256 /* SourceFile */ || + node.kind === 145 /* PropertyDeclaration */) { return node; } } } - function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { - var declarationContainer = getControlFlowContainer(declaration); - var container = getControlFlowContainer(reference); - while (container !== declarationContainer && - (container.kind === 179 /* FunctionExpression */ || container.kind === 180 /* ArrowFunction */) && - (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { - container = getControlFlowContainer(container); + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304 /* AssignmentsMarked */)) { + links.flags |= 4194304 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + while (true) { + node = node.parent; + if (!node) { + return false; + } + if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */) { + return true; + } + } + } + function markParameterAssignments(node) { + if (node.kind === 69 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); } - return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); @@ -23777,12 +29805,15 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 180 /* ArrowFunction */) { - if (languageVersion < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { + if (container.kind === 180 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } } - if (node.flags & 33554432 /* AwaitContext */) { + if (node.flags & 262144 /* AwaitContext */) { getNodeLinks(container).flags |= 8192 /* CaptureArguments */; } } @@ -23790,37 +29821,76 @@ var ts; markAliasSymbolAsReferenced(symbol); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - if (languageVersion === 2 /* ES6 */ - && localOrExportSymbol.flags & 32 /* Class */ - && localOrExportSymbol.valueDeclaration.kind === 221 /* ClassDeclaration */ - && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { - getNodeLinks(container).flags |= 524288 /* ClassWithBodyScopedClassBinding */; - getNodeLinks(node).flags |= 1048576 /* BodyScopedClassBinding */; - break; + if (localOrExportSymbol.flags & 32 /* Class */) { + var declaration_1 = localOrExportSymbol.valueDeclaration; + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (languageVersion === 2 /* ES6 */ + && declaration_1.kind === 221 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration_1)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration_1 && container.name !== node) { + getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration_1.kind === 192 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container !== undefined) { + if (container.parent === declaration_1) { + if (container.kind === 145 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); } - container = ts.getContainingClass(container); } } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node)) { + var declaration = localOrExportSymbol.valueDeclaration; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node) || !declaration) { return type; } - var declaration = localOrExportSymbol.valueDeclaration; - var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || !declaration || - ts.getRootDeclaration(declaration).kind === 142 /* Parameter */ || ts.isInAmbientContext(declaration) || - !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); - if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32 /* Undefined */) && getCombinedTypeFlags(flowType) & 32 /* Undefined */) { + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 142 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && + (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && + (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || + isOuterVariable || ts.isInAmbientContext(declaration); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. + if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -23999,7 +30069,7 @@ var ts; break; case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: - if (container.flags & 32 /* Static */) { + if (ts.getModifierFlags(container) & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -24028,10 +30098,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -24039,8 +30105,8 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - var type = container.flags & 32 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*includeOuterFunctions*/ true); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -24108,7 +30174,7 @@ var ts; } return unknownType; } - if ((container.flags & 32 /* Static */) || isCallExpression) { + if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } else { @@ -24171,8 +30237,8 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 147 /* MethodDeclaration */ && container.flags & 256 /* Async */) { - if (ts.isSuperPropertyOrElementAccess(node.parent) && ts.isAssignmentTarget(node.parent)) { + if (container.kind === 147 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } else { @@ -24229,7 +30295,7 @@ var ts; // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression if (ts.isClassLike(container.parent) || container.parent.kind === 171 /* ObjectLiteralExpression */) { - if (container.flags & 32 /* Static */) { + if (ts.getModifierFlags(container) & 32 /* Static */) { return container.kind === 147 /* MethodDeclaration */ || container.kind === 146 /* MethodSignature */ || container.kind === 149 /* GetAccessor */ || @@ -24249,11 +30315,11 @@ var ts; return false; } } - function getContextuallyTypedThisType(func) { + function getContextualThisParameter(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180 /* ArrowFunction */) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return getThisTypeOfSignature(contextualSignature); + return contextualSignature.thisParameter; } } return undefined; @@ -24269,14 +30335,14 @@ var ts; if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getTypeOfExpression(iife.arguments[i])); + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } return createArrayType(getUnionType(restTypes)); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; links.resolvedSignature = anySignature; - var type = checkExpression(iife.arguments[indexOfParameter]); + var type = getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])); links.resolvedSignature = cached; return type; } @@ -24320,15 +30386,15 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_12 = declaration.propertyName || declaration.name; + var name_15 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_12)) { - var text = getTextOfPropertyName(name_12); + !ts.isBindingPattern(name_15)) { + var text = getTextOfPropertyName(name_15); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -24408,6 +30474,10 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + // Don't do this for special property assignments to avoid circularity + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { + return undefined; + } // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); @@ -24433,14 +30503,14 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union of the resulting // types is returned. function applyToContextualType(type, mapper) { - if (!(type.flags & 16384 /* Union */)) { + if (!(type.flags & 524288 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -24458,7 +30528,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 130048 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 4161536 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -24467,7 +30537,7 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 524288 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one @@ -24587,6 +30657,7 @@ var ts; case 187 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); case 253 /* PropertyAssignment */: + case 254 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); case 170 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); @@ -24641,13 +30712,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 16384 /* Union */)) { + if (!(type.flags & 524288 /* Union */)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -24734,7 +30805,7 @@ var ts; } } else { - var type = checkExpression(e, contextualMapper); + var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 191 /* SpreadElementExpression */; @@ -24743,7 +30814,7 @@ var ts; // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -24757,7 +30828,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.elementTypes[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { if (patternElement.kind !== 193 /* OmittedExpression */) { @@ -24772,7 +30843,9 @@ var ts; } } } - return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, /*subtypeReduction*/ true) : + strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); @@ -24780,11 +30853,14 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } function isNumericLiteralName(name) { // The intent of numeric names is that // - they are names with text in a numeric form, and that @@ -24815,7 +30891,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 34 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -24831,14 +30907,14 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = {}; + var propertiesTable = ts.createMap(); var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -24862,7 +30938,7 @@ var ts; } else { ts.Debug.assert(memberDecl.kind === 254 /* ShorthandPropertyAssignment */); - type = checkExpression(memberDecl.name, contextualMapper); + type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); @@ -24878,7 +30954,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -24925,7 +31001,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!ts.hasProperty(propertiesTable, prop.name)) { + if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -24937,8 +31013,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */; - result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -25005,10 +31081,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - // Maybe there's a string indexer? - var indexerType = getIndexTypeOfType(elementAttributesType, 0 /* String */); - if (indexerType) { - correspondingPropType = indexerType; + var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); + if (attributeType) { + correspondingPropType = attributeType; } else { // If there's no corresponding property with this name, error @@ -25099,7 +31174,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 16384 /* Union */)); + ts.Debug.assert(!(valueType.flags & 524288 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -25115,7 +31190,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature)); + return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -25124,9 +31199,9 @@ var ts; /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // JSX.ElementAttributesProperty [symbol] - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064 /* Type */); // JSX.ElementAttributesProperty [type] var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); // The properties of JSX.ElementAttributesProperty @@ -25157,17 +31232,17 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 16384 /* Union */) { + if (elemType.flags & 524288 /* Union */) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - })); + }), /*subtypeReduction*/ true); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type if (elemType.flags & 2 /* String */) { return anyType; } - else if (elemType.flags & 256 /* StringLiteral */) { + else if (elemType.flags & 32 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { @@ -25231,7 +31306,7 @@ var ts; // Props is of type 'any' or unknown return attributesType; } - else if (attributesType.flags & 16384 /* Union */) { + else if (attributesType.flags & 524288 /* Union */) { // Props cannot be a union type error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; @@ -25329,7 +31404,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = {}; + var nameTable = ts.createMap(); // Process this array in right-to-left order so we know which // attributes (mostly from spreads) are being overwritten and // thus should have their types ignored @@ -25352,7 +31427,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912 /* Optional */) && - nameTable[targetProperties[i].name] === undefined) { + !nameTable[targetProperties[i].name]) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -25371,8 +31446,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 145 /* PropertyDeclaration */; } - function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; + function getDeclarationModifierFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } /** * Check whether the requested property access is valid. @@ -25383,7 +31461,7 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkClassPropertyAccess(node, left, type, prop) { - var flags = getDeclarationFlagsFromSymbol(prop); + var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 172 /* PropertyAccessExpression */ || node.kind === 218 /* VariableDeclaration */ ? node.name : @@ -25412,7 +31490,7 @@ var ts; } } // Public properties are otherwise accessible. - if (!(flags & (8 /* Private */ | 16 /* Protected */))) { + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { return true; } // Property is known to be private or protected at this point @@ -25445,12 +31523,12 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 33554432 /* ThisType */) { + if (type.flags & 268435456 /* ThisType */) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } // TODO: why is the first part of this check here? - if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (32768 /* Class */ | 65536 /* Interface */) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -25459,9 +31537,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getCombinedTypeFlags(type) & 96 /* Nullable */; + var kind = getFalsyFlags(type) & 6144 /* Nullable */; if (kind) { - error(node, kind & 32 /* Undefined */ ? kind & 64 /* Null */ ? + error(node, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -25478,24 +31556,24 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); - if (isTypeAny(type)) { + if (isTypeAny(type) || type === silentNeverType) { return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 512 /* TypeParameter */ && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { // handle cases when type is Type parameter with invalid or any constraint return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); + reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); } return unknownType; } if (noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (prop.valueDeclaration.flags & 8 /* Private */)) { + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { if (prop.flags & 16777216 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -25513,10 +31591,24 @@ var ts; // accessor, or optional method. if (node.kind !== 172 /* PropertyAccessExpression */ || ts.isAssignmentTarget(node) || !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 16384 /* Union */)) { + !(prop.flags & 8192 /* Method */ && propType.flags & 524288 /* Union */)) { return propType; } - return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*includeOuterFunctions*/ false); + return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 524288 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 /* PropertyAccessExpression */ @@ -25596,8 +31688,8 @@ var ts; // Obtain base constraint such that we can bail out if the constraint is an unknown type var objectType = getApparentType(checkNonNullExpression(node.expression)); var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; - if (objectType === unknownType) { - return unknownType; + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; } var isConstEnum = isConstEnumObjectType(objectType); if (isConstEnum && @@ -25615,23 +31707,24 @@ var ts; // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. // See if we can index as a property. if (node.argumentExpression) { - var name_13 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_13 !== undefined) { - var prop = getPropertyOfType(objectType, name_13); + var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_16 !== undefined) { + var prop = getPropertyOfType(objectType, name_16); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_13, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_16, symbolToString(objectType.symbol)); return unknownType; } } } // Check for compatible indexer types. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { + var allowedNullableFlags = strictNullChecks ? 0 : 6144 /* Nullable */; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */ | allowedNullableFlags)) { // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -25695,7 +31788,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 16777216 /* ESSymbol */) === 0) { + if ((expressionType.flags & 512 /* ESSymbol */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -25755,13 +31848,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_9 = signature.declaration && signature.declaration.parent; + var parent_10 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_9 === lastParent) { + if (lastParent && parent_10 === lastParent) { index++; } else { - lastParent = parent_9; + lastParent = parent_10; index = cutoffIndex; } } @@ -25769,12 +31862,12 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_9; + lastParent = parent_10; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -25867,7 +31960,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -25878,7 +31971,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); + var context = createInferenceContext(signature, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context, instantiateType(source, contextualMapper), target); @@ -26001,9 +32094,7 @@ var ts; // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { - argType = arg.kind === 9 /* StringLiteral */ && !reportErrors - ? getStringLiteralTypeForText(arg.text) - : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -26188,10 +32279,10 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getStringLiteralTypeForText(element.name.text); + return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); case 140 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 16777216 /* ESSymbol */)) { + if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { return nameType; } else { @@ -26410,7 +32501,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -26437,7 +32528,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); } return candidate; } @@ -26462,14 +32553,14 @@ var ts; var candidate = void 0; var typeArgumentsAreValid = void 0; var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate.typeParameters, /*inferUnionTypes*/ false) + ? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false) : undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -26531,6 +32622,9 @@ var ts; return resolveUntypedCall(node); } var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } var apparentType = getApparentType(funcType); if (apparentType === unknownType) { // Another error has already been reported @@ -26542,16 +32636,10 @@ var ts; // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - // TS 1.0 spec: 4.12 - // If FuncExpr is of type Any, or of an object type that has no call or construct signatures - // but is a subtype of the Function interface, the call is an untyped function call. In an - // untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (isTypeAny(funcType) || - (isTypeAny(apparentType) && funcType.flags & 512 /* TypeParameter */) || - (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { @@ -26567,12 +32655,34 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); } return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have + // no common signatures. + if (funcType.flags & 524288 /* Union */) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -26581,6 +32691,9 @@ var ts; } } var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } // If expressionType's apparent type(section 3.8.1) is an object type with one or // more construct signatures, the expression is processed in the same manner as a // function call, but using the construct signatures as the initial set of candidate @@ -26596,7 +32709,7 @@ var ts; // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 128 /* Abstract */) { + if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -26643,19 +32756,31 @@ var ts; return true; } var declaration = signature.declaration; - var flags = declaration.flags; + var modifiers = ts.getModifierFlags(declaration); // Public constructor is accessible. - if (!(flags & (8 /* Private */ | 16 /* Protected */))) { + if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - // A private or protected constructor can only be instantiated within it's own class + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { - if (flags & 8 /* Private */) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 /* Protected */ && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } + if (modifiers & 8 /* Private */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (flags & 16 /* Protected */) { + if (modifiers & 16 /* Protected */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -26670,11 +32795,12 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -26707,13 +32833,14 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); return resolveErrorCall(node); @@ -26742,10 +32869,10 @@ var ts; // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work // to correctly fill the candidatesOutArray. var cached = links.resolvedSignature; - if (cached && cached !== anySignature && !candidatesOutArray) { + if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = anySignature; + links.resolvedSignature = resolvingSignature; var result = resolveSignature(node, candidatesOutArray); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary @@ -26756,12 +32883,12 @@ var ts; function getResolvedOrAnySignature(node) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. - return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); } return links.inferredClassType; } @@ -26811,7 +32938,7 @@ var ts; return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { @@ -26830,7 +32957,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32 /* Undefined */); + return includeFalsyTypes(type, 2048 /* Undefined */); } } return type; @@ -26842,6 +32969,12 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (context.thisParameter) { + if (!signature.thisParameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); + } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -26859,7 +32992,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193 /* OmittedExpression */) { + if (!ts.isOmittedExpression(element)) { if (element.name.kind === 69 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -26979,20 +33112,8 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - // When yield/return statements are contextually typed we allow the return type to be a union type. - // Otherwise we require the yield/return expressions to have a best common supertype. - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); - if (!type) { - if (funcIsGenerator) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); - return createIterableIteratorType(unknownType); - } - else { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); - } - } + // Return a union of the return expression types. + type = getUnionType(types, /*subtypeReduction*/ true); if (funcIsGenerator) { type = createIterableIteratorType(type); } @@ -27000,6 +33121,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } + if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } var widenedType = getWidenedType(type); // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the @@ -27024,27 +33148,21 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - var expr = node.expression; - if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { + if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(expr.expression); - if (!(type.flags & 16384 /* Union */)) { - return false; - } - var propName = expr.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { + var type = checkExpression(node.expression); + if (!isLiteralType(type)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(propType, switchTypes); + return eachTypeContainedIn(type, switchTypes); } function functionHasImplicitReturn(func) { - if (!(func.flags & 32768 /* HasImplicitReturn */)) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); @@ -27069,7 +33187,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type === neverType) { + if (type.flags & 8192 /* Never */) { hasReturnOfTypeNever = true; } else if (!ts.contains(aggregatedTypes, type)) { @@ -27105,7 +33223,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -27113,8 +33231,8 @@ var ts; if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !functionHasImplicitReturn(func)) { return; } - var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; - if (returnType === neverType) { + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 8192 /* Never */) { error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -27234,7 +33352,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -27248,8 +33366,8 @@ var ts; // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return symbol.isReadonly || - symbol.flags & 4 /* Property */ && (getDeclarationFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || - symbol.flags & 3 /* Variable */ && (getDeclarationFlagsFromSymbol(symbol) & 2048 /* Const */) !== 0 || + symbol.flags & 4 /* Property */ && (getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || + symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || (symbol.flags & 8 /* EnumMember */) !== 0; } @@ -27334,7 +33452,7 @@ var ts; function checkAwaitExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 33554432 /* AwaitContext */)) { + if (!(node.flags & 262144 /* AwaitContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -27346,16 +33464,25 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { + return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + } switch (node.operator) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: - if (maybeTypeOfKind(operandType, 16777216 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49 /* ExclamationToken */: - return booleanType; + var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); + return facts === 1048576 /* Truthy */ ? falseType : + facts === 2097152 /* Falsy */ ? trueType : + booleanType; case 41 /* PlusPlusToken */: case 42 /* MinusMinusToken */: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -27369,6 +33496,9 @@ var ts; } function checkPostfixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors @@ -27382,10 +33512,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 49152 /* UnionOrIntersection */) { + if (type.flags & 1572864 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -27400,20 +33530,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { var types = type.types; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 32768 /* Intersection */) { + if (type.flags & 1048576 /* Intersection */) { var types = type.types; - for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { - var t = types_12[_a]; + for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { + var t = types_16[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -27422,18 +33552,21 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (80896 /* ObjectType */ | 65536 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (2588672 /* ObjectType */ | 2097152 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.15.4 // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, // and the right operand to be of type Any or a subtype of the 'Function' interface type. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 16777726 /* Primitive */)) { + if (isTypeOfKind(leftType, 8190 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -27443,36 +33576,39 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var p = properties_3[_i]; + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var p = properties_4[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); } return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 /* PropertyAssignment */ || property.kind === 254 /* ShorthandPropertyAssignment */) { - var name_14 = property.name; - if (name_14.kind === 140 /* ComputedPropertyName */) { - checkComputedPropertyName(name_14); + var name_17 = property.name; + if (name_17.kind === 140 /* ComputedPropertyName */) { + checkComputedPropertyName(name_17); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_17)) { return undefined; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_17); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -27488,7 +33624,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_14)); + error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); } } else { @@ -27521,8 +33657,11 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -27554,7 +33693,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32 /* Undefined */)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -27583,8 +33722,76 @@ var ts; } return sourceType; } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 69 /* Identifier */: + case 9 /* StringLiteral */: + case 10 /* RegularExpressionLiteral */: + case 176 /* TaggedTemplateExpression */: + case 189 /* TemplateExpression */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + case 93 /* NullKeyword */: + case 135 /* UndefinedKeyword */: + case 179 /* FunctionExpression */: + case 192 /* ClassExpression */: + case 180 /* ArrowFunction */: + case 170 /* ArrayLiteralExpression */: + case 171 /* ObjectLiteralExpression */: + case 182 /* TypeOfExpression */: + case 196 /* NonNullExpression */: + case 242 /* JsxSelfClosingElement */: + case 241 /* JsxElement */: + return true; + case 188 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 187 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 185 /* PrefixUnaryExpression */: + case 186 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 49 /* ExclamationToken */: + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 183 /* VoidExpression */: // Explicit opt-out + case 177 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 195 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 96 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], /*subtypeReduction*/ true); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -27619,23 +33826,26 @@ var ts; case 68 /* CaretEqualsToken */: case 46 /* AmpersandToken */: case 66 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.19.1 // These operators require their operands to be of type Any, the Number primitive type, // or an enum type. Operands of an enum type are treated // as having the primitive type Number. If one operand is the null or undefined value, // it is treated as having the type of the other operand. // The result is always of the Number primitive type. - if (leftType.flags & 96 /* Nullable */) + if (leftType.flags & 6144 /* Nullable */) leftType = rightType; - if (rightType.flags & 96 /* Nullable */) + if (rightType.flags & 6144 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion - if ((leftType.flags & 8 /* Boolean */) && - (rightType.flags & 8 /* Boolean */) && + if ((leftType.flags & 136 /* BooleanLike */) && + (rightType.flags & 136 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -27650,24 +33860,27 @@ var ts; return numberType; case 35 /* PlusToken */: case 57 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.19.2 // The binary + operator requires both operands to be of the Number primitive type or an enum type, // or at least one of the operands to be of type Any or the String primitive type. // If one operand is the null or undefined value, it is treated as having the type of the other operand. - if (leftType.flags & 96 /* Nullable */) + if (leftType.flags & 6144 /* Nullable */) leftType = rightType; - if (rightType.flags & 96 /* Nullable */) + if (rightType.flags & 6144 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { + if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { + if (isTypeOfKind(leftType, 34 /* StringLike */) || isTypeOfKind(rightType, 34 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -27703,6 +33916,12 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -27712,19 +33931,26 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; + return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + leftType; case 52 /* BarBarToken */: - return getUnionType([getNonNullableType(leftType), rightType]); + return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; case 56 /* EqualsToken */: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); case 24 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } return rightType; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 16777216 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -27785,7 +34011,7 @@ var ts; function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 8388608 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 65536 /* YieldContext */) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -27824,14 +34050,22 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getUnionType([type1, type2]); + return getBestChoiceType(type1, type2); } - function checkStringLiteralExpression(node) { - var contextualType = getContextualType(node); - if (contextualType && isStringLiteralUnionType(contextualType)) { - return getStringLiteralTypeForText(node.text); + function checkLiteralExpression(node) { + if (node.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + case 8 /* NumericLiteral */: + return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + case 99 /* TrueKeyword */: + return trueType; + case 84 /* FalseKeyword */: + return falseType; } - return stringType; } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -27864,6 +34098,36 @@ var ts; } return links.resolvedType; } + function isTypeAssertion(node) { + node = skipParenthesizedNodes(node); + return node.kind === 177 /* TypeAssertionExpression */ || node.kind === 195 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var type = checkExpressionCached(declaration.initializer); + return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 16384 /* TypeParameter */) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + // If the type parameter is constrained to the base primitive type we're checking for, + // consider this a literal context. For example, given a type parameter 'T extends string', + // this causes us to infer string literal types for T. + if (apparentType.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { + return true; + } + contextualType = apparentType; + } + return maybeTypeOfKind(contextualType, 480 /* Literal */); + } + return false; + } + function checkExpressionForMutableLocation(node, contextualMapper) { + var type = checkExpression(node, contextualMapper); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } function checkPropertyAssignment(node, contextualMapper) { // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including @@ -27871,7 +34135,7 @@ var ts; if (node.name.kind === 140 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - return checkExpression(node.initializer, contextualMapper); + return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { // Grammar checking @@ -27930,11 +34194,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - // Grammar checking - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69 /* Identifier */: @@ -27945,15 +34204,13 @@ var ts; return checkSuperExpression(node); case 93 /* NullKeyword */: return nullWideningType; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: - return booleanType; - case 8 /* NumericLiteral */: - return checkNumericLiteral(node); + return checkLiteralExpression(node); case 189 /* TemplateExpression */: return checkTemplateExpression(node); - case 9 /* StringLiteral */: - return checkStringLiteralExpression(node); case 11 /* NoSubstitutionTemplateLiteral */: return stringType; case 10 /* RegularExpressionLiteral */: @@ -28037,7 +34294,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 92 /* ParameterPropertyModifier */) { + if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { func = ts.getContainingFunction(node); if (!(func.kind === 148 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -28109,9 +34366,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_15 = _a[_i].name; - if (ts.isBindingPattern(name_15) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, parameterName, typePredicate.parameterName)) { + var name_18 = _a[_i].name; + if (ts.isBindingPattern(name_18) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -28131,23 +34388,27 @@ var ts; case 156 /* FunctionType */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - var parent_10 = node.parent; - if (node === parent_10.type) { - return parent_10; + var parent_11 = node.parent; + if (node === parent_11.type) { + return parent_11; } } } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (name_16.kind === 69 /* Identifier */ && - name_16.text === predicateVariableName) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name_19 = element.name; + if (name_19.kind === 69 /* Identifier */ && + name_19.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_16.kind === 168 /* ArrayBindingPattern */ || - name_16.kind === 167 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, predicateVariableNode, predicateVariableName)) { + else if (name_19.kind === 168 /* ArrayBindingPattern */ || + name_19.kind === 167 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { return true; } } @@ -28202,22 +34463,27 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (!node.body) { + if (noUnusedIdentifiers && !node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var getter = 1, setter = 2, property = getter | setter; - var instanceNames = {}; - var staticNames = {}; + var Accessor; + (function (Accessor) { + Accessor[Accessor["Getter"] = 1] = "Getter"; + Accessor[Accessor["Setter"] = 2] = "Setter"; + Accessor[Accessor["Property"] = 3] = "Property"; + })(Accessor || (Accessor = {})); + var instanceNames = ts.createMap(); + var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, property); + addName(instanceNames, param.name, param.name.text, 3 /* Property */); } } } @@ -28228,21 +34494,21 @@ var ts; if (memberName) { switch (member.kind) { case 149 /* GetAccessor */: - addName(names, member.name, memberName, getter); + addName(names, member.name, memberName, 1 /* Getter */); break; case 150 /* SetAccessor */: - addName(names, member.name, memberName, setter); + addName(names, member.name, memberName, 2 /* Setter */); break; case 145 /* PropertyDeclaration */: - addName(names, member.name, memberName, property); + addName(names, member.name, memberName, 3 /* Property */); break; } } } } function addName(names, location, name, meaning) { - if (ts.hasProperty(names, name)) { - var prev = names[name]; + var prev = names[name]; + if (prev) { if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -28256,7 +34522,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = {}; + var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144 /* PropertySignature */) { @@ -28270,7 +34536,7 @@ var ts; default: continue; } - if (ts.hasProperty(names, memberName)) { + if (names[memberName]) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -28334,7 +34600,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (node.flags & 128 /* Abstract */ && node.body) { + if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -28383,7 +34649,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 145 /* PropertyDeclaration */ && - !(n.flags & 32 /* Static */) && + !(ts.getModifierFlags(n) & 32 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -28403,7 +34669,7 @@ var ts; // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & 92 /* ParameterPropertyModifier */; }); + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -28436,13 +34702,8 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); if (node.kind === 149 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768 /* HasImplicitReturn */)) { - if (node.flags & 65536 /* HasExplicitReturn */) { - if (compilerOptions.noImplicitReturns) { - error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -28459,10 +34720,10 @@ var ts; var otherKind = node.kind === 149 /* GetAccessor */ ? 150 /* SetAccessor */ : 149 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 28 /* AccessibilityModifier */) !== (otherAccessor.flags & 28 /* AccessibilityModifier */))) { + if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (((node.flags & 128 /* Abstract */) !== (otherAccessor.flags & 128 /* Abstract */))) { + if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } // TypeScript 1.0 spec (April 2014): 4.5 @@ -28471,7 +34732,10 @@ var ts; checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - getTypeOfAccessors(getSymbolOfNode(node)); + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 149 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171 /* ObjectLiteralExpression */) { checkSourceElement(node.body); @@ -28503,7 +34767,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -28525,6 +34789,9 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } + if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } } } function checkTypeQuery(node) { @@ -28554,10 +34821,10 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 8 /* Private */) && ts.isInAmbientContext(node); + return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedNodeFlags(n); + var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. if (n.parent.kind !== 222 /* InterfaceDeclaration */ && @@ -28620,7 +34887,7 @@ var ts; } } var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; - var someNodeFlags = 0; + var someNodeFlags = 0 /* None */; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; var allHaveQuestionToken = true; @@ -28651,13 +34918,13 @@ var ts; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { var reportError = (node.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) && - (node.flags & 32 /* Static */) !== (subsequentNode.flags & 32 /* Static */); + (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members // 2. something with the same name was defined before the set of overloads that prevents them from merging // here we'll report error only for the first case since for second we should already report error in binder if (reportError) { - var diagnostic = node.flags & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -28675,7 +34942,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (node.flags & 128 /* Abstract */) { + if (ts.getModifierFlags(node) & 128 /* Abstract */) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -28743,7 +35010,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -28832,10 +35099,10 @@ var ts; case 224 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; case 229 /* ImportEqualsDeclaration */: - var result_1 = 0; + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); - return result_1; + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; default: return 1048576 /* ExportValue */; } @@ -28872,7 +35139,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 4096 /* Reference */) { + if (promise.flags & 131072 /* Reference */) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -28898,7 +35165,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -28916,13 +35183,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types); + return getUnionType(types, /*subtypeReduction*/ true); } else { var promisedType = getPromisedType(type); @@ -29001,7 +35268,7 @@ var ts; * @param returnType The return type of a FunctionLikeDeclaration * @param location The node on which to report the error. */ - function checkCorrectPromiseType(returnType, location) { + function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { if (returnType === unknownType) { // The return type already had some other error, so we ignore and return // the unknown type. @@ -29018,7 +35285,7 @@ var ts; } // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(location, diagnostic, typeName); return unknownType; } /** @@ -29037,7 +35304,7 @@ var ts; function checkAsyncFunctionReturnType(node) { if (languageVersion >= 2 /* ES6 */) { var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type); + return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { @@ -29079,17 +35346,17 @@ var ts; } var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { + // try to fall back to global promise type. var typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - return unknownType; + return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); } // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. checkReturnTypeAnnotationAsExpression(node); // Validate the promise constructor type. var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } // Verify there is no local declaration that could collide with the promise constructor. @@ -29144,7 +35411,7 @@ var ts; // serialize the type metadata. if (node && node.kind === 155 /* TypeReference */) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = root.parent.kind === 155 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; // Resolve type so we know which symbol is referenced var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias @@ -29333,22 +35600,21 @@ var ts; } function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function(key) { - if (ts.hasProperty(node.locals, key)) { - var local_1 = node.locals[key]; - if (!local_1.isReferenced) { - if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142 /* Parameter */) { - var parameter = local_1.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); - } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); + var _loop_1 = function (key) { + var local = node.locals[key]; + if (!local.isReferenced) { + if (local.valueDeclaration && local.valueDeclaration.kind === 142 /* Parameter */) { + var parameter = local.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + } } }; for (var key in node.locals) { @@ -29356,6 +35622,9 @@ var ts; } } } + function parameterIsThisKeyword(parameter) { + return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; + } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -29365,15 +35634,15 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 147 /* MethodDeclaration */ || member.kind === 145 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && member.flags & 8 /* Private */) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } else if (member.kind === 148 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && parameter.flags & 8 /* Private */) { - error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -29384,9 +35653,16 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!typeParameter.symbol.isReferenced) { + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -29396,14 +35672,12 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - if (ts.hasProperty(node.locals, key)) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); - } + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } } @@ -29522,7 +35796,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152 /* HasAsyncFunctions */) { + if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -29551,7 +35825,7 @@ var ts; // const x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { return; } // skip variable declarations that don't have initializers @@ -29566,7 +35840,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072 /* BlockScoped */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219 /* VariableDeclarationList */); var container = varDeclList.parent.kind === 200 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent @@ -29583,8 +35857,8 @@ var ts; // otherwise if variable has an initializer - show error that initialization will fail // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - var name_17 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_17, name_17); + var name_20 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); } } } @@ -29637,7 +35911,7 @@ var ts; // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred if (current.parent.kind === 145 /* PropertyDeclaration */ && - !(current.parent.flags & 32 /* Static */) && + !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)) { return; } @@ -29672,12 +35946,12 @@ var ts; checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_11 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_11); - var name_18 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_18)); - if (parent_11.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); + var parent_12 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_12); + var name_21 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); + if (parent_12.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -29750,7 +36024,7 @@ var ts; 128 /* Abstract */ | 64 /* Readonly */ | 32 /* Static */; - return (left.flags & interestingFlags) === (right.flags & interestingFlags); + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -29892,7 +36166,7 @@ var ts; if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -29903,7 +36177,7 @@ var ts; var rightType = checkNonNullExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -29985,7 +36259,7 @@ var ts; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableType()) { + if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -30000,7 +36274,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true), errorNode); } } return typeAsIterable.iterableElementType; @@ -30026,7 +36300,7 @@ var ts; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. - if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIteratorType()) { + if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -30041,7 +36315,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -30063,7 +36337,7 @@ var ts; } // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), // then just grab its type argument. - if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, /*errorNode*/ undefined) || @@ -30091,10 +36365,10 @@ var ts; // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 16384 /* Union */) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); + if (arrayOrStringType.flags & 524288 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34 /* StringLike */); }), /*subtypeReduction*/ true); } - else if (arrayOrStringType.flags & 258 /* StringLike */) { + else if (arrayOrStringType.flags & 34 /* StringLike */) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -30106,7 +36380,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType === neverType) { + if (arrayType.flags & 8192 /* Never */) { return stringType; } } @@ -30126,10 +36400,10 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 258 /* StringLike */) { + if (arrayElementType.flags & 34 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType]); + return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); } return arrayElementType; } @@ -30143,7 +36417,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 /* Void */ | 1 /* Any */); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -30157,7 +36431,7 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType === neverType) { + if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (func.asteriskToken) { // A generator does not need its return expressions checked against its return type. @@ -30201,7 +36475,7 @@ var ts; function checkWithStatement(node) { // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 33554432 /* AwaitContext */) { + if (node.flags & 262144 /* AwaitContext */) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -30295,7 +36569,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals && ts.hasProperty(locals, identifierName)) { + if (locals) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -30320,14 +36594,14 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 1024 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 32768 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(member.flags & 32 /* Static */) && ts.hasDynamicName(member)) { + if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -30339,7 +36613,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (type.flags & 2048 /* Interface */)) { + if (!errorNode && (type.flags & 65536 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -30364,7 +36638,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 2048 /* Interface */) { + else if (containingType.flags & 65536 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -30436,7 +36710,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 512 /* Default */)) { + if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -30479,6 +36753,11 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { + error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); + } + } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type @@ -30496,15 +36775,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { + if (!ts.isEntityNameExpression(typeRefNode.expression)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; - if (declaredType.flags & (1024 /* Class */ | 2048 /* Interface */)) { + var declaredType = (t.flags & 131072 /* Reference */) ? t.target : t; + if (declaredType.flags & (32768 /* Class */ | 65536 /* Interface */)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -30523,7 +36802,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && declaration.flags & 8 /* Private */) { + if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); @@ -30562,7 +36841,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -30574,7 +36853,7 @@ var ts; // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { if (derivedClassDecl.kind === 192 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -30585,7 +36864,7 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); if ((baseDeclarationFlags & 8 /* Private */) || (derivedDeclarationFlags & 8 /* Private */)) { // either base or derived property is private - not override, skip it continue; @@ -30658,19 +36937,19 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = {}; + var seen = ts.createMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; - if (!ts.hasProperty(seen, prop.name)) { + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var prop = properties_5[_a]; + var existing = seen[prop.name]; + if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; } else { - var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -30711,7 +36990,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -30719,7 +36998,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - checkUnusedTypeParameters(node); + registerForUnusedIdentifiersCheck(node); } } function checkTypeAliasDeclaration(node) { @@ -30743,7 +37022,7 @@ var ts; } else { var text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text)) { + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -31072,10 +37351,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - // Ambient shorthand module is an implicit any - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -31102,9 +37377,9 @@ var ts; break; case 169 /* BindingElement */: case 218 /* VariableDeclaration */: - var name_19 = node.name; - if (ts.isBindingPattern(name_19)) { - for (var _b = 0, _c = name_19.elements; _b < _c.length; _b++) { + var name_22 = node.name; + if (ts.isBindingPattern(name_22)) { + for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); @@ -31137,19 +37412,20 @@ var ts; } } function getFirstIdentifier(node) { - while (true) { - if (node.kind === 139 /* QualifiedName */) { - node = node.left; - } - else if (node.kind === 172 /* PropertyAccessExpression */) { - node = node.expression; - } - else { - break; - } + switch (node.kind) { + case 69 /* Identifier */: + return node; + case 139 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 69 /* Identifier */); + return node; + case 172 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 69 /* Identifier */); + return node; } - ts.Debug.assert(node.kind === 69 /* Identifier */); - return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -31189,8 +37465,8 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | - (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | - (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); + (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -31210,7 +37486,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -31238,7 +37514,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1 /* Export */) { + if (ts.getModifierFlags(node) & 1 /* Export */) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -31247,11 +37523,11 @@ var ts; if (target.flags & 107455 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1536 /* Namespace */).flags & 1536 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793056 /* Type */) { + if (target.flags & 793064 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -31269,7 +37545,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -31301,7 +37577,7 @@ var ts; if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, + var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); @@ -31322,7 +37598,7 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69 /* Identifier */) { @@ -31371,7 +37647,7 @@ var ts; var _a = exports[id], declarations = _a.declarations, flags = _a.flags; // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1536 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -31554,9 +37830,10 @@ var ts; } } function checkSourceFile(node) { - var start = new Date().getTime(); + ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); - ts.checkTime += new Date().getTime() - start; + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { @@ -31636,8 +37913,8 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; - var memberFlags = 0; + var symbols = ts.createMap(); + var memberFlags = 0 /* None */; if (isInsideWithStatementBody(location)) { // We cannot answer semantic questions within a with block, do not proceed any further return []; @@ -31674,7 +37951,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!(memberFlags & 32 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); + copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); } break; case 179 /* FunctionExpression */: @@ -31687,7 +37964,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = location.flags; + memberFlags = ts.getModifierFlags(location); location = location.parent; } copySymbols(globals, meaning); @@ -31705,7 +37982,7 @@ var ts; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array - if (!ts.hasProperty(symbols, id)) { + if (!symbols[id]) { symbols[id] = symbol; } } @@ -31794,17 +38071,15 @@ var ts; default: } } - if (entityName.parent.kind === 235 /* ExportAssignment */) { + if (entityName.parent.kind === 235 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 172 /* PropertyAccessExpression */) { - if (isInRightSideOfImportOrExportAssignment(entityName)) { - // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); - } + if (entityName.kind !== 172 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -31813,19 +38088,19 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 194 /* ExpressionWithTypeArguments */) { - meaning = 793056 /* Type */; + meaning = 793064 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455 /* Value */; } } else { - meaning = 1536 /* Namespace */; + meaning = 1920 /* Namespace */; } meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (ts.isExpression(entityName)) { + else if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { // Missing entity name. return undefined; @@ -31852,7 +38127,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 246 /* JsxAttribute */) { @@ -31908,7 +38183,7 @@ var ts; } // fallthrough case 95 /* SuperKeyword */: - var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case 165 /* ThisType */: return getTypeFromTypeNode(node).symbol; @@ -31956,17 +38231,17 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return unknownType; } - if (ts.isTypeNode(node)) { + if (ts.isPartOfTypeNode(node)) { return getTypeFromTypeNode(node); } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { return getTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -32051,7 +38326,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return checkExpression(expr); + return getRegularTypeOfLiteralType(checkExpression(expr)); } /** * Gets either the static or instance type of a class element, based on @@ -32059,7 +38334,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 32 /* Static */ + return ts.getModifierFlags(node) & 32 /* Static */ ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -32070,7 +38345,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!ts.hasProperty(propsByName, p.name)) { + if (!propsByName[p.name]) { propsByName[p.name] = p; } }); @@ -32080,9 +38355,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* SyntheticProperty */) { var symbols_3 = []; - var name_20 = symbol.name; + var name_23 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_20); + var symbol = getPropertyOfType(t, name_23); if (symbol) { symbols_3.push(symbol); } @@ -32103,12 +38378,18 @@ var ts; } // Emitter support function isArgumentsLocalBinding(node) { - return getReferencedValueSymbol(node) === argumentsSymbol; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + return getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol) { - // module not found - be conservative + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -32121,7 +38402,7 @@ var ts; // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455 /* Value */) - : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -32129,32 +38410,44 @@ var ts; return s && !!(s.flags & 107455 /* Value */); } } + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node) { - var symbol = getReferencedValueSymbol(node); - if (symbol) { - if (symbol.flags & 1048576 /* ExportValue */) { - // If we reference an exported entity within the same module declaration, then whether - // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the - // kinds that we do NOT prefix. - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (exportSymbol.flags & 944 /* ExportHasLocal */) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 256 /* SourceFile */) { - // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. - if (parentSymbol.valueDeclaration === ts.getSourceFileOfNode(node)) { - return parentSymbol.valueDeclaration; + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { + return undefined; } + symbol = exportSymbol; } - for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 225 /* ModuleDeclaration */ || n.kind === 224 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { - return n; + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 256 /* SourceFile */) { + var symbolFile = parentSymbol.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + for (var n = node.parent; n; n = n.parent) { + if (ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) { + return n; + } } } } @@ -32163,8 +38456,14 @@ var ts; // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. function getReferencedImportDeclaration(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined; + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && symbol.flags & 8388608 /* Alias */) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* BlockScoped */) { @@ -32211,32 +38510,56 @@ var ts; // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. function getReferencedDeclarationWithCollidingName(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel function isDeclarationWithCollidingName(node) { - return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; } function isValueAliasDeclaration(node) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + // A synthesized node comes from an emit transformation and is always a value. + return true; + } switch (node.kind) { case 229 /* ImportEqualsDeclaration */: case 231 /* ImportClause */: case 232 /* NamespaceImport */: case 234 /* ImportSpecifier */: case 238 /* ExportSpecifier */: - return isAliasResolvedToValue(getSymbolOfNode(node)); + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); case 235 /* ExportAssignment */: - return node.expression && node.expression.kind === 69 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; + return node.expression + && node.expression.kind === 69 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 256 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 256 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -32257,9 +38580,14 @@ var ts; return isConstEnumSymbol(s) || s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { + node = ts.getParseTreeNode(node); + // Purely synthesized nodes are always emitted. + if (node === undefined) { + return true; + } if (ts.isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (getSymbolLinks(symbol).referenced) { + if (symbol && getSymbolLinks(symbol).referenced) { return true; } } @@ -32289,7 +38617,8 @@ var ts; return false; } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + node = ts.getParseTreeNode(node); + return node ? getNodeLinks(node).flags : undefined; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -32309,17 +38638,21 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } - function getTypeReferenceSerializationKind(typeName) { + function getTypeReferenceSerializationKind(typeName, location) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true); + var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var globalPromiseSymbol = tryGetGlobalPromiseConstructorSymbol(); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } var constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 793056 /* Type */, /*ignoreErrors*/ true); + var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; @@ -32331,22 +38664,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16 /* Void */)) { - return ts.TypeReferenceSerializationKind.VoidType; + else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 8 /* Boolean */)) { + else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 132 /* NumberLike */)) { + else if (isTypeOfKind(type, 340 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 258 /* StringLike */)) { + else if (isTypeOfKind(type, 34 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTypeOfKind(type, 8192 /* Tuple */)) { + else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 16777216 /* ESSymbol */)) { + else if (isTypeOfKind(type, 512 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -32363,7 +38696,7 @@ var ts; // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) - ? getTypeOfSymbol(symbol) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -32382,17 +38715,46 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return ts.hasProperty(globals, name); + return !!globals[name]; } - function getReferencedValueSymbol(reference) { - return getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, - /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent_13 = reference.parent; + if (ts.isDeclaration(parent_13) && reference === parent_13.name) { + location = getDeclarationContainer(parent_13); + } + } + return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); } function getReferencedValueDeclaration(reference) { - ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getReferencedValueSymbol(reference); - return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -32403,9 +38765,6 @@ var ts; // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { - if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { - continue; - } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; @@ -32441,7 +38800,9 @@ var ts; isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue }; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -32454,7 +38815,7 @@ var ts; // identifiers are treated as values only if they appear in type queries var meaning = (node.kind === 172 /* PropertyAccessExpression */) || (node.kind === 69 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793056 /* Type */ | 1536 /* Namespace */; + : 793064 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -32491,9 +38852,9 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_12 = getParentOfSymbol(current); - if (parent_12) { - current = parent_12; + var parent_14 = getParentOfSymbol(current); + if (parent_14) { + current = parent_14; } else { break; @@ -32523,12 +38884,16 @@ var ts; } function initializeTypeChecker() { // Bind all source files and propagate errors - ts.forEach(host.getSourceFiles(), function (file) { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); - }); - var augmentations; + } // Initialize global symbol table - ts.forEach(host.getSourceFiles(), function (file) { + var augmentations; + var requestedExternalEmitHelpers = 0; + var firstFileRequestingExternalHelpers; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -32539,16 +38904,31 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - mergeSymbolTable(globals, file.symbol.globalExports); + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + for (var id in source) { + if (!(id in globals)) { + globals[id] = source[id]; + } + } } - }); + if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { + var fileRequestedExternalEmitHelpers = file.flags & 31744 /* EmitHelperFlags */; + if (fileRequestedExternalEmitHelpers) { + requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; + if (firstFileRequestingExternalHelpers === undefined) { + firstFileRequestingExternalHelpers = file; + } + } + } + } if (augmentations) { // merge module augmentations. // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed - for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { - var list = augmentations_1[_i]; - for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { - var augmentation = list_2[_a]; + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; mergeModuleAugmentation(augmentation); } } @@ -32574,10 +38954,11 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", /*arity*/ 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", /*arity*/ 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", /*arity*/ 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); + tryGetGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalSymbol("Promise", 107455 /* Value */, /*diagnostic*/ undefined) && getGlobalPromiseConstructorSymbol(); }); getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); getGlobalThenableType = ts.memoize(createThenableType); getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); }); @@ -32594,9 +38975,48 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793056 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793064 /* Type */, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + // If we have specified that we are importing helpers, we should report global + // errors if we cannot resolve the helpers external module, or if it does not have + // the necessary helpers exported. + if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { + // Find the first reference to the helpers module. + var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, + /*errorNode*/ undefined); + // If we found the module, report errors if it does not have the necessary exports. + if (helpersModule) { + var exports = helpersModule.exports; + if (requestedExternalEmitHelpers & 1024 /* HasClassExtends */ && languageVersion < 2 /* ES6 */) { + verifyHelperSymbol(exports, "__extends", 107455 /* Value */); + } + if (requestedExternalEmitHelpers & 16384 /* HasJsxSpreadAttributes */ && compilerOptions.jsx !== 1 /* Preserve */) { + verifyHelperSymbol(exports, "__assign", 107455 /* Value */); + } + if (requestedExternalEmitHelpers & 2048 /* HasDecorators */) { + verifyHelperSymbol(exports, "__decorate", 107455 /* Value */); + if (compilerOptions.emitDecoratorMetadata) { + verifyHelperSymbol(exports, "__metadata", 107455 /* Value */); + } + } + if (requestedExternalEmitHelpers & 4096 /* HasParamDecorators */) { + verifyHelperSymbol(exports, "__param", 107455 /* Value */); + } + if (requestedExternalEmitHelpers & 8192 /* HasAsyncFunctions */) { + verifyHelperSymbol(exports, "__awaiter", 107455 /* Value */); + if (languageVersion < 2 /* ES6 */) { + verifyHelperSymbol(exports, "__generator", 107455 /* Value */); + } + } + } + } + } + function verifyHelperSymbol(symbols, name, meaning) { + var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); + if (!symbol) { + error(/*location*/ undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -32609,7 +39029,7 @@ var ts; // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(65536 /* Anonymous */); + var thenableType = createObjectType(2097152 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -32638,52 +39058,12 @@ var ts; return false; } function checkGrammarModifiers(node) { - switch (node.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 225 /* ModuleDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 142 /* Parameter */: - break; - case 220 /* FunctionDeclaration */: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && - node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 200 /* VariableStatement */: - case 223 /* TypeAliasDeclaration */: - if (node.modifiers && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 224 /* EnumDeclaration */: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && - node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - default: - return false; - } - if (!node.modifiers) { - return; + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; - var flags = 0; + var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 128 /* ReadonlyKeyword */) { @@ -32819,7 +39199,7 @@ var ts; node.kind !== 150 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { + if (!(node.parent.kind === 221 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -32874,10 +39254,61 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function checkGrammarAsyncModifier(node, asyncModifier) { - if (languageVersion < 2 /* ES6 */) { - return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 148 /* Constructor */: + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 153 /* IndexSignature */: + case 225 /* ModuleDeclaration */: + case 230 /* ImportDeclaration */: + case 229 /* ImportEqualsDeclaration */: + case 236 /* ExportDeclaration */: + case 235 /* ExportAssignment */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 142 /* Parameter */: + return false; + default: + if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 220 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AsyncKeyword */); + case 221 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 115 /* AbstractKeyword */); + case 222 /* InterfaceDeclaration */: + case 200 /* VariableStatement */: + case 223 /* TypeAliasDeclaration */: + return true; + case 224 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 74 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { case 147 /* MethodDeclaration */: case 220 /* FunctionDeclaration */: @@ -32968,7 +39399,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1023 /* Modifier */) { + if (ts.getModifierFlags(parameter) !== 0) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -33006,8 +39437,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { - var arg = args_1[_i]; + for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { + var arg = args_2[_i]; if (arg.kind === 193 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -33111,29 +39542,33 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; - var _loop_2 = function(prop) { - var name_21 = prop.name; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var name_24 = prop.name; if (prop.kind === 193 /* OmittedExpression */ || - name_21.kind === 140 /* ComputedPropertyName */) { + name_24.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_21); + checkGrammarComputedPropertyName(name_24); } if (prop.kind === 254 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } // Modifiers are never allowed on properties except for 'async' on a method declaration - ts.forEach(prop.modifiers, function (mod) { - if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 147 /* MethodDeclaration */) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 147 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } } - }); + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -33146,8 +39581,8 @@ var ts; if (prop.kind === 253 /* PropertyAssignment */ || prop.kind === 254 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_21.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_21); + if (name_24.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_24); } currentKind = Property; } @@ -33163,51 +39598,46 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_21); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); if (effectiveName === undefined) { - return "continue"; + continue; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_21, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_21)); + grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } - }; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var state_3 = _loop_2(prop); - if (typeof state_3 === "object") return state_3.value; } } function checkGrammarJsxElement(node) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { - seen[name_22.text] = true; + var name_25 = jsxAttr.name; + if (!seen[name_25.text]) { + seen[name_25.text] = true; } else { - return grammarErrorOnNode(name_22, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 /* JsxExpression */ && !initializer.expression) { @@ -33264,7 +39694,7 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(accessor.flags & 128 /* Abstract */)) { + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { @@ -33415,10 +39845,27 @@ var ts; } } } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 207 /* ForInStatement */ && node.parent.parent.kind !== 208 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + // Error on equals token which immediate precedes the initializer + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -33452,7 +39899,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 193 /* OmittedExpression */) { + if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -33498,8 +39945,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); return true; } } @@ -33553,7 +40000,7 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - // A declare modifier is required for any top level .d.ts declaration except export=, export default, + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace // interfaces and imports categories: // // DeclarationElement: @@ -33571,8 +40018,8 @@ var ts; node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 236 /* ExportDeclaration */ || node.kind === 235 /* ExportAssignment */ || - (node.flags & 2 /* Ambient */) || - (node.flags & (1 /* Export */ | 512 /* Default */))) { + node.kind === 228 /* NamespaceExportDeclaration */ || + ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -33626,20 +40073,11913 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); return true; } } - var _a; + function getAmbientModules() { + var result = []; + for (var sym in globals) { + if (ambientModuleSymbolRegex.test(sym)) { + result.push(globals[sym]); + } + } + return result; + } } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); +/// +/// +/// +/* @internal */ +var ts; +(function (ts) { + ; + /** + * This map contains information about the shape of each Node in "types.ts" pertaining to how + * each node should be traversed during a transformation. + * + * Each edge corresponds to a property in a Node subtype that should be traversed when visiting + * each child. The properties are assigned in the order in which traversal should occur. + * + * We only add entries for nodes that do not have a create/update pair defined in factory.ts + * + * NOTE: This needs to be kept up to date with changes to nodes in "types.ts". Currently, this + * map is not comprehensive. Only node edges relevant to tree transformation are + * currently defined. We may extend this to be more comprehensive, and eventually + * supplant the existing `forEachChild` implementation if performance is not + * significantly impacted. + */ + var nodeEdgeTraversalMap = ts.createMap((_a = {}, + _a[139 /* QualifiedName */] = [ + { name: "left", test: ts.isEntityName }, + { name: "right", test: ts.isIdentifier } + ], + _a[143 /* Decorator */] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[177 /* TypeAssertionExpression */] = [ + { name: "type", test: ts.isTypeNode }, + { name: "expression", test: ts.isUnaryExpression } + ], + _a[195 /* AsExpression */] = [ + { name: "expression", test: ts.isExpression }, + { name: "type", test: ts.isTypeNode } + ], + _a[196 /* NonNullExpression */] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[224 /* EnumDeclaration */] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[225 /* ModuleDeclaration */] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[226 /* ModuleBlock */] = [ + { name: "statements", test: ts.isStatement } + ], + _a[229 /* ImportEqualsDeclaration */] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "moduleReference", test: ts.isModuleReference } + ], + _a[240 /* ExternalModuleReference */] = [ + { name: "expression", test: ts.isExpression, optional: true } + ], + _a[255 /* EnumMember */] = [ + { name: "name", test: ts.isPropertyName }, + { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } + ], + _a)); + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the + * `nodeEdgeTraversalMap` above will be visited. + * + * @param node The node containing the children to reduce. + * @param f The callback function + * @param initial The initial value to supply to the reduction. + */ + function reduceEachChild(node, f, initial) { + if (node === undefined) { + return initial; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + return initial; + } + // We do not yet support types. + if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + return initial; + } + var result = initial; + switch (node.kind) { + // Leaf nodes + case 198 /* SemicolonClassElement */: + case 201 /* EmptyStatement */: + case 193 /* OmittedExpression */: + case 217 /* DebuggerStatement */: + case 287 /* NotEmittedStatement */: + // No need to visit nodes with no children. + break; + // Names + case 140 /* ComputedPropertyName */: + result = reduceNode(node.expression, f, result); + break; + // Signature elements + case 142 /* Parameter */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 143 /* Decorator */: + result = reduceNode(node.expression, f, result); + break; + // Type member + case 145 /* PropertyDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 147 /* MethodDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 148 /* Constructor */: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 149 /* GetAccessor */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 150 /* SetAccessor */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + // Binding patterns + case 167 /* ObjectBindingPattern */: + case 168 /* ArrayBindingPattern */: + result = ts.reduceLeft(node.elements, f, result); + break; + case 169 /* BindingElement */: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + // Expression + case 170 /* ArrayLiteralExpression */: + result = ts.reduceLeft(node.elements, f, result); + break; + case 171 /* ObjectLiteralExpression */: + result = ts.reduceLeft(node.properties, f, result); + break; + case 172 /* PropertyAccessExpression */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.name, f, result); + break; + case 173 /* ElementAccessExpression */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.argumentExpression, f, result); + break; + case 174 /* CallExpression */: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 175 /* NewExpression */: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 176 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, f, result); + result = reduceNode(node.template, f, result); + break; + case 179 /* FunctionExpression */: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 180 /* ArrowFunction */: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 178 /* ParenthesizedExpression */: + case 181 /* DeleteExpression */: + case 182 /* TypeOfExpression */: + case 183 /* VoidExpression */: + case 184 /* AwaitExpression */: + case 190 /* YieldExpression */: + case 191 /* SpreadElementExpression */: + case 196 /* NonNullExpression */: + result = reduceNode(node.expression, f, result); + break; + case 185 /* PrefixUnaryExpression */: + case 186 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, f, result); + break; + case 187 /* BinaryExpression */: + result = reduceNode(node.left, f, result); + result = reduceNode(node.right, f, result); + break; + case 188 /* ConditionalExpression */: + result = reduceNode(node.condition, f, result); + result = reduceNode(node.whenTrue, f, result); + result = reduceNode(node.whenFalse, f, result); + break; + case 189 /* TemplateExpression */: + result = reduceNode(node.head, f, result); + result = ts.reduceLeft(node.templateSpans, f, result); + break; + case 192 /* ClassExpression */: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 194 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + break; + // Misc + case 197 /* TemplateSpan */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.literal, f, result); + break; + // Element + case 199 /* Block */: + result = ts.reduceLeft(node.statements, f, result); + break; + case 200 /* VariableStatement */: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.declarationList, f, result); + break; + case 202 /* ExpressionStatement */: + result = reduceNode(node.expression, f, result); + break; + case 203 /* IfStatement */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.thenStatement, f, result); + result = reduceNode(node.elseStatement, f, result); + break; + case 204 /* DoStatement */: + result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, f, result); + break; + case 205 /* WhileStatement */: + case 212 /* WithStatement */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 206 /* ForStatement */: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.condition, f, result); + result = reduceNode(node.incrementor, f, result); + result = reduceNode(node.statement, f, result); + break; + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 211 /* ReturnStatement */: + case 215 /* ThrowStatement */: + result = reduceNode(node.expression, f, result); + break; + case 213 /* SwitchStatement */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.caseBlock, f, result); + break; + case 214 /* LabeledStatement */: + result = reduceNode(node.label, f, result); + result = reduceNode(node.statement, f, result); + break; + case 216 /* TryStatement */: + result = reduceNode(node.tryBlock, f, result); + result = reduceNode(node.catchClause, f, result); + result = reduceNode(node.finallyBlock, f, result); + break; + case 218 /* VariableDeclaration */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 219 /* VariableDeclarationList */: + result = ts.reduceLeft(node.declarations, f, result); + break; + case 220 /* FunctionDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 221 /* ClassDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 227 /* CaseBlock */: + result = ts.reduceLeft(node.clauses, f, result); + break; + case 230 /* ImportDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.importClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 231 /* ImportClause */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.namedBindings, f, result); + break; + case 232 /* NamespaceImport */: + result = reduceNode(node.name, f, result); + break; + case 233 /* NamedImports */: + case 237 /* NamedExports */: + result = ts.reduceLeft(node.elements, f, result); + break; + case 234 /* ImportSpecifier */: + case 238 /* ExportSpecifier */: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + break; + case 235 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.expression, f, result); + break; + case 236 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.exportClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + // JSX + case 241 /* JsxElement */: + result = reduceNode(node.openingElement, f, result); + result = ts.reduceLeft(node.children, f, result); + result = reduceNode(node.closingElement, f, result); + break; + case 242 /* JsxSelfClosingElement */: + case 243 /* JsxOpeningElement */: + result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.attributes, f, result); + break; + case 245 /* JsxClosingElement */: + result = reduceNode(node.tagName, f, result); + break; + case 246 /* JsxAttribute */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 247 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, f, result); + break; + case 248 /* JsxExpression */: + result = reduceNode(node.expression, f, result); + break; + // Clauses + case 249 /* CaseClause */: + result = reduceNode(node.expression, f, result); + // fall-through + case 250 /* DefaultClause */: + result = ts.reduceLeft(node.statements, f, result); + break; + case 251 /* HeritageClause */: + result = ts.reduceLeft(node.types, f, result); + break; + case 252 /* CatchClause */: + result = reduceNode(node.variableDeclaration, f, result); + result = reduceNode(node.block, f, result); + break; + // Property assignments + case 253 /* PropertyAssignment */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 254 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.objectAssignmentInitializer, f, result); + break; + // Top-level nodes + case 256 /* SourceFile */: + result = ts.reduceLeft(node.statements, f, result); + break; + case 288 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, f, result); + break; + default: + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_1 = edgeTraversalPath; _i < edgeTraversalPath_1.length; _i++) { + var edge = edgeTraversalPath_1[_i]; + var value = node[edge.name]; + if (value !== undefined) { + result = ts.isArray(value) + ? ts.reduceLeft(value, f, result) + : f(result, value); + } + } + } + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { + if (node === undefined) { + return undefined; + } + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + if (!optional) { + Debug.failNotOptional(); + } + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + if (parenthesize !== undefined) { + visitedNode = parenthesize(visitedNode, parentNode); + } + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + function visitNodes(nodes, visitor, test, start, count, parenthesize, parentNode) { + if (nodes === undefined) { + return undefined; + } + var updated; + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*location*/ undefined, + /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); + } + // Visit each original node. + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. + updated = ts.createNodeArray(nodes.slice(0, i), /*location*/ nodes, nodes.hasTrailingComma); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + visitedNode = parenthesize + ? parenthesize(visitedNode, parentNode) + : visitedNode; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + var visitedNode = parenthesize + ? parenthesize(visited, parentNode) + : visited; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + function visitEachChild(node, visitor, context) { + if (node === undefined) { + return undefined; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + return node; + } + // We do not yet support types. + if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + return node; + } + switch (node.kind) { + case 198 /* SemicolonClassElement */: + case 201 /* EmptyStatement */: + case 193 /* OmittedExpression */: + case 217 /* DebuggerStatement */: + // No need to visit nodes with no children. + return node; + // Names + case 140 /* ComputedPropertyName */: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + // Signature elements + case 142 /* Parameter */: + return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + // Type member + case 145 /* PropertyDeclaration */: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 147 /* MethodDeclaration */: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 148 /* Constructor */: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 149 /* GetAccessor */: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 150 /* SetAccessor */: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + // Binding patterns + case 167 /* ObjectBindingPattern */: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 168 /* ArrayBindingPattern */: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 169 /* BindingElement */: + return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, /*optional*/ true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + // Expression + case 170 /* ArrayLiteralExpression */: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 171 /* ObjectLiteralExpression */: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 172 /* PropertyAccessExpression */: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 173 /* ElementAccessExpression */: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 174 /* CallExpression */: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 175 /* NewExpression */: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 176 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + case 178 /* ParenthesizedExpression */: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 179 /* FunctionExpression */: + return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 180 /* ArrowFunction */: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, /*optional*/ true), context.endLexicalEnvironment())); + case 181 /* DeleteExpression */: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 182 /* TypeOfExpression */: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 183 /* VoidExpression */: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184 /* AwaitExpression */: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 185 /* PrefixUnaryExpression */: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 186 /* PostfixUnaryExpression */: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 188 /* ConditionalExpression */: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 189 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 190 /* YieldExpression */: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 191 /* SpreadElementExpression */: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192 /* ClassExpression */: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 194 /* ExpressionWithTypeArguments */: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + // Misc + case 197 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + // Element + case 199 /* Block */: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 200 /* VariableStatement */: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 202 /* ExpressionStatement */: + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 203 /* IfStatement */: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, /*optional*/ true, liftToBlock)); + case 204 /* DoStatement */: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 205 /* WhileStatement */: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 206 /* ForStatement */: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 207 /* ForInStatement */: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 208 /* ForOfStatement */: + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 209 /* ContinueStatement */: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); + case 210 /* BreakStatement */: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); + case 211 /* ReturnStatement */: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true)); + case 212 /* WithStatement */: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 213 /* SwitchStatement */: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 214 /* LabeledStatement */: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 215 /* ThrowStatement */: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 216 /* TryStatement */: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, /*optional*/ true), visitNode(node.finallyBlock, visitor, ts.isBlock, /*optional*/ true)); + case 218 /* VariableDeclaration */: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 219 /* VariableDeclarationList */: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 220 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 221 /* ClassDeclaration */: + return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 227 /* CaseBlock */: + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 230 /* ImportDeclaration */: + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 231 /* ImportClause */: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true)); + case 232 /* NamespaceImport */: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 233 /* NamedImports */: + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 234 /* ImportSpecifier */: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); + case 235 /* ExportAssignment */: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 236 /* ExportDeclaration */: + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, /*optional*/ true)); + case 237 /* NamedExports */: + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + case 238 /* ExportSpecifier */: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); + // JSX + case 241 /* JsxElement */: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 242 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 243 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 245 /* JsxClosingElement */: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 246 /* JsxAttribute */: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 247 /* JsxSpreadAttribute */: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 248 /* JsxExpression */: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + // Clauses + case 249 /* CaseClause */: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + case 250 /* DefaultClause */: + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 251 /* HeritageClause */: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 252 /* CatchClause */: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + // Property assignments + case 253 /* PropertyAssignment */: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 254 /* ShorthandPropertyAssignment */: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + // Top-level nodes + case 256 /* SourceFile */: + context.startLexicalEnvironment(); + return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); + // Transformation nodes + case 288 /* PartiallyEmittedExpression */: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + default: + var updated = void 0; + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_2 = edgeTraversalPath; _i < edgeTraversalPath_2.length; _i++) { + var edge = edgeTraversalPath_2[_i]; + var value = node[edge.name]; + if (value !== undefined) { + var visited = ts.isArray(value) + ? visitNodes(value, visitor, edge.test, 0, value.length, edge.parenthesize, node) + : visitNode(value, visitor, edge.test, edge.optional, edge.lift, edge.parenthesize, node); + if (updated !== undefined || visited !== value) { + if (updated === undefined) { + updated = ts.getMutableClone(node); + } + if (visited !== value) { + updated[edge.name] = visited; + } + } + } + } + } + return updated ? ts.updateNode(updated, node) : node; + } + // return node; + } + ts.visitEachChild = visitEachChild; + function mergeFunctionBodyLexicalEnvironment(body, declarations) { + if (body && declarations !== undefined && declarations.length > 0) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.createNodeArray(ts.concatenate(body.statements, declarations), body.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([ts.createReturn(body, /*location*/ body)].concat(declarations), body), + /*location*/ body, + /*multiLine*/ true); + } + } + return body; + } + ts.mergeFunctionBodyLexicalEnvironment = mergeFunctionBodyLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ + function extractSingleNode(nodes) { + Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0 /* None */; + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + } + /** + * Aggregates the transform flags for the subtree of a node. + */ + function aggregateTransformFlagsForSubtree(node) { + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || ts.isTypeNode(node)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0 /* None */); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ + function aggregateTransformFlagsForChildNode(transformFlags, child) { + return transformFlags | aggregateTransformFlagsForNode(child); + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 174 /* CallExpression */: + case 175 /* NewExpression */: + case 170 /* ArrayLiteralExpression */: + return 537133909 /* ArrayLiteralOrCallOrNewExcludes */; + case 225 /* ModuleDeclaration */: + return 546335573 /* ModuleExcludes */; + case 142 /* Parameter */: + return 538968917 /* ParameterExcludes */; + case 180 /* ArrowFunction */: + return 550710101 /* ArrowFunctionExcludes */; + case 179 /* FunctionExpression */: + case 220 /* FunctionDeclaration */: + return 550726485 /* FunctionExcludes */; + case 219 /* VariableDeclarationList */: + return 538968917 /* VariableDeclarationListExcludes */; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + return 537590613 /* ClassExcludes */; + case 148 /* Constructor */: + return 550593365 /* ConstructorExcludes */; + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return 550593365 /* MethodOrAccessorExcludes */; + case 117 /* AnyKeyword */: + case 130 /* NumberKeyword */: + case 127 /* NeverKeyword */: + case 132 /* StringKeyword */: + case 120 /* BooleanKeyword */: + case 133 /* SymbolKeyword */: + case 103 /* VoidKeyword */: + case 141 /* TypeParameter */: + case 144 /* PropertySignature */: + case 146 /* MethodSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 153 /* IndexSignature */: + case 222 /* InterfaceDeclaration */: + case 223 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 171 /* ObjectLiteralExpression */: + return 537430869 /* ObjectLiteralExcludes */; + default: + return 536871765 /* NodeExcludes */; + } + } + var Debug; + (function (Debug) { + Debug.failNotOptional = Debug.shouldAssert(1 /* Normal */) + ? function (message) { return Debug.assert(false, message || "Node not optional."); } + : function (message) { }; + Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + : function (node, message) { }; + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : function (node, test, message) { }; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + })(Debug = ts.Debug || (ts.Debug = {})); + var _a; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + /** + * Flattens a destructuring assignment expression. + * + * @param root The destructuring assignment expression. + * @param needsValue Indicates whether the value from the right-hand-side of the + * destructuring assignment is needed as part of a larger expression. + * @param recordTempVariable A callback used to record new temporary variables. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { + if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + var right = node.right; + if (ts.isDestructuringAssignment(right)) { + return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); + } + else { + return node.right; + } + } + var location = node; + var value = node.right; + var expressions = []; + if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignmen) is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); + if (needsValue) { + expressions.push(value); + } + var expression = ts.inlineExpressions(expressions); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location) { + var expression = ts.createAssignment(name, value, location); + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(expression); + expressions.push(expression); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + /** + * Flattens binding patterns in a parameter declaration. + * + * @param node The ParameterDeclaration to flatten. + * @param value The rhs value for the binding pattern. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenParameterDestructuring(context, node, value, visitor) { + var declarations = []; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location) { + var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(declaration); + declarations.push(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(/*recordTempVariable*/ undefined); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenParameterDestructuring = flattenParameterDestructuring; + /** + * Flattens binding patterns in a variable declaration. + * + * @param node The VariableDeclaration to flatten. + * @param value An optional rhs value for the binding pattern. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { + var declarations = []; + var pendingAssignments; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location, original) { + if (pendingAssignments) { + pendingAssignments.push(value); + value = ts.inlineExpressions(pendingAssignments); + pendingAssignments = undefined; + } + var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); + declaration.original = original; + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + declarations.push(declaration); + ts.aggregateTransformFlags(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + if (recordTempVariable) { + var assignment = ts.createAssignment(name, value, location); + if (pendingAssignments) { + pendingAssignments.push(assignment); + } + else { + pendingAssignments = [assignment]; + } + } + else { + emitAssignment(name, value, location, /*original*/ undefined); + } + return name; + } + } + ts.flattenVariableDestructuring = flattenVariableDestructuring; + /** + * Flattens binding patterns in a variable declaration and transforms them into an expression. + * + * @param node The VariableDeclaration to flatten. + * @param recordTempVariable A callback used to record new temporary variables. + * @param nameSubstitution An optional callback used to substitute binding names. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { + var pendingAssignments = []; + flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor); + var expression = ts.inlineExpressions(pendingAssignments); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location, original) { + var left = nameSubstitution && nameSubstitution(name) || name; + emitPendingAssignment(left, value, location, original); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitPendingAssignment(name, value, location, /*original*/ undefined); + return name; + } + function emitPendingAssignment(name, value, location, original) { + var expression = ts.createAssignment(name, value, location); + expression.original = original; + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + pendingAssignments.push(expression); + return expression; + } + } + ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; + function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { + if (value && visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + if (ts.isBinaryExpression(root)) { + emitDestructuringAssignment(root.left, value, location); + } + else { + emitBindingElement(root, value); + } + function emitDestructuringAssignment(bindingTarget, value, location) { + // When emitting target = value use source map node to highlight, including any temporary assignments needed for this + var target; + if (ts.isShorthandPropertyAssignment(bindingTarget)) { + var initializer = visitor + ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) + : bindingTarget.objectAssignmentInitializer; + if (initializer) { + value = createDefaultValueCheck(value, initializer, location); + } + target = bindingTarget.name; + } + else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56 /* EqualsToken */) { + var initializer = visitor + ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) + : bindingTarget.right; + value = createDefaultValueCheck(value, initializer, location); + target = bindingTarget.left; + } + else { + target = bindingTarget; + } + if (target.kind === 171 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value, location); + } + else if (target.kind === 170 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value, location); + } + else { + var name_26 = ts.getMutableClone(target); + context.setSourceMapRange(name_26, target); + context.setCommentRange(name_26, target); + emitAssignment(name_26, value, location, /*original*/ undefined); + } + } + function emitObjectLiteralAssignment(target, value, location) { + var properties = target.properties; + if (properties.length !== 1) { + // For anything but a single element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. + // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + if (p.kind === 253 /* PropertyAssignment */ || p.kind === 254 /* ShorthandPropertyAssignment */) { + var propName = p.name; + var target_1 = p.kind === 254 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + // Assignment for target = value.propName should highligh whole property, hence use p as source map node + emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); + } + } + } + function emitArrayLiteralAssignment(target, value, location) { + var elements = target.elements; + var numElements = elements.length; + if (numElements !== 1) { + // For anything but a single element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. + // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var e = elements[i]; + if (e.kind !== 193 /* OmittedExpression */) { + // Assignment for target = value.propName should highligh whole property, hence use e as source map node + if (e.kind !== 191 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); + } + else if (i === numElements - 1) { + emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); + } + } + } + } + function emitBindingElement(target, value) { + // Any temporary assignments needed to emit target = value should point to target + var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + if (initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = ts.createVoidZero(); + } + var name = target.name; + if (ts.isBindingPattern(name)) { + var elements = name.elements; + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (ts.isOmittedExpression(element)) { + continue; + } + else if (name.kind === 167 /* ObjectBindingPattern */) { + // Rewrite element to a declaration with an initializer that fetches property + var propName = element.propertyName || element.name; + emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); + } + else { + if (!element.dotDotDotToken) { + // Rewrite element to a declaration that accesses array element at index i + emitBindingElement(element, ts.createElementAccess(value, i)); + } + else if (i === numElements - 1) { + emitBindingElement(element, ts.createArraySlice(value, i)); + } + } + } + } + else { + emitAssignment(name, value, target, target); + } + } + function createDefaultValueCheck(value, defaultValue, location) { + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); + return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53 /* QuestionToken */), defaultValue, ts.createToken(54 /* ColonToken */), value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @param expression The right-hand expression that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(expression, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)); + } + else if (ts.isLiteralExpression(propertyName)) { + var clone_2 = ts.getSynthesizedClone(propertyName); + clone_2.text = ts.unescapeIdentifier(clone_2.text); + return ts.createElementAccess(expression, clone_2); + } + else { + if (ts.isGeneratedIdentifier(propertyName)) { + var clone_3 = ts.getSynthesizedClone(propertyName); + clone_3.text = ts.unescapeIdentifier(clone_3.text); + return ts.createPropertyAccess(expression, clone_3); + } + else { + return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + } + } + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + * @param emitTempVariableAssignment A callback used to emit a temporary variable. + * @param visitor An optional callback used to visit the value. + */ + function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + if (visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + return emitTempVariableAssignment(value, location); + } + } +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ + var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /** Enables substitutions for async methods with `super` calls. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["AsyncMethodsWithSuper"] = 4] = "AsyncMethodsWithSuper"; + /* Enables substitutions for unqualified enum members */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + function transformTypeScript(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentScope; + var currentSourceFileExternalHelpersModuleName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + var applicableSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var currentSuperContainer; + return transformSourceFile; + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + return ts.visitNode(node, visitor, ts.isSourceFile); + } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ + function saveStateAndInvoke(node, f) { + // Save state + var savedCurrentScope = currentScope; + // Handle state changes before visiting a node. + onBeforeVisitNode(node); + var visited = f(node); + // Restore state + currentScope = savedCurrentScope; + return visited; + } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ + function visitorWorker(node) { + if (node.kind === 256 /* SourceFile */) { + return visitSourceFile(node); + } + else if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitorWorker(node) { + if (node.kind === 236 /* ExportDeclaration */ || + node.kind === 230 /* ImportDeclaration */ || + node.kind === 231 /* ImportClause */ || + (node.kind === 229 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 240 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace + return undefined; + } + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitorWorker(node) { + switch (node.kind) { + case 148 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. + return undefined; + case 145 /* PropertyDeclaration */: + case 153 /* IndexSignature */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 147 /* MethodDeclaration */: + // Fallback to the default visit behavior. + return visitorWorker(node); + case 198 /* SemicolonClassElement */: + return node; + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ + function visitTypeScript(node) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 82 /* ExportKeyword */: + case 77 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. + return currentNamespace ? undefined : node; + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 115 /* AbstractKeyword */: + case 118 /* AsyncKeyword */: + case 74 /* ConstKeyword */: + case 122 /* DeclareKeyword */: + case 128 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 160 /* ArrayType */: + case 161 /* TupleType */: + case 159 /* TypeLiteral */: + case 154 /* TypePredicate */: + case 141 /* TypeParameter */: + case 117 /* AnyKeyword */: + case 120 /* BooleanKeyword */: + case 132 /* StringKeyword */: + case 130 /* NumberKeyword */: + case 127 /* NeverKeyword */: + case 103 /* VoidKeyword */: + case 133 /* SymbolKeyword */: + case 157 /* ConstructorType */: + case 156 /* FunctionType */: + case 158 /* TypeQuery */: + case 155 /* TypeReference */: + case 162 /* UnionType */: + case 163 /* IntersectionType */: + case 164 /* ParenthesizedType */: + case 165 /* ThisType */: + case 166 /* LiteralType */: + // TypeScript type nodes are elided. + case 153 /* IndexSignature */: + // TypeScript index signatures are elided. + case 143 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 223 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + case 145 /* PropertyDeclaration */: + // TypeScript property declarations are elided. + case 148 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + return undefined; + case 222 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + case 221 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + // - async methods + return visitClassDeclaration(node); + case 192 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + // - async methods + return visitClassExpression(node); + case 251 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause + return visitHeritageClause(node); + case 194 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. + return visitExpressionWithTypeArguments(node); + case 147 /* MethodDeclaration */: + // TypeScript method declarations may be 'async', and may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node); + case 149 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node); + case 150 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitSetAccessor(node); + case 220 /* FunctionDeclaration */: + // TypeScript function declarations may be 'async' + return visitFunctionDeclaration(node); + case 179 /* FunctionExpression */: + // TypeScript function expressions may be 'async' + return visitFunctionExpression(node); + case 180 /* ArrowFunction */: + // TypeScript arrow functions may be 'async' + return visitArrowFunction(node); + case 142 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters + return visitParameter(node); + case 178 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression + return visitParenthesizedExpression(node); + case 177 /* TypeAssertionExpression */: + case 195 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node); + case 196 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. + return visitNonNullExpression(node); + case 224 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. + return visitEnumDeclaration(node); + case 184 /* AwaitExpression */: + // TypeScript 'await' expressions must be transformed. + return visitAwaitExpression(node); + case 200 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. + return visitVariableStatement(node); + case 225 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. + return visitModuleDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. + return visitImportEqualsDeclaration(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 256 /* SourceFile */: + case 227 /* CaseBlock */: + case 226 /* ModuleBlock */: + case 199 /* Block */: + currentScope = node; + break; + } + } + function visitSourceFile(node) { + currentSourceFile = node; + // If the source file requires any helpers and is an external module, and + // the importHelpers compiler option is enabled, emit a synthesized import + // statement for the helpers library. + if (node.flags & 31744 /* EmitHelperFlags */ + && compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); + var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); + var externalHelpersModuleImport = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + externalHelpersModuleImport.parent = node; + externalHelpersModuleImport.flags &= ~8 /* Synthesized */; + statements.push(externalHelpersModuleImport); + currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + currentSourceFileExternalHelpersModuleName = undefined; + node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + node.externalHelpersModuleName = externalHelpersModuleName; + } + else { + node = ts.visitEachChild(node, visitor, context); + } + setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); + return node; + } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ + function visitClassDeclaration(node) { + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; + var isDecoratedClass = shouldEmitDecorateCallForClass(node); + var classAlias; + // emit name if + // - node has a name + // - node has static initializers + // + var name = node.name; + if (!name && staticProperties.length > 0) { + name = ts.getGeneratedNameForNode(node); + } + var statements = []; + if (!isDecoratedClass) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), + /*location*/ node); + ts.setOriginalNode(classDeclaration, node); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + if (staticProperties.length > 0) { + setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); + } + statements.push(classDeclaration); + } + else { + classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); + } + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (staticProperties.length) { + addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, /*noSourceMaps*/ true)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); + addConstructorDecorationStatement(statements, node, classAlias); + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (isNamespaceExport(node)) { + addExportMemberAssignment(statements, node); + } + else if (isDecoratedClass) { + if (isDefaultExternalModuleExport(node)) { + statements.push(ts.createExportAssignment( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*isExportEquals*/ false, getLocalName(node))); + } + else if (isNamedExternalModuleExport(node)) { + statements.push(createExternalModuleExport(name)); + } + } + return statements; + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param hasExtendsClause A value indicating whether + */ + function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | let C = C_1; + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C_1 = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | let C = C_1; + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C_1 = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | let C = C_1; + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + var location = ts.moveRangePastDecorators(node); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var classExpression = ts.setOriginalNode(ts.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), + /*location*/ location), node); + if (!name) { + name = ts.getGeneratedNameForNode(node); + } + // Record an alias to avoid class double-binding. + var classAlias; + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + } + var declaredName = getDeclarationName(node, /*allowComments*/ true); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var transformedClassExpression = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(classAlias || declaredName, + /*type*/ undefined, classExpression) + ]), + /*location*/ location); + setCommentRange(transformedClassExpression, node); + statements.push(ts.setOriginalNode( + /*node*/ transformedClassExpression, + /*original*/ node)); + if (classAlias) { + // We emit the class alias as a `let` declaration here so that it has the same + // TDZ as the class. + // let ${declaredName} = ${decoratedClassAlias} + statements.push(ts.setOriginalNode(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(declaredName, + /*type*/ undefined, classAlias) + ]), + /*location*/ location), + /*original*/ node)); + } + return classAlias; + } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ + function visitClassExpression(node) { + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, heritageClauses !== undefined); + var classExpression = ts.setOriginalNode(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members, + /*location*/ node), node); + if (staticProperties.length > 0) { + var expressions = []; + var temp = ts.createTempVariable(hoistVariableDeclaration); + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + // record an alias as the class name is not in scope for statics. + enableSubstitutionForClassAliases(); + classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + } + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + return classExpression; + } + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + */ + function transformClassMembers(node, hasExtendsClause) { + var members = []; + var constructor = transformConstructor(node, hasExtendsClause); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.createNodeArray(members, /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + */ + function transformConstructor(node, hasExtendsClause) { + // Check if we have property assignment inside class declaration. + // If there is a 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 + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = node.transformFlags & 131072 /* ContainsParameterPropertyAssignments */; + var constructor = ts.getFirstConstructorWithBody(node); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body, + /*location*/ constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + */ + function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". + return constructor + ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) + : []; + } + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param parameters The transformed parameters for the constructor. + */ + function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + var statements = []; + var indexOfFirstStatement = 0; + // The body of a constructor is a new lexical environment + startLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (hasExtendsClause) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); + addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + // End the lexical environment. + ts.addRange(statements, endLexicalEnvironment()); + return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, + /*location*/ constructor ? constructor.body.statements : node.members), + /*location*/ constructor ? constructor.body : undefined), true); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + // add prologue directives to the list (if any) + var index = ts.addPrologueDirectives(result, statements, /*ensureUseStrict*/ false, visitor); + if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit + return index; + } + var statement = statements[index]; + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) + && ts.isIdentifier(parameter.name); + } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + var localName = ts.getMutableClone(name); + setNodeEmitFlags(localName, 49152 /* NoComments */); + return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, + /*location*/ node.name), localName), + /*location*/ ts.moveRangePos(node, -1))); + } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ true); + } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ + function isInitializedProperty(member, isStatic) { + return member.kind === 145 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) + && member.initializer !== undefined; + } + /** + * Generates assignment statements for property initializers. + * + * @param node The class node. + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function addInitializedPropertyStatements(statements, node, properties, receiver) { + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var property = properties_7[_i]; + var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); + setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + setCommentRange(statement, property); + statements.push(statement); + } + } + /** + * Generates assignment expressions for property initializers. + * + * @param node The class node. + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function generateInitializedPropertyExpressions(node, properties, receiver) { + var expressions = []; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var expression = transformInitializedProperty(node, property, receiver); + expression.startsOnNewLine = true; + setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + setCommentRange(expression, property); + expressions.push(expression); + } + return expressions; + } + /** + * Transforms a property initializer into an assignment statement. + * + * @param node The class containing the property. + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ + function transformInitializedProperty(node, property, receiver) { + var propertyName = visitPropertyNameOfClassElement(property); + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); + return ts.createAssignment(memberAccess, initializer); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member) { + return isDecoratedClassElement(member, /*isStatic*/ true); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member) { + return isDecoratedClassElement(member, /*isStatic*/ false); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic) { + return ts.nodeOrChildIsDecorated(member) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return getAllDecoratorsOfAccessors(node, member); + case 147 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 145 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + if (accessor !== firstAccessor) { + return undefined; + } + var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(node, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, decoratorExpressions); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", undefined); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", undefined); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 145 /* PropertyDeclaration */ + ? ts.createVoidZero() + : ts.createNull() + : undefined; + var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + setNodeEmitFlags(helper, 49152 /* NoComments */); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { + var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + if (expression) { + statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node, decoratedClassAlias) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the class: + // + // @dec + // class C { + // } + // + // The emit for the class is: + // + // C = C_1 = __decorate([dec], C); + // + if (decoratedClassAlias) { + var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); + var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152 /* NoComments */); + return result; + } + else { + var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152 /* NoComments */); + return result; + } + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + setNodeEmitFlags(helper, 49152 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ + function addTypeMetadata(node, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, decoratorExpressions); + } + else { + addOldTypeMetadata(node, decoratorExpressions); + } + } + function addOldTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeParameterTypesOfNode(node)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); + } + } + } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 145 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddReturnTypeMetadata(node) { + return node.kind === 147 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddParamTypesMetadata(node) { + var kind = node.kind; + return kind === 221 /* ClassDeclaration */ + || kind === 192 /* ClassExpression */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */; + } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 145 /* PropertyDeclaration */: + case 142 /* Parameter */: + case 149 /* GetAccessor */: + return serializeTypeNode(node.type); + case 150 /* SetAccessor */: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 147 /* MethodDeclaration */: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 160 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 155 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ + function serializeParameterTypesOfNode(node) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = valueDeclaration.parameters; + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunctionLike(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 103 /* VoidKeyword */: + return ts.createVoidZero(); + case 164 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 156 /* FunctionType */: + case 157 /* ConstructorType */: + return ts.createIdentifier("Function"); + case 160 /* ArrayType */: + case 161 /* TupleType */: + return ts.createIdentifier("Array"); + case 154 /* TypePredicate */: + case 120 /* BooleanKeyword */: + return ts.createIdentifier("Boolean"); + case 132 /* StringKeyword */: + return ts.createIdentifier("String"); + case 166 /* LiteralType */: + switch (node.literal.kind) { + case 9 /* StringLiteral */: + return ts.createIdentifier("String"); + case 8 /* NumericLiteral */: + return ts.createIdentifier("Number"); + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return ts.createIdentifier("Boolean"); + default: + ts.Debug.failBadSyntaxKind(node.literal); + break; + } + break; + case 130 /* NumberKeyword */: + return ts.createIdentifier("Number"); + case 133 /* SymbolKeyword */: + return languageVersion < 2 /* ES6 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 155 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 158 /* TypeQuery */: + case 159 /* TypeLiteral */: + case 162 /* UnionType */: + case 163 /* IntersectionType */: + case 117 /* AnyKeyword */: + case 165 /* ThisType */: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + return ts.createIdentifier("Object"); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + case ts.TypeReferenceSerializationKind.Unknown: + var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 /* ES6 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + default: + return ts.createIdentifier("Object"); + } + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * entity name at runtime. + */ + function serializeEntityNameAsExpression(node, useFallback) { + switch (node.kind) { + case 69 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name_27 = ts.getMutableClone(node); + name_27.flags &= ~8 /* Synthesized */; + name_27.original = undefined; + name_27.parent = currentScope; + if (useFallback) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_27), ts.createLiteral("undefined")), name_27); + } + return name_27; + case 139 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node, useFallback); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ + function serializeQualifiedNameAsExpression(node, useFallback) { + var left; + if (node.left.kind === 69 /* Identifier */) { + left = serializeEntityNameAsExpression(node.left, useFallback); + } + else if (useFallback) { + var temp = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); + } + else { + left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); + } + return ts.createPropertyAccess(left, node.right); + } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53 /* QuestionToken */), ts.createIdentifier("Symbol"), ts.createToken(54 /* ColonToken */), ts.createIdentifier("Object")); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(name.text); + } + else { + return ts.getSynthesizedClone(name); + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + if (member.decorators) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + expression = ts.createAssignment(generatedName, expression); + } + return ts.setOriginalNode(ts.createComputedPropertyName(expression, /*location*/ name), name); + } + else { + return name; + } + } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ + function visitHeritageClause(node) { + if (node.token === 83 /* ExtendsKeyword */) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.createHeritageClause(83 /* ExtendsKeyword */, types, node); + } + return undefined; + } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ + function visitExpressionWithTypeArguments(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createExpressionWithTypeArguments( + /*typeArguments*/ undefined, expression, node); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, async, public, private, protected, or readonly + * - The node has both a decorator and a computed property name + * + * @param node The method node. + */ + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var method = ts.createMethod( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(method, node); + setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(method, node); + return method; + } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has both a decorator and a computed property name + * + * @param node The get accessor node. + */ + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createGetAccessor( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), + /*location*/ node); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has both a decorator and a computed property name + * + * @param node The set accessor node. + */ + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createSetAccessor( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), + /*location*/ node); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked async + * - The node is exported from a TypeScript namespace + * + * @param node The function node. + */ + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var func = ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node); + ts.setOriginalNode(func, node); + if (isNamespaceExport(node)) { + var statements = [func]; + addExportMemberAssignment(statements, node); + return statements; + } + return func; + } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The function expression node. + */ + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + var func = ts.createFunctionExpression(node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node); + ts.setOriginalNode(func, node); + return func; + } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node is marked async + */ + function visitArrowFunction(node) { + var func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, node.equalsGreaterThanToken, transformConciseBody(node), + /*location*/ node); + ts.setOriginalNode(func, node); + return func; + } + function transformFunctionBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformFunctionBodyWorker(node.body); + } + function transformFunctionBodyWorker(body, start) { + if (start === void 0) { start = 0; } + var savedCurrentScope = currentScope; + currentScope = body; + startLexicalEnvironment(); + var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); + var visited = ts.updateBlock(body, statements); + var declarations = endLexicalEnvironment(); + currentScope = savedCurrentScope; + return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + } + function transformConciseBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false); + } + function transformConciseBodyWorker(body, forceBlockFunctionBody) { + if (ts.isBlock(body)) { + return transformFunctionBodyWorker(body); + } + else { + startLexicalEnvironment(); + var visited = ts.visitNode(body, visitor, ts.isConciseBody); + var declarations = endLexicalEnvironment(); + var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + if (forceBlockFunctionBody && !ts.isBlock(merged)) { + return ts.createBlock([ + ts.createReturn(merged) + ]); + } + else { + return merged; + } + } + } + function getPromiseConstructor(type) { + var typeName = ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function transformAsyncFunctionBody(node) { + var promiseConstructor = languageVersion < 2 /* ES6 */ ? getPromiseConstructor(node.type) : undefined; + var isArrowFunction = node.kind === 180 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + var block = ts.createBlock(statements, /*location*/ node.body, /*multiLine*/ true); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= 2 /* ES6 */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 4 /* EmitSuperHelper */); + } + } + return block; + } + else { + return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)); + } + } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ + function visitParameter(node) { + if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + return undefined; + } + var parameter = ts.createParameterDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), + /*location*/ ts.moveRangePastModifiers(node)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setOriginalNode(parameter, node); + setCommentRange(parameter, node); + setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + return parameter; + } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ + function visitVariableStatement(node) { + if (isNamespaceExport(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + // elide statement if there are no initialized variables. + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), + /*location*/ node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + } + else { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), + /*location*/ node); + } + } + /** + * Visits an await expression. + * + * This function will be called any time a TypeScript await expression is encountered. + * + * @param node The await expression node. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node), node); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ + function shouldEmitEnumDeclaration(node) { + return !ts.isConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + function shouldEmitVarForEnumDeclaration(node) { + return !ts.hasModifier(node, 1 /* Export */) + || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + } + /* + * Adds a trailing VariableStatement for an enum or module declaration. + */ + function addVarForEnumExportedFromNamespace(statements, node) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), + /*type*/ undefined, getExportName(node))]); + setSourceMapRange(statement, node); + statements.push(statement); + } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 64 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. + if (shouldEmitVarForEnumDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the enum. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = getExportName(node); + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), + /*location*/ node); + ts.setOriginalNode(enumStatement, node); + setNodeEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + if (isNamespaceExport(node)) { + addVarForEnumExportedFromNamespace(statements, node); + } + return statements; + } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, ts.map(node.members, transformEnumMember)); + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), + /*location*/ undefined, + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ + function transformEnumMember(member) { + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + return ts.createStatement(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name, + /*location*/ member), + /*location*/ member); + } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + function isModuleMergedWithES6Class(node) { + return languageVersion === 2 /* ES6 */ + && ts.isMergedWithClass(node); + } + function isES6ExportedDeclaration(node) { + return isExternalModuleExport(node) + && moduleKind === ts.ModuleKind.ES6; + } + function shouldEmitVarForModuleDeclaration(node) { + return !isModuleMergedWithES6Class(node) + && (!isES6ExportedDeclaration(node) + || ts.isFirstDeclarationOfKind(node, node.kind)); + } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ + function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. + var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) + ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) + : undefined, [ + ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]); + ts.setOriginalNode(statement, /*original*/ node); + // Adjust the source map emit to match the old emitter. + if (node.kind === 224 /* EnumDeclaration */) { + setSourceMapRange(statement.declarationList, node); + } + else { + setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + setCommentRange(statement, node); + setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); + statements.push(statement); + } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 64 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. + if (shouldEmitVarForModuleDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the namespace. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = getExportName(node); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (ts.hasModifier(node, 1 /* Export */) && !isES6ExportedDeclaration(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = getLocalName(node); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg]), + /*location*/ node); + ts.setOriginalNode(moduleStatement, node); + setNodeEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + return statements; + } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 226 /* ModuleBlock */) { + ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + var block = ts.createBlock(ts.createNodeArray(statements, + /*location*/ statementsLocation), + /*location*/ blockLocation, + /*multiLine*/ true); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 226 /* ModuleBlock */) { + setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ + function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + return ts.visitEachChild(node, visitor, context); + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference) + ]), node), node); + } + else { + // exports.${name} = ${moduleReference}; + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ + function isNamespaceExport(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512 /* Default */); + } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512 /* Default */); + } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ + function expressionToStatement(expression) { + return ts.createStatement(expression, /*location*/ undefined); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); + setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var statement = ts.createStatement(expression); + setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue), location); + } + function createExternalModuleExport(exportName) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createNamedExports([ + ts.createExportSpecifier(exportName) + ])); + } + function getNamespaceMemberName(name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), /*location*/ name); + var emitFlags; + if (!allowComments) { + emitFlags |= 49152 /* NoComments */; + } + if (!allowSourceMaps) { + emitFlags |= 1536 /* NoSourceMap */; + } + if (emitFlags) { + setNodeEmitFlags(qualifiedName, emitFlags); + } + return qualifiedName; + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return getNamespaceMemberName(name, /*allowComments*/ false, /*allowSourceMaps*/ true); + } + /** + * Gets the declaration name used inside of a namespace or enum. + */ + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + setSourceMapRange(name, node.name); + return name; + } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + /** + * Gets the local name for a declaration for use in expressions. + * + * A local name will *never* be prefixed with an module or namespace export modifier like + * "exports.". + * + * @param node The declaration. + * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. + * @param allowComments A value indicating whether comments may be emitted for the name. + */ + function getLocalName(node, noSourceMaps, allowComments) { + return getDeclarationName(node, allowComments, !noSourceMaps, 262144 /* LocalName */); + } + /** + * Gets the export name for a declaration for use in expressions. + * + * An export name will *always* be prefixed with an module or namespace export modifier + * like "exports." if one is required. + * + * @param node The declaration. + * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. + * @param allowComments A value indicating whether comments may be emitted for the name. + */ + function getExportName(node, noSourceMaps, allowComments) { + if (isNamespaceExport(node)) { + return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); + } + return getDeclarationName(node, allowComments, !noSourceMaps, 131072 /* ExportName */); + } + /** + * Gets the name for a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + * @param emitFlags Additional NodeEmitFlags to specify for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name) { + var name_28 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536 /* NoSourceMap */; + } + if (!allowComments) { + emitFlags |= 49152 /* NoComments */; + } + if (emitFlags) { + setNodeEmitFlags(name_28, emitFlags); + } + return name_28; + } + else { + return ts.getGeneratedNameForNode(node); + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(69 /* Identifier */); + } + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 4 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(174 /* CallExpression */); + context.enableSubstitution(172 /* PropertyAccessExpression */); + context.enableSubstitution(173 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(221 /* ClassDeclaration */); + context.enableEmitNotification(147 /* MethodDeclaration */); + context.enableEmitNotification(149 /* GetAccessor */); + context.enableEmitNotification(150 /* SetAccessor */); + context.enableEmitNotification(148 /* Constructor */); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(69 /* Identifier */); + // Keep track of class aliases. + classAliases = ts.createMap(); + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(254 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(225 /* ModuleDeclaration */); + } + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 221 /* ClassDeclaration */ + || kind === 148 /* Constructor */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */; + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 225 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 224 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(node, emit) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSuperContainer = currentSuperContainer; + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + currentSuperContainer = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(node, emit); + applicableSubstitutions = savedApplicableSubstitutions; + currentSuperContainer = savedCurrentSuperContainer; + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name_29 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_29); + if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + } + return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + } + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { + switch (node.kind) { + case 174 /* CallExpression */: + return substituteCallExpression(node); + case 172 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; + if (classAlias) { + var clone_4 = ts.getSynthesizedClone(classAlias); + setSourceMapRange(clone_4, node); + setCommentRange(clone_4, node); + return clone_4; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. + if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 225 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 224 /* EnumDeclaration */); + if (substitute) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, /*location*/ node); + } + } + } + return undefined; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 95 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 95 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + } + } + ts.transformTypeScript = transformTypeScript; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES6Module(context) { + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 230 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 231 /* ImportClause */: + return visitImportClause(node); + case 233 /* NamedImports */: + case 232 /* NamespaceImport */: + return visitNamedBindings(node); + case 234 /* ImportSpecifier */: + return visitImportSpecifier(node); + case 235 /* ExportAssignment */: + return visitExportAssignment(node); + case 236 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 237 /* NamedExports */: + return visitNamedExports(node); + case 238 /* ExportSpecifier */: + return visitExportSpecifier(node); + } + return node; + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; // do not emit export equals for ES6 + } + var original = ts.getOriginalNode(node); + return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true); + if (node.exportClause === newExportClause) { + return node; + } + return newExportClause + ? ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, newExportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); + if (node.elements === newExports) { + return node; + } + return newExports.length ? ts.createNamedExports(newExports) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + function visitImportEqualsDeclaration(node) { + return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitImportDeclaration(node) { + if (node.importClause) { + var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); + if (!newImportClause.name && !newImportClause.namedBindings) { + return undefined; + } + else if (newImportClause !== node.importClause) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, newImportClause, node.moduleSpecifier); + } + } + return node; + } + function visitImportClause(node) { + var newDefaultImport = node.name; + if (!resolver.isReferencedAliasDeclaration(node)) { + newDefaultImport = undefined; + } + var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true); + return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings + ? ts.createImportClause(newDefaultImport, newNamedBindings) + : node; + } + function visitNamedBindings(node) { + if (node.kind === 232 /* NamespaceImport */) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); + if (!newNamedImportElements || newNamedImportElements.length == 0) { + return undefined; + } + if (newNamedImportElements === node.elements) { + return node; + } + return ts.createNamedImports(newNamedImportElements); + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + } + ts.transformES6Module = transformES6Module; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(187 /* BinaryExpression */); + context.enableSubstitution(185 /* PrefixUnaryExpression */); + context.enableSubstitution(186 /* PostfixUnaryExpression */); + context.enableEmitNotification(256 /* SourceFile */); + var exportFunctionForFileMap = []; + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var hasExportStarsToExportValues; + var exportFunctionForFile; + var contextObjectForFile; + var exportedLocalNames; + var exportedFunctionDeclarations; + var enclosingBlockScopedContainer; + var currentParent; + var currentNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + currentNode = node; + // Perform the transformation. + var updated = transformSystemModuleWorker(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + exportedLocalNames = undefined; + exportedFunctionDeclarations = undefined; + return updated; + } + return node; + } + function transformSystemModuleWorker(node) { + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + ts.Debug.assert(!exportFunctionForFile); + // Collect information about the external module and dependency groups. + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunctionForFile = ts.createUniqueName("exports"); + contextObjectForFile = ts.createUniqueName("context"); + exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; + var dependencyGroups = collectDependencyGroups(externalImports); + var statements = []; + // Add the body of the module. + addSystemModuleBody(statements, node, dependencyGroups); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); + var body = ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(exportFunctionForFile), + ts.createParameter(contextObjectForFile) + ], + /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, body] + : [dependencies, body])) + ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); + var _a; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param statements The output statements for the module body. + * @param node The source file for the module. + * @param statementOffset The offset at which to begin visiting the statements of the SourceFile. + */ + function addSystemModuleBody(statements, node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // var file_1; // local alias + // var y; + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitSourceElement); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) + ]))); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); + // We emit the lexical environment (hoisted variables and function declarations) + // early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + // - Calls to the exporter for exported function declarations are grouped after + // the declarations. + ts.addRange(statements, endLexicalEnvironment()); + // Emit early exports for function declarations. + ts.addRange(statements, exportedFunctionDeclarations); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, + /*location*/ undefined, + /*multiLine*/ true))) + ]), + /*multiLine*/ true))); + } + function addExportStarIfNeeded(statements) { + if (!hasExportStarsToExportValues) { + return; + } + // 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. + // local names set should only be added if we have anything exported + if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + if (externalImport.kind === 236 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + return addExportStarFunction(statements, /*localNames*/ undefined); + } + } + var exportedNames = []; + if (exportedLocalNames) { + for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { + var exportedLocalName = exportedLocalNames_1[_a]; + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); + } + } + for (var _b = 0, externalImports_2 = externalImports; _b < externalImports_2.length; _b++) { + var externalImport = externalImports_2[_b]; + if (externalImport.kind !== 236 /* ExportDeclaration */) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + // export * from ... + continue; + } + for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { + var element = _d[_c]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true)) + ]))); + return addExportStarFunction(statements, exportedNamesStorageRef); + } + /** + * Emits a setter callback for each dependency group. + * @param write The callback used to write each callback. + */ + function generateSetters(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 230 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // fall-through + case 229 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 236 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true); + } + function visitSourceElement(node) { + switch (node.kind) { + case 230 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 236 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 235 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return visitNestedNode(node); + } + } + function visitNestedNode(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var currentGrandparent = currentParent; + currentParent = currentNode; + currentNode = node; + if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { + enclosingBlockScopedContainer = currentParent; + } + var result = visitNestedNodeWorker(node); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return result; + } + function visitNestedNodeWorker(node) { + switch (node.kind) { + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 221 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 206 /* ForStatement */: + return visitForStatement(node); + case 207 /* ForInStatement */: + return visitForInStatement(node); + case 208 /* ForOfStatement */: + return visitForOfStatement(node); + case 204 /* DoStatement */: + return visitDoStatement(node); + case 205 /* WhileStatement */: + return visitWhileStatement(node); + case 214 /* LabeledStatement */: + return visitLabeledStatement(node); + case 212 /* WithStatement */: + return visitWithStatement(node); + case 213 /* SwitchStatement */: + return visitSwitchStatement(node); + case 227 /* CaseBlock */: + return visitCaseBlock(node); + case 249 /* CaseClause */: + return visitCaseClause(node); + case 250 /* DefaultClause */: + return visitDefaultClause(node); + case 216 /* TryStatement */: + return visitTryStatement(node); + case 252 /* CatchClause */: + return visitCatchClause(node); + case 199 /* Block */: + return visitBlock(node); + case 202 /* ExpressionStatement */: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (node.importClause && ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitImportEqualsDeclaration(node) { + if (ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + // NOTE(rbuckton): Do we support export import = require('') in System? + return undefined; + } + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + var statements = []; + ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); + return statements; + } + return undefined; + } + function visitExportSpecifier(specifier) { + if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) + || resolver.isValueAliasDeclaration(specifier)) { + recordExportName(specifier.name); + return createExportStatement(specifier.name, specifier.propertyName || specifier.name); + } + return undefined; + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + return createExportStatement(ts.createLiteral("default"), node.expression); + } + } + return undefined; + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The variable statement to visit. + */ + function visitVariableStatement(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3 /* BlockScoped */) == 0) || + enclosingBlockScopedContainer.kind === 256 /* SourceFile */; + if (!shouldHoist) { + return node; + } + var isExported = ts.hasModifier(node, 1 /* Export */); + var expressions = []; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, isExported); + if (visited) { + expressions.push(visited); + } + } + if (expressions.length) { + return ts.createStatement(ts.inlineExpressions(expressions), node); + } + return undefined; + } + /** + * Transforms a VariableDeclaration into one or more assignment expressions. + * + * @param node The VariableDeclaration to transform. + * @param isExported A value used to indicate whether the containing statement was exported. + */ + function transformVariable(node, isExported) { + // Hoist any bound names within the declaration. + hoistBindingElement(node, isExported); + if (!node.initializer) { + // If the variable has no initializer, ignore it. + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + // If the variable has an IdentifierName, write out an assignment expression in its place. + return ts.createAssignment(name, node.initializer); + } + else { + // If the variable has a BindingPattern, flatten the variable into multiple assignment expressions. + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The function declaration to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + // If the function is exported, ensure it has a name and rewrite the function without any export flags. + var name_30 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.asteriskToken, name_30, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, node.body, + /*location*/ node); + // Record a declaration export in the outer module body function. + recordExportedFunctionDeclaration(node); + if (!ts.hasModifier(node, 512 /* Default */)) { + recordExportName(name_30); + } + ts.setOriginalNode(newNode, node); + node = newNode; + } + // Hoist the function declaration to the outer module body function. + hoistFunctionDeclaration(node); + return undefined; + } + function visitExpressionStatement(node) { + var originalNode = ts.getOriginalNode(node); + if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { + var name_31 = getDeclarationName(originalNode); + // We only need to hoistVariableDeclaration for EnumDeclaration + // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement + // which then call transformsVariable for each declaration in declarationList + if (originalNode.kind === 224 /* EnumDeclaration */) { + hoistVariableDeclaration(name_31); + } + return [ + node, + createExportStatement(name_31, name_31) + ]; + } + return node; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The class declaration to visit. + */ + function visitClassDeclaration(node) { + // Hoist the name of the class declaration to the outer module body function. + var name = getDeclarationName(node); + hoistVariableDeclaration(name); + var statements = []; + // Rewrite the class declaration into an assignment of a class expression. + statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, node.heritageClauses, node.members, + /*location*/ node)), + /*location*/ node)); + // If the class was exported, write a declaration export to the inner module body function. + if (ts.hasModifier(node, 1 /* Export */)) { + if (!ts.hasModifier(node, 512 /* Default */)) { + recordExportName(name); + } + statements.push(createDeclarationExport(node)); + } + return statements; + } + function shouldHoistLoopInitializer(node) { + return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) === 0; + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitForStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var expressions = []; + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, /*isExported*/ false); + if (visited) { + expressions.push(visited); + } + } + ; + return ts.createFor(expressions.length + ? ts.inlineExpressions(expressions) + : ts.createSynthesizedNode(193 /* OmittedExpression */), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), + /*location*/ node); + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + /** + * Transforms and hoists the declaration list of a ForInStatement or ForOfStatement into an expression. + * + * @param node The decalaration list to transform. + */ + function transformForBinding(node) { + var firstDeclaration = ts.firstOrUndefined(node.declarations); + hoistBindingElement(firstDeclaration, /*isExported*/ false); + var name = firstDeclaration.name; + return ts.isIdentifier(name) + ? name + : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitForInStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitForOfStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitDoStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitWhileStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitLabeledStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitWithStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitSwitchStatement(node) { + var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); + if (caseBlock !== node.caseBlock) { + var updated = ts.getMutableClone(node); + updated.caseBlock = caseBlock; + return updated; + } + return node; + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); + if (clauses !== node.clauses) { + var updated = ts.getMutableClone(node); + updated.clauses = clauses; + return updated; + } + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The clause to visit. + */ + function visitCaseClause(node) { + var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); + if (statements !== node.statements) { + var updated = ts.getMutableClone(node); + updated.statements = statements; + return updated; + } + return node; + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The clause to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The clause to visit. + */ + function visitCatchClause(node) { + var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); + if (block !== node.block) { + var updated = ts.getMutableClone(node); + updated.block = block; + return updated; + } + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The block to visit. + */ + function visitBlock(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + // + // Substitutions + // + function onEmitNode(node, emit) { + if (node.kind === 256 /* SourceFile */) { + exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + exportFunctionForFile = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + case 187 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 185 /* PrefixUnaryExpression */: + case 186 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for identifiers exported at the top level of a module. + */ + function substituteExpressionIdentifier(node) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + var importBinding = createImportBinding(importDeclaration); + if (importBinding) { + return importBinding; + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return substituteAssignmentExpression(node); + } + return node; + } + function substituteAssignmentExpression(node) { + setNodeEmitFlags(node, 128 /* NoSubstitution */); + var left = node.left; + switch (left.kind) { + case 69 /* Identifier */: + var exportDeclaration = resolver.getReferencedExportContainer(left); + if (exportDeclaration) { + return createExportExpression(left, node); + } + break; + case 171 /* ObjectLiteralExpression */: + case 170 /* ArrayLiteralExpression */: + if (hasExportedReferenceInDestructuringPattern(left)) { + return substituteDestructuring(node); + } + break; + } + return node; + } + function isExportedBinding(name) { + var container = resolver.getReferencedExportContainer(name); + return container && container.kind === 256 /* SourceFile */; + } + function hasExportedReferenceInDestructuringPattern(node) { + switch (node.kind) { + case 69 /* Identifier */: + return isExportedBinding(node); + case 171 /* ObjectLiteralExpression */: + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (hasExportedReferenceInObjectDestructuringElement(property)) { + return true; + } + } + break; + case 170 /* ArrayLiteralExpression */: + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (hasExportedReferenceInArrayDestructuringElement(element)) { + return true; + } + } + break; + } + return false; + } + function hasExportedReferenceInObjectDestructuringElement(node) { + if (ts.isShorthandPropertyAssignment(node)) { + return isExportedBinding(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringElement(node.initializer); + } + else { + return false; + } + } + function hasExportedReferenceInArrayDestructuringElement(node) { + if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else { + return hasExportedReferenceInDestructuringElement(node); + } + } + function hasExportedReferenceInDestructuringElement(node) { + if (ts.isBinaryExpression(node)) { + var left = node.left; + return node.operatorToken.kind === 56 /* EqualsToken */ + && isDestructuringPattern(left) + && hasExportedReferenceInDestructuringPattern(left); + } + else if (ts.isIdentifier(node)) { + return isExportedBinding(node); + } + else if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else if (isDestructuringPattern(node)) { + return hasExportedReferenceInDestructuringPattern(node); + } + else { + return false; + } + } + function isDestructuringPattern(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 171 /* ObjectLiteralExpression */ + || kind === 170 /* ArrayLiteralExpression */; + } + function substituteDestructuring(node) { + return ts.flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration); + } + function substituteUnaryExpression(node) { + var operand = node.operand; + var operator = node.operator; + var substitute = ts.isIdentifier(operand) && + (node.kind === 186 /* PostfixUnaryExpression */ || + (node.kind === 185 /* PrefixUnaryExpression */ && (operator === 41 /* PlusPlusToken */ || operator === 42 /* MinusMinusToken */))); + if (substitute) { + var exportDeclaration = resolver.getReferencedExportContainer(operand); + if (exportDeclaration) { + var expr = ts.createPrefix(node.operator, operand, node); + setNodeEmitFlags(expr, 128 /* NoSubstitution */); + var call = createExportExpression(operand, expr); + if (node.kind === 185 /* PrefixUnaryExpression */) { + return call; + } + else { + // export function returns the value that was passes as the second argument + // however for postfix unary expressions result value should be the value before modification. + // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' + return operator === 41 /* PlusPlusToken */ + ? ts.createSubtract(call, ts.createLiteral(1)) + : ts.createAdd(call, ts.createLiteral(1)); + } + } + } + return node; + } + /** + * Gets a name to use for a DeclarationStatement. + * @param node The declaration statement. + */ + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function addExportStarFunction(statements, localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); + } + statements.push(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) + ])), + ts.createStatement(ts.createCall(exportFunctionForFile, + /*typeArguments*/ undefined, [exports])) + ], + /*location*/ undefined, + /*multiline*/ true))); + return exportStarFunction; + } + /** + * Creates a call to the current file's export function to export a value. + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; + return ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exportName, value]); + } + /** + * Creates a call to the current file's export function to export a value. + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportStatement(name, value) { + return ts.createStatement(createExportExpression(name, value)); + } + /** + * Creates a call to the current file's export function to export a declaration. + * @param node The declaration to export. + */ + function createDeclarationExport(node) { + var declarationName = getDeclarationName(node); + var exportName = ts.hasModifier(node, 512 /* Default */) ? ts.createLiteral("default") : declarationName; + return createExportStatement(exportName, declarationName); + } + function createImportBinding(importDeclaration) { + var importAlias; + var name; + if (ts.isImportClause(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); + name = ts.createIdentifier("default"); + } + else if (ts.isImportSpecifier(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); + name = importDeclaration.propertyName || importDeclaration.name; + } + else { + return undefined; + } + if (name.originalKeywordKind && languageVersion === 0 /* ES3 */) { + return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); + } + else { + return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); + } + } + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + // deduplicate/group entries in dependency list by the dependency name + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + continue; + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + function getNameOfDependencyGroup(dependencyGroup) { + return dependencyGroup.name; + } + function recordExportName(name) { + if (!exportedLocalNames) { + exportedLocalNames = []; + } + exportedLocalNames.push(name); + } + function recordExportedFunctionDeclaration(node) { + if (!exportedFunctionDeclarations) { + exportedFunctionDeclarations = []; + } + exportedFunctionDeclarations.push(createDeclarationExport(node)); + } + function hoistBindingElement(node, isExported) { + if (ts.isOmittedExpression(node)) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + if (isExported) { + recordExportName(name); + } + } + else if (ts.isBindingPattern(name)) { + ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + } + } + function hoistExportedBindingElement(node) { + hoistBindingElement(node, /*isExported*/ true); + } + function hoistNonExportedBindingElement(node) { + hoistBindingElement(node, /*isExported*/ false); + } + function updateSourceFile(node, statements, nodeEmitFlags) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + setNodeEmitFlags(updated, nodeEmitFlags); + return updated; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(187 /* BinaryExpression */); + context.enableSubstitution(185 /* PrefixUnaryExpression */); + context.enableSubstitution(186 /* PostfixUnaryExpression */); + context.enableSubstitution(254 /* ShorthandPropertyAssignment */); + context.enableEmitNotification(256 /* SourceFile */); + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var bindingNameExportSpecifiersMap; + // Subset of exportSpecifiers that is a binding-name. + // This is to reduce amount of memory we have to keep around even after we done with module-transformer + var bindingNameExportSpecifiersForFileMap = ts.createMap(); + var hasExportStarsToExportValues; + return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + // Collect information about the external module. + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + // Perform the transformation. + var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule_1(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + return updated; + } + return node; + var _a; + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + var updated = updateSourceFile(node, statements); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); + } + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true); + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var define = ts.createIdentifier("define"); + setNodeEmitFlags(define, 16 /* UMDDefine */); + return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); + } + /** + * Transforms a SourceFile into an AMD or UMD module. + * + * @param node The SourceFile node. + * @param define The expression used to define the module. + * @param moduleName An expression for the module name, if available. + * @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies. + */ + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter("require"), + ts.createParameter("exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ]); + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); + // Visit each statement of the module body. + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addRange(statements, endLexicalEnvironment()); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + var body = ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); + if (hasExportStarsToExportValues) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + setNodeEmitFlags(body, 2 /* EmitExportStar */); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (emitAsReturn) { + var statement = ts.createReturn(exportEquals.expression, + /*location*/ exportEquals); + setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), + /*location*/ exportEquals); + setNodeEmitFlags(statement, 49152 /* NoComments */); + statements.push(statement); + } + } + } + /** + * Visits a node at the top level of the source file. + * + * @param node The node. + */ + function visitor(node) { + switch (node.kind) { + case 230 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 236 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 235 /* ExportAssignment */: + return visitExportAssignment(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 221 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 202 /* ExpressionStatement */: + return visitExpressionStatement(node); + default: + // This visitor does not descend into the tree, as export/import statements + // are only transformed at the top level of a file. + return node; + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The ImportDeclaration node. + */ + function visitImportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var statements = []; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + statements.push(ts.createStatement(createRequireCall(node), + /*location*/ node)); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, createRequireCall(node))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createConstDeclarationList(variables), + /*location*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node), + /*location*/ node) + ]))); + } + addExportImportAssignments(statements, node); + return ts.singleOrMany(statements); + } + function visitImportEqualsDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + // Set emitFlags on the name of the importEqualsDeclaration + // This is so the printer will not substitute the identifier + setNodeEmitFlags(node.name, 128 /* NoSubstitution */); + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), + /*location*/ node)); + } + else { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*location*/ undefined, + /*flags*/ languageVersion >= 2 /* ES6 */ ? 2 /* Const */ : 0 /* None */), + /*location*/ node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.createStatement(createExportAssignment(node.name, node.name), + /*location*/ node)); + } + } + addExportImportAssignments(statements, node); + return statements; + } + function visitExportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ]), + /*location*/ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + if (resolver.isValueAliasDeclaration(specifier)) { + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), + /*location*/ specifier)); + } + } + return ts.singleOrMany(statements); + } + else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + // export * from "mod"; + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), + /*typeArguments*/ undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), + /*location*/ node); + } + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + var statements = []; + addExportDefault(statements, node.expression, /*location*/ node); + return statements; + } + } + return undefined; + } + function addExportDefault(statements, expression, location) { + tryAddExportDefaultCompat(statements); + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); + } + function tryAddExportDefaultCompat(statements) { + var original = ts.getOriginalNode(currentSourceFile); + ts.Debug.assert(original.kind === 256 /* SourceFile */); + if (!original.symbol.exports["___esModule"]) { + if (languageVersion === 0 /* ES3 */) { + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + function addExportImportAssignments(statements, node) { + if (ts.isImportEqualsDeclaration(node)) { + addExportMemberAssignments(statements, node.name); + } + else { + var names = ts.reduceEachChild(node, collectExportMembers, []); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_32 = names_1[_i]; + addExportMemberAssignments(statements, name_32); + } + } + } + function collectExportMembers(names, node) { + if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { + var name_33 = node.name; + if (ts.isIdentifier(name_33)) { + names.push(name_33); + } + } + return ts.reduceEachChild(node, collectExportMembers, names); + } + function addExportMemberAssignments(statements, name) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), + /*location*/ specifier.name))); + } + } + } + function addExportMemberAssignment(statements, node) { + if (ts.hasModifier(node, 512 /* Default */)) { + addExportDefault(statements, getDeclarationName(node), /*location*/ node); + } + else { + statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); + } + } + function visitVariableStatement(node) { + // If the variable is for a generated declaration, + // we should maintain it and just strip off the 'export' modifier if necessary. + var originalKind = ts.getOriginalNode(node).kind; + if (originalKind === 225 /* ModuleDeclaration */ || + originalKind === 224 /* EnumDeclaration */ || + originalKind === 221 /* ClassDeclaration */) { + if (!ts.hasModifier(node, 1 /* Export */)) { + return node; + } + return ts.setOriginalNode(ts.createVariableStatement( + /*modifiers*/ undefined, node.declarationList), node); + } + var resultStatements = []; + // If we're exporting these variables, then these just become assignments to 'exports.blah'. + // We only want to emit assignments for variables with initializers. + if (ts.hasModifier(node, 1 /* Export */)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length > 0) { + var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + resultStatements.push(inlineAssignments); + } + } + else { + resultStatements.push(node); + } + // While we might not have been exported here, each variable might have been exported + // later on in an export specifier (e.g. `export {foo as blah, bar}`). + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + addExportMemberAssignmentsForBindingName(resultStatements, decl.name); + } + return resultStatements; + } + /** + * Creates appropriate assignments for each binding identifier that is exported in an export specifier, + * and inserts it into 'resultStatements'. + */ + function addExportMemberAssignmentsForBindingName(resultStatements, name) { + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + addExportMemberAssignmentsForBindingName(resultStatements, element.name); + } + } + } + else { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + var sourceFileId = ts.getOriginalNodeId(currentSourceFile); + if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { + bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); + } + bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; + addExportMemberAssignments(resultStatements, name); + } + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); + } + else { + return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + } + function visitFunctionDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, node.body, + /*location*/ node), + /*original*/ node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitClassDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.setOriginalNode(ts.createClassDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, node.heritageClauses, node.members, + /*location*/ node), + /*original*/ node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + // Decorators end up creating a series of assignment expressions which overwrite + // the local binding that we export, so we need to defer from exporting decorated classes + // until the decoration assignments take place. We do this when visiting expression-statements. + if (node.name && !(node.decorators && node.decorators.length)) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitExpressionStatement(node) { + var original = ts.getOriginalNode(node); + var origKind = original.kind; + if (origKind === 224 /* EnumDeclaration */ || origKind === 225 /* ModuleDeclaration */) { + return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); + } + else if (origKind === 221 /* ClassDeclaration */) { + // The decorated assignment for a class name may need to be transformed. + var classDecl = original; + if (classDecl.name) { + var statements = [node]; + addExportMemberAssignments(statements, classDecl.name); + return statements; + } + } + return node; + } + function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { + var statements = [node]; + // Preserve old behavior for enums in which a variable statement is emitted after the body itself. + if (ts.hasModifier(original, 1 /* Export */) && + original.kind === 224 /* EnumDeclaration */ && + ts.isFirstDeclarationOfKind(original, 224 /* EnumDeclaration */)) { + addVarForExportedEnumOrNamespaceDeclaration(statements, original); + } + addExportMemberAssignments(statements, original.name); + return statements; + } + /** + * Adds a trailing VariableStatement for an enum or module declaration. + */ + function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { + var transformedStatement = ts.createVariableStatement( + /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), + /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], + /*location*/ node); + setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); + statements.push(transformedStatement); + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function onEmitNode(node, emit) { + if (node.kind === 256 /* SourceFile */) { + bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + bindingNameExportSpecifiersMap = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, /*location*/ node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, /*location*/ node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + case 187 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 186 /* PostfixUnaryExpression */: + case 185 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteExportedName(node) + || trySubstituteImportedName(node) + || node; + } + function substituteBinaryExpression(node) { + var left = node.left; + // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier + if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { + setNodeEmitFlags(node, 128 /* NoSubstitution */); + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, node); + } + return nestedExportAssignment; + } + } + return node; + } + function substituteUnaryExpression(node) { + // Because how the compiler only parse plusplus and minusminus to be either prefixUnaryExpression or postFixUnaryExpression depended on where they are + // We don't need to check that the operator has SyntaxKind.plusplus or SyntaxKind.minusminus + var operator = node.operator; + var operand = node.operand; + if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { + setNodeEmitFlags(node, 128 /* NoSubstitution */); + var transformedUnaryExpression = void 0; + if (node.kind === 186 /* PostfixUnaryExpression */) { + transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), + /*location*/ node); + // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here + setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); + } + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, transformedUnaryExpression || node); + } + return nestedExportAssignment; + } + } + return node; + } + function trySubstituteExportedName(node) { + var emitFlags = getNodeEmitFlags(node); + if ((emitFlags & 262144 /* LocalName */) === 0) { + var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); + if (container) { + if (container.kind === 256 /* SourceFile */) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), + /*location*/ node); + } + } + } + return undefined; + } + function trySubstituteImportedName(node) { + if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (ts.isImportClause(declaration)) { + if (languageVersion >= 1 /* ES5 */) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), + /*location*/ node); + } + else { + // TODO: ES3 transform to handle x.default -> x["default"] + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), + /*location*/ node); + } + } + else if (ts.isImportSpecifier(declaration)) { + var name_34 = declaration.propertyName || declaration.name; + if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { + // TODO: ES3 transform to handle x.default -> x["default"] + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), + /*location*/ node); + } + else { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), + /*location*/ node); + } + } + } + } + return undefined; + } + function getModuleMemberName(name) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), name, + /*location*/ name); + } + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (ts.isDefined(moduleName)) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + function createExportStatement(name, value, location) { + var statement = ts.createStatement(createExportAssignment(name, value)); + statement.startsOnNewLine = true; + if (location) { + setSourceMapRange(statement, location); + } + return statement; + } + function createExportAssignment(name, value) { + return ts.createAssignment(name.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion === 0 /* ES3 */ + ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) + : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { + var importNode = externalImports_3[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function updateSourceFile(node, statements) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + return updated; + } + var _a; + } + ts.transformModule = transformModule; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var entities = createEntitiesMap(); + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return transformSourceFile; + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + return node; + } + function visitor(node) { + if (node.transformFlags & 4 /* Jsx */) { + return visitorWorker(node); + } + else if (node.transformFlags & 8 /* ContainsJsx */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 241 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 242 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 248 /* JsxExpression */: + return visitJsxExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 244 /* JsxText */: + return visitJsxText(node); + case 248 /* JsxExpression */: + return visitJsxExpression(node); + case 241 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 242 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes; + if (attrs.length === 0) { + // When there are no attributes, React wants "null" + objectProperties = ts.createNull(); + } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. + segments.unshift(ts.createObjectLiteral()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments) + || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + } + var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createLiteral(true); + } + else if (node.kind === 9 /* StringLiteral */) { + var decoded = tryDecodeEntities(node.text); + return decoded ? ts.createLiteral(decoded, /*location*/ node) : node; + } + else if (node.kind === 248 /* JsxExpression */) { + return visitJsxExpression(node); + } + else { + ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var text = ts.getTextOfNode(node, /*includeTrivia*/ true); + var parts; + var firstNonWhitespace = 0; + var lastNonWhitespace = -1; + // JSX trims whitespace at the end and beginning of lines, except that the + // start/end of a tag is considered a start/end of a line only if that line is + // on the same line as the closing tag. See examples in + // tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { + var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + if (!parts) { + parts = []; + } + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + parts.push(ts.createLiteral(decodeEntities(part))); + } + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpace(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + if (firstNonWhitespace !== -1) { + var part = text.substr(firstNonWhitespace); + if (!parts) { + parts = []; + } + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + parts.push(ts.createLiteral(decodeEntities(part))); + } + if (parts) { + return ts.reduceLeft(parts, aggregateJsxTextParts); + } + return undefined; + } + /** + * Aggregates two expressions by interpolating them with a whitespace literal. + */ + function aggregateJsxTextParts(left, right) { + return ts.createAdd(ts.createAdd(left, ts.createLiteral(" ")), right); + } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities[word]; + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) + return ch ? String.fromCharCode(ch) : match; + } + }); + } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 241 /* JsxElement */) { + return getTagName(node.openingElement); + } + else { + var name_35 = node.tagName; + if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { + return ts.createLiteral(name_35.text); + } + else { + return ts.createExpressionFromEntityName(name_35); + } + } + } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ + function getAttributeName(node) { + var name = node.name; + if (/^[A-Za-z_]\w*$/.test(name.text)) { + return name; + } + else { + return ts.createLiteral(name.text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + function createEntitiesMap() { + return ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); + } +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES7(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if (node.transformFlags & 16 /* ES7 */) { + return visitorWorker(node); + } + else if (node.transformFlags & 32 /* ContainsES7 */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 187 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + // We are here because ES7 adds support for the exponentiation operator. + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { + var target = void 0; + var value = void 0; + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), + /*location*/ left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, + /*location*/ left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), left.name, + /*location*/ left); + value = ts.createPropertyAccess(expressionTemp, left.name, + /*location*/ left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node), /*location*/ node); + } + else if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */) { + // Transforms `a ** b` into `Math.pow(a, b)` + return ts.createMathPow(left, right, /*location*/ node); + } + else { + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + } + ts.transformES7 = transformES7; +})(ts || (ts = {})); +/// +/// +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ +var ts; +(function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block + })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); + var instructionNames = ts.createMap((_a = {}, + _a[2 /* Return */] = "return", + _a[3 /* Break */] = "break", + _a[4 /* Yield */] = "yield", + _a[5 /* YieldStar */] = "yield*", + _a[7 /* Endfinally */] = "endfinally", + _a)); + function transformGenerators(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. + var labelNumbers; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. + return transformSourceFile; + function transformSourceFile(node) { + if (node.transformFlags & 1024 /* ContainsGenerator */) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + } + return node; + } + /** + * Visits a node. + * + * @param node The node to visit. + */ + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 512 /* Generator */) { + return visitGenerator(node); + } + else if (transformFlags & 1024 /* ContainsGenerator */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 204 /* DoStatement */: + return visitDoStatement(node); + case 205 /* WhileStatement */: + return visitWhileStatement(node); + case 213 /* SwitchStatement */: + return visitSwitchStatement(node); + case 214 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 179 /* FunctionExpression */: + return visitFunctionExpression(node); + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 206 /* ForStatement */: + return visitForStatement(node); + case 207 /* ForInStatement */: + return visitForInStatement(node); + case 210 /* BreakStatement */: + return visitBreakStatement(node); + case 209 /* ContinueStatement */: + return visitContinueStatement(node); + case 211 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (1024 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 187 /* BinaryExpression */: + return visitBinaryExpression(node); + case 188 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 190 /* YieldExpression */: + return visitYieldExpression(node); + case 170 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 171 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 173 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 174 /* CallExpression */: + return visitCallExpression(node); + case 175 /* NewExpression */: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ + function visitGenerator(node) { + switch (node.kind) { + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 179 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + node = ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, transformGeneratorFunctionBody(node.body), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + node = ts.setOriginalNode(ts.createFunctionExpression( + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, transformGeneratorFunctionBody(node.body), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ + function transformGeneratorFunctionBody(body) { + // Save existing generator state + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + // Initialize generator state + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addRange(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + // Restore previous generator state + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.createBlock(statements, /*location*/ body, body.multiLine); + } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (node.transformFlags & 4194304 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + // Do not hoist custom prologues. + if (node.emitFlags & 8388608 /* CustomPrologue */) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + } + } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitBinaryExpression(node) { + switch (ts.getExpressionAssociativity(node)) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + ts.Debug.fail("Unknown associativity."); + } + } + function isCompoundAssignment(kind) { + return kind >= 57 /* FirstCompoundAssignment */ + && kind <= 68 /* LastCompoundAssignment */; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 57 /* PlusEqualsToken */: return 35 /* PlusToken */; + case 58 /* MinusEqualsToken */: return 36 /* MinusToken */; + case 59 /* AsteriskEqualsToken */: return 37 /* AsteriskToken */; + case 60 /* AsteriskAsteriskEqualsToken */: return 38 /* AsteriskAsteriskToken */; + case 61 /* SlashEqualsToken */: return 39 /* SlashToken */; + case 62 /* PercentEqualsToken */: return 40 /* PercentToken */; + case 63 /* LessThanLessThanEqualsToken */: return 43 /* LessThanLessThanToken */; + case 64 /* GreaterThanGreaterThanEqualsToken */: return 44 /* GreaterThanGreaterThanToken */; + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 45 /* GreaterThanGreaterThanGreaterThanToken */; + case 66 /* AmpersandEqualsToken */: return 46 /* AmpersandToken */; + case 67 /* BarEqualsToken */: return 47 /* BarToken */; + case 68 /* CaretEqualsToken */: return 48 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 172 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 173 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.createBinary(target, 56 /* EqualsToken */, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 24 /* CommaToken */) { + return visitCommaExpression(node); + } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ + function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + } + else { + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); + markLabel(resultLabel); + return resultLocal; + } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ + function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24 /* CommaToken */) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ + function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ + function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; + // NOTE: we are explicitly not handling YieldStar at this time. + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + emitYieldStar(expression, /*location*/ node); + } + else { + emitYield(expression, /*location*/ node); + } + markLabel(resumeLabel); + return createGeneratorResume(); + } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ + function visitElements(elements, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp = declareLocal(); + var hasAssignedTemp = false; + if (numInitialElements > 0) { + emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + hasAssignedTemp = true; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions)); + hasAssignedTemp = true; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + /*location*/ undefined, multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + visited.startsOnNewLine = true; + } + expressions.push(visited); + } + return expressions; + } + } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false)), + /*typeArguments*/ undefined, [], + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 199 /* Block */: + return transformAndEmitBlock(node); + case 202 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 203 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 204 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 205 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 206 /* ForStatement */: + return transformAndEmitForStatement(node); + case 207 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 209 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 210 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 211 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 212 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 213 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 214 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 215 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 216 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement, /*optional*/ true)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(/*continueLabel*/ conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression), + /*location*/ initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression), + /*location*/ node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.incrementor, visitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations + if (containsYield(node)) { + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); + emitBreak(label, /*location*/ node); + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); + emitBreak(label, /*location*/ node); + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true), + /*location*/ node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true), + /*location*/ node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 250 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 249 /* CaseClause */) { + var caseClause = clause; + if (containsYield(caseClause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(caseClause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], /*location*/ caseClause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(node.label.text); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(node.label.text); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (renamedCatchVariables && ts.hasProperty(renamedCatchVariables, node.text)) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_36) { + var clone_7 = ts.getMutableClone(name_36); + setSourceMapRange(clone_7, node); + setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node)) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, /*location*/ node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + hoistVariableDeclaration(temp); + return temp; + } + /** + * Defines a label, uses as the target of a Break operation. + */ + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + /** + * Marks the current operation with the specified label. + */ + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + /** + * Ends the current block operation. + */ + function endBlock() { + var block = peekBlock(); + ts.Debug.assert(block !== undefined, "beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + /** + * Gets the current open block. + */ + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + /** + * Gets the kind of the current open block. + */ + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + /** + * Ends a code block for a generated `with` statement. + */ + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1 /* With */); + var block = endBlock(); + markLabel(block.endLabel); + } + function isWithBlock(block) { + return block.kind === 1 /* With */; + } + /** + * Begins a code block for a generated `try` statement. + */ + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var text = variable.name.text; + var name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = ts.createMap(); + context.enableSubstitution(69 /* Identifier */); + } + renamedCatchVariables[text] = true; + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1 /* Catch */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); + emitNop(); + } + /** + * Enters the `finally` block of a generated `try` statement. + */ + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2 /* Finally */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + /** + * Ends the code block for a generated `try` statement. + */ + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = endBlock(); + var state = exception.state; + if (state < 2 /* Finally */) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + function isExceptionBlock(block) { + return block.kind === 0 /* Exception */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel: breakLabel + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findBreakTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + return 0; + } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findContinueTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + return 0; + } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ + function createLabel(label) { + if (label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createSynthesizedNode(8 /* NumericLiteral */); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createNode(193 /* OmittedExpression */); + } + /** + * Creates a numeric literal for the provided instruction. + */ + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + literal.trailingComment = instructionNames[instruction]; + return literal; + } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ + function createInlineBreak(label, location) { + ts.Debug.assert(label > 0, "Invalid label: " + label); + return ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), location); + } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ + function createInlineReturn(expression, location) { + return ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)]), location); + } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ + function createGeneratorResume(location) { + return ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [], location); + } + /** + * Emits an empty instruction. + */ + function emitNop() { + emitWorker(0 /* Nop */); + } + /** + * Emits a Statement. + * + * @param node A statement. + */ + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } + else { + emitNop(); + } + } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + // mark entry point + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + /** + * Builds the generator function body. + */ + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), + /*typeArguments*/ undefined, [ + ts.createThis(), + setNodeEmitFlags(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*location*/ undefined, + /*multiLine*/ buildResult.length > 0)), 4194304 /* ReuseTempVariableScope */) + ]); + } + /** + * Builds the statements for the generator function body. + */ + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + switchStatement.startsOnNewLine = true; + return [switchStatement]; + } + if (statements) { + return statements; + } + return []; + } + /** + * Flush the current label and advance to a new label. + */ + function flushLabel() { + if (!statements) { + return; + } + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + /** + * Flush the final label of the generator function body. + */ + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + } + if (statements && clauses) { + appendLabel(/*markLabelEnd*/ false); + } + updateLabelExpressions(); + } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ + function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. + if (!lastOperationWasCompletion) { + return true; + } + // if there are no labels defined or referenced, then the final label is + // not reachable. + if (!labelOffsets || !labelExpressions) { + return false; + } + // if the label for this offset is referenced, then the final label + // is reachable. + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. + statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + /** + * Tries to enter into a new label at the current operation index. + */ + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + /** + * Updates literal expressions for labels with actual label numbers. + */ + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + /** + * Tries to enter or leave a code block. + */ + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + if (isExceptionBlock(block)) { + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + } + else if (isWithBlock(block)) { + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + } + } + } + } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } + else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ + function writeAssign(left, right, operationLocation) { + writeStatement(ts.createStatement(ts.createAssignment(left, right), operationLocation)); + } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createThrow(expression, operationLocation)); + } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)]), operationLocation)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), operationLocation)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.createIf(condition, ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), operationLocation))); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.createIf(ts.createLogicalNot(condition), ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), operationLocation))); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)]), operationLocation)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5 /* YieldStar */), + expression + ]), operationLocation)); + } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7 /* Endfinally */) + ]))); + } + } + ts.transformGenerators = transformGenerators; + var _a; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var ES6SubstitutionFlags; + (function (ES6SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES6SubstitutionFlags[ES6SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES6SubstitutionFlags[ES6SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES6SubstitutionFlags || (ES6SubstitutionFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + function transformES6(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + // don't treat content of nodes that start new lexical environment as part of converted loop copy + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64 /* ES6 */) !== 0 || + node.kind === 214 /* LabeledStatement */ || + (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128 /* ContainsES6 */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { + switch (node.kind) { + case 211 /* ReturnStatement */: + return visitReturnStatement(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 213 /* SwitchStatement */: + return visitSwitchStatement(node); + case 210 /* BreakStatement */: + case 209 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 97 /* ThisKeyword */: + return visitThisKeyword(node); + case 69 /* Identifier */: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 82 /* ExportKeyword */: + return node; + case 221 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 192 /* ClassExpression */: + return visitClassExpression(node); + case 142 /* Parameter */: + return visitParameter(node); + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 180 /* ArrowFunction */: + return visitArrowFunction(node); + case 179 /* FunctionExpression */: + return visitFunctionExpression(node); + case 218 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 69 /* Identifier */: + return visitIdentifier(node); + case 219 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 214 /* LabeledStatement */: + return visitLabeledStatement(node); + case 204 /* DoStatement */: + return visitDoStatement(node); + case 205 /* WhileStatement */: + return visitWhileStatement(node); + case 206 /* ForStatement */: + return visitForStatement(node); + case 207 /* ForInStatement */: + return visitForInStatement(node); + case 208 /* ForOfStatement */: + return visitForOfStatement(node); + case 202 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 171 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 254 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 170 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 174 /* CallExpression */: + return visitCallExpression(node); + case 175 /* NewExpression */: + return visitNewExpression(node); + case 178 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 187 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* TemplateHead */: + case 13 /* TemplateMiddle */: + case 14 /* TemplateTail */: + return visitTemplateLiteral(node); + case 176 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 189 /* TemplateExpression */: + return visitTemplateExpression(node); + case 190 /* YieldExpression */: + return visitYieldExpression(node); + case 95 /* SuperKeyword */: + return visitSuperKeyword(node); + case 190 /* YieldExpression */: + // `yield` will be handled by a generators transform. + return ts.visitEachChild(node, visitor, context); + case 147 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 256 /* SourceFile */: + return visitSourceFileNode(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 180 /* ArrowFunction */) { + enclosingNonArrowFunction = currentNode; + if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + // keep track of the enclosing variable statement when in the context of + // variable statements, variable declarations, binding elements, and binding + // patterns. + switch (currentNode.kind) { + case 200 /* VariableStatement */: + enclosingVariableStatement = currentNode; + break; + case 219 /* VariableDeclarationList */: + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + case 167 /* ObjectBindingPattern */: + case 168 /* ArrayBindingPattern */: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8 /* Return */; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 180 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction is then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 210 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 210 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 210 /* BreakStatement */) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 24 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 24 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var modifierFlags = ts.getModifierFlags(node); + var isExported = modifierFlags & 1 /* Export */; + var isDefault = modifierFlags & 512 /* Default */; + // Add an `export` modifier to the statement if needed (for `--target es5 --module es6`) + var modifiers = isExported && !isDefault + ? ts.filter(node.modifiers, isExportModifier) + : undefined; + var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)) + ]), + /*location*/ node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (isExported && isDefault) { + var statements = [statement]; + statements.push(ts.createExportAssignment( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*isExportEquals*/ false, getDeclarationName(node, /*allowComments*/ false))); + return statements; + } + return statement; + } + function isExportModifier(node) { + return node.kind === 82 /* ExportKeyword */; + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + if (getNodeEmitFlags(node) & 524288 /* Indented */) { + setNodeEmitFlags(classFunction, 524288 /* Indented */); + } + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + setNodeEmitFlags(inner, 49152 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + setNodeEmitFlags(outer, 49152 /* NoComments */); + return ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16 /* CloseBraceToken */); + var localName = getLocalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + setNodeEmitFlags(outer, 49152 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); + setNodeEmitFlags(block, 49152 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), + /*location*/ extendsClauseElement)); + } + } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + statements.push(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, getDeclarationName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), + /*location*/ constructor || node)); + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + if (constructor && !hasSynthesizedSuper) { + return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); + } + return []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + startLexicalEnvironment(); + if (constructor) { + addCaptureThisForNodeIfNeeded(statements, constructor); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + } + addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); + if (constructor) { + var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + ts.addRange(statements, body); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, + /*location*/ constructor ? constructor.body.statements : node.members), + /*location*/ constructor ? constructor.body : node, + /*multiLine*/ true); + if (!constructor) { + setNodeEmitFlags(block, 49152 /* NoComments */); + } + return block; + } + function transformConstructorBodyWithSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); + } + function transformConstructorBodyWithoutSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + } + /** + * Adds a synthesized call to `_super` if it is needed. + * + * @param statements The statements for the new constructor body. + * @param constructor The constructor for the class. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, or if the class has an `extends` clause but no + // constructor, we emit a synthesized call to `_super`. + if (constructor ? hasSynthesizedSuper : extendsClauseElement) { + statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), + /*location*/ extendsClauseElement)); + } + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.createParameter(node.name, + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_37)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(setNodeEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), + /*location*/ parameter)) + ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), + /*elseStatement*/ undefined, + /*location*/ parameter); + statement.startsOnNewLine = true; + setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 69 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(setNodeEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ]), + /*location*/ parameter), 8388608 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ], /*location*/ parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), + /*location*/ parameter), ts.createPostfixIncrement(temp, /*location*/ parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), + /*location*/ parameter)) + ])); + setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, ts.createThis()) + ])); + setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); + setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 198 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 147 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 148 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(/*location*/ member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = getCommentRange(member); + var sourceMapRange = getSourceMapRange(member); + var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); + setNodeEmitFlags(func, 49152 /* NoComments */); + setSourceMapRange(func, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), + /*location*/ member.name), func), + /*location*/ member); + ts.setOriginalNode(statement, member); + setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + setNodeEmitFlags(statement, 1536 /* NoSourceMap */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), + /*location*/ getSourceMapRange(accessors.firstAccessor)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + setNodeEmitFlags(statement, 49152 /* NoComments */); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); + setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); + setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); + setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + var getter = ts.createPropertyAssignment("get", getterFunction); + setCommentRange(getter, getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); + setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + var setter = ts.createPropertyAssignment("set", setterFunction); + setCommentRange(setter, getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); + setNodeEmitFlags(func, 256 /* CapturesThis */); + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + return transformFunctionLikeToExpression(node, /*location*/ node, node.name); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + return ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node), + /*original*/ node); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 180 /* ArrowFunction */) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location), + /*original*/ node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + startLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); + // If we added any generated statements, this must be a multi-line block. + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 180 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, /*location*/ body); + setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + // If we added any final generated statements, this must be a multi-line block + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + setNodeEmitFlags(block, 32 /* SingleLine */); + } + if (closeBraceLocation) { + setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 178 /* ParenthesizedExpression */: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 187 /* BinaryExpression */: + return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (needsDestructuringValue) { + switch (node.expression.kind) { + case 178 /* ParenthesizedExpression */: + return ts.createParen(visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ true), + /*location*/ node); + case 187 /* BinaryExpression */: + return ts.createParen(visitBinaryExpression(node.expression, /*needsDestructuringValue*/ true), + /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + ts.Debug.assert(ts.isDestructuringAssignment(node)); + return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) == 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); + } + else { + assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24 /* CommaToken */, acc); }), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); + ts.setOriginalNode(declarationList, node); + setCommentRange(declarationList, node); + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, /*lookInLabeledStatements*/ false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 207 /* ForInStatement */ + && enclosingBlockScopeContainer.kind !== 208 /* ForOfStatement */ + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, /*lookInLabeledStatements*/ false))); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_8 = ts.getMutableClone(node); + clone_8.initializer = ts.createVoidZero(); + return clone_8; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern. + if (ts.isBindingPattern(node.name)) { + var recordTempVariablesInLine = !enclosingVariableStatement + || !ts.hasModifier(enclosingVariableStatement, 1 /* Export */); + return ts.flattenVariableDestructuring(context, node, /*value*/ undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + /** + * Visits a ForOfStatement and converts it into a compatible ForStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 69 /* Identifier */ + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + // Initialize LHS + // var v = _a[_i]; + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ initializer); + ts.setOriginalNode(declarationList, initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, ts.createElementAccess(rhsReference, counter)) + ], /*location*/ ts.moveRangePos(initializer, -1)), + /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); + if (ts.isDestructuringAssignment(assignment)) { + // This is a destructuring pattern, so we flatten the destructuring instead. + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, + /*needsValue*/ false, hoistVariableDeclaration, visitor))); + } + else { + // Currently there is not way to check that assignment is binary expression of destructing assignment + // so we have to cast never type to binaryExpression + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + // The old emitter does not emit source maps for the expression + setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); + // The old emitter does not emit source maps for the block. + // We add the location to preserve comments. + var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), + /*location*/ bodyLocation); + setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) + ], /*location*/ node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), + /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); + return forStatement; + } + /** + * Visits an ObjectLiteralExpression with computed propety names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 4194304 /* ContainsYield */ + || property.name.kind === 140 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + /*location*/ undefined, node.multiLine), 524288 /* Indented */)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 69 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert ? convert(node, /*convertedLoopBodyStatements*/ undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 219 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (outerConvertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length) { + var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_3); + loopBody = ts.createBlock(statements_3, /*location*/ undefined, /*multiline*/ true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 + && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 256 /* CapturesThis */; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 2097152 /* AsyncFunctionBody */; + } + var convertedLoopVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, loopParameters, + /*type*/ undefined, loopBody), loopBodyFlags)) + ])); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (currentState.argumentsName) { + // if alias for arguments is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + // if alias for this is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerConvertedLoopState) { + // pass them to outer converted loop + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var name_38 in currentState.hoistedLocalVariables) { + var identifier = currentState.hoistedLocalVariables[name_38]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { + var outParam = loopOutParameters_1[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + // clean statement part + loop.statement = undefined; + // visit childnodes to transform initializer/condition/incrementor parts + loop = ts.visitEachChild(loop, visitor, context); + // set loop statement + loop.statement = ts.createBlock(convertedLoopBodyStatements, + /*location*/ undefined, + /*multiline*/ true); + // reset and re-aggregate the transform flags + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 214 /* LabeledStatement */ + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 56 /* EqualsToken */, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37 /* AsteriskToken */), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(name)); + if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 253 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 254 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 147 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined), + /*location*/ method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); + setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, + /*location*/ node); + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), + /*location*/ node); + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + // We are here because we contain a SpreadElementExpression. + ts.Debug.assert((node.transformFlags & 262144 /* ContainsSpreadElementExpression */) !== 0); + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + /** + * Transforms an array of Expression nodes that contains a SpreadElementExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpreadElement(node) { + return ts.isSpreadElementExpression(node) + ? visitSpanOfSpreadElements + : visitSpanOfNonSpreadElements; + } + function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.map(chunk, visitExpressionOfSpreadElement); + } + function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, ts.isExpression), + /*location*/ undefined, multiLine); + } + /** + * Transforms the expression of a SpreadElementExpression node. + * + * @param node A SpreadElementExpression node. + */ + function visitExpressionOfSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, /*location*/ node); + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Allocate storage for the template site object + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Build up the template arguments and the raw and cooked strings for the template. + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + // NOTE: The parentheses here is entirely optional as we are now able to auto- + // parenthesize when rebuilding the tree. This should be removed in a + // future version. It is here for now to match our existing emit. + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) + ])); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, /*location*/ node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword(node) { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32 /* Static */) + && currentParent.kind !== 174 /* CallExpression */ + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + function visitSourceFileNode(node) { + var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, prologue); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); + ts.addRange(statements, endLexicalEnvironment()); + var clone = ts.getMutableClone(node); + clone.statements = ts.createNodeArray(statements, /*location*/ node.statements); + return clone; + } + /** + * Called by the printer just before a node is printed. + * + * @param node The node to be printed. + */ + function onEmitNode(node, emit) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + enclosingFunction = node; + } + previousOnEmitNode(node, emit); + enclosingFunction = savedEnclosingFunction; + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(69 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(97 /* ThisKeyword */); + context.enableEmitNotification(148 /* Constructor */); + context.enableEmitNotification(147 /* MethodDeclaration */); + context.enableEmitNotification(149 /* GetAccessor */); + context.enableEmitNotification(150 /* SetAccessor */); + context.enableEmitNotification(180 /* ArrowFunction */); + context.enableEmitNotification(179 /* FunctionExpression */); + context.enableEmitNotification(220 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 169 /* BindingElement */: + case 221 /* ClassDeclaration */: + case 224 /* EnumDeclaration */: + case 218 /* VariableDeclaration */: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + case 97 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && enclosingFunction + && enclosingFunction.emitFlags & 256 /* CapturesThis */) { + return ts.createIdentifier("_this", /*location*/ node); + } + return node; + } + /** + * Gets the local name for a declaration for use in expressions. + * + * A local name will *never* be prefixed with an module or namespace export modifier like + * "exports.". + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getDeclarationName(node, allowComments, allowSourceMaps, 262144 /* LocalName */); + } + /** + * Gets the name of a declaration, without source map or comments. + * + * @param node The declaration. + * @param allowComments Allow comments for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && !ts.isGeneratedIdentifier(node.name)) { + var name_39 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536 /* NoSourceMap */; + } + if (!allowComments) { + emitFlags |= 49152 /* NoComments */; + } + if (emitFlags) { + setNodeEmitFlags(name_39, emitFlags); + } + return name_39; + } + return ts.getGeneratedNameForNode(node); + } + function getClassMemberPrefix(node, member) { + var expression = getLocalName(node); + return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + var parameter = ts.singleOrUndefined(constructor.parameters); + if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191 /* SpreadElementExpression */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression === parameter.name; + } + } + ts.transformES6 = transformES6; +})(ts || (ts = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/* @internal */ +var ts; +(function (ts) { + var moduleTransformerMap = ts.createMap((_a = {}, + _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.System] = ts.transformSystemModule, + _a[ts.ModuleKind.AMD] = ts.transformModule, + _a[ts.ModuleKind.CommonJS] = ts.transformModule, + _a[ts.ModuleKind.UMD] = ts.transformModule, + _a[ts.ModuleKind.None] = ts.transformModule, + _a)); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); + function getTransformers(compilerOptions) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + transformers.push(ts.transformTypeScript); + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (jsx === 2 /* React */) { + transformers.push(ts.transformJsx); + } + transformers.push(ts.transformES7); + if (languageVersion < 2 /* ES6 */) { + transformers.push(ts.transformES6); + transformers.push(ts.transformGenerators); + } + return transformers; + } + ts.getTransformers = getTransformers; + /** + * Tracks a monotonically increasing transformation id used to associate a node with a specific + * transformation. This ensures transient properties related to transformations can be safely + * stored on source tree nodes that may be reused across multiple transformations (such as + * with compile-on-save). + */ + var nextTransformId = 1; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host. + * @param sourceFiles An array of source files + * @param transforms An array of Transformers. + */ + function transformFiles(resolver, host, sourceFiles, transformers) { + var transformId = nextTransformId; + nextTransformId++; + var tokenSourceMapRanges = ts.createMap(); + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var enabledSyntaxKindFeatures = new Array(289 /* Count */); + var parseTreeNodesWithAnnotations = []; + var lastTokenSourceMapRangeNode; + var lastTokenSourceMapRangeToken; + var lastTokenSourceMapRange; + var lexicalEnvironmentStackOffset = 0; + var hoistedVariableDeclarations; + var hoistedFunctionDeclarations; + var lexicalEnvironmentDisabled; + // The transformation context is provided to each transformer as part of transformer + // initialization. + var context = { + getCompilerOptions: function () { return host.getCompilerOptions(); }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + getNodeEmitFlags: getNodeEmitFlags, + setNodeEmitFlags: setNodeEmitFlags, + getSourceMapRange: getSourceMapRange, + setSourceMapRange: setSourceMapRange, + getTokenSourceMapRange: getTokenSourceMapRange, + setTokenSourceMapRange: setTokenSourceMapRange, + getCommentRange: getCommentRange, + setCommentRange: setCommentRange, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + startLexicalEnvironment: startLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + onSubstituteNode: onSubstituteNode, + enableSubstitution: enableSubstitution, + isSubstitutionEnabled: isSubstitutionEnabled, + onEmitNode: onEmitNode, + enableEmitNotification: enableEmitNotification, + isEmitNotificationEnabled: isEmitNotificationEnabled + }; + // Chain together and initialize each transformer. + var transformation = chain.apply(void 0, transformers)(context); + // Transform each source file. + var transformed = ts.map(sourceFiles, transformSourceFile); + // Disable modification of the lexical environment. + lexicalEnvironmentDisabled = true; + return { + getSourceFiles: function () { return transformed; }, + getTokenSourceMapRange: getTokenSourceMapRange, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + onSubstituteNode: context.onSubstituteNode, + onEmitNode: context.onEmitNode, + dispose: function () { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { + var node = parseTreeNodesWithAnnotations_1[_i]; + if (node.transformId === transformId) { + node.transformId = 0; + node.emitFlags = 0; + node.commentRange = undefined; + node.sourceMapRange = undefined; + } + } + parseTreeNodesWithAnnotations.length = 0; + } + }; + /** + * Transforms a source file. + * + * @param sourceFile The source file to transform. + */ + function transformSourceFile(sourceFile) { + if (ts.isDeclarationFile(sourceFile)) { + return sourceFile; + } + return transformation(sourceFile); + } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + function enableSubstitution(kind) { + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + } + /** + * Default hook for node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + return node; + } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ + function enableEmitNotification(kind) { + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + } + /** + * Default hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(node, emit) { + emit(node); + } + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function beforeSetAnnotation(node) { + if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + parseTreeNodesWithAnnotations.push(node); + node.transformId = transformId; + } + } + /** + * Gets flags that control emit behavior of a node. + * + * If the node does not have its own NodeEmitFlags set, the node emit flags of its + * original pointer are used. + * + * @param node The node. + */ + function getNodeEmitFlags(node) { + return node.emitFlags; + } + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setNodeEmitFlags(node, emitFlags) { + beforeSetAnnotation(node); + node.emitFlags = emitFlags; + return node; + } + /** + * Gets a custom text range to use when emitting source maps. + * + * If a node does not have its own custom source map text range, the custom source map + * text range of its original pointer is used. + * + * @param node The node. + */ + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + beforeSetAnnotation(node); + node.sourceMapRange = range; + return node; + } + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * If a node does not have its own custom source map text range for a token, the custom + * source map text range for the token of its original pointer is used. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + // As a performance optimization, use the cached value of the most recent node. + // This helps for cases where this function is called repeatedly for the same node. + if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { + return lastTokenSourceMapRange; + } + // Get the custom token source map range for a node or from one of its original nodes. + // Custom token ranges are not stored on the node to avoid the GC burden. + var range; + var current = node; + while (current) { + range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; + if (range !== undefined) { + break; + } + current = current.original; + } + // Cache the most recently requested value. + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + return range; + } + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + // Cache the most recently requested value. + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; + return node; + } + /** + * Gets a custom text range to use when emitting comments. + * + * If a node does not have its own custom source map text range, the custom source map + * text range of its original pointer is used. + * + * @param node The node. + */ + function getCommentRange(node) { + return node.commentRange || node; + } + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + beforeSetAnnotation(node); + node.commentRange = range; + return node; + } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ + function hoistVariableDeclaration(name) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var decl = ts.createVariableDeclaration(name); + if (!hoistedVariableDeclarations) { + hoistedVariableDeclarations = [decl]; + } + else { + hoistedVariableDeclarations.push(decl); + } + } + /** + * Records a hoisted function declaration within a lexical environment. + */ + function hoistFunctionDeclaration(func) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + if (!hoistedFunctionDeclarations) { + hoistedFunctionDeclarations = [func]; + } + else { + hoistedFunctionDeclarations.push(func); + } + } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ + function startLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentStackOffset++; + hoistedVariableDeclarations = undefined; + hoistedFunctionDeclarations = undefined; + } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ + function endLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + var statements; + if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { + if (hoistedFunctionDeclarations) { + statements = hoistedFunctionDeclarations.slice(); + } + if (hoistedVariableDeclarations) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + // Restore the previous lexical environment. + lexicalEnvironmentStackOffset--; + hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + return statements; + } + } + ts.transformFiles = transformFiles; + function chain(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + function compose(a, b, c, d, e) { + if (e) { + var args_4 = []; + for (var i = 0; i < arguments.length; i++) { + args_4[i] = arguments[i]; + } + return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + var _a; +})(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { + if (compilerOptions.extendedDiagnostics) { + return createSourceMapWriterWithExtendedDiagnostics(host, writer); + } + return createSourceMapWriterWorker(host, writer); + } + else { + return getNullSourceMapWriter(); + } + } + ts.createSourceMapWriter = createSourceMapWriter; var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { }, + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitPos: function (pos) { }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + changeEmitSourcePos: function () { }, + stopOverridingSpan: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -33648,27 +51988,11 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitStart: function (range) { }, - emitEnd: function (range, stopOverridingSpan) { }, - emitPos: function (pos) { }, - changeEmitSourcePos: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; }, - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; - function createSourceMapWriter(host, writer) { + function createSourceMapWriterWorker(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; + var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be var stopOverridingSpan = false; var modifyLastSourcePos = false; @@ -33680,23 +52004,42 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; + // This keeps track of the number of times `disable` has been called without a + // corresponding call to `enable`. As long as this value is non-zero, mappings will not + // be recorded. + // This is primarily used to provide a better experience when debugging binding + // patterns and destructuring assignments for simple expressions. + var disableDepth; return { + initialize: initialize, + reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitStart: emitStart, emitEnd: emitEnd, + emitTokenStart: emitTokenStart, + emitTokenEnd: emitTokenEnd, changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: function () { return stopOverridingSpan = true; }, getText: getText, - getSourceMappingURL: getSourceMappingURL, - initialize: initialize, - reset: reset + getSourceMappingURL: getSourceMappingURL }; + /** + * Initialize the SourceMapWriter for a new output file. + * + * @param filePath The path to the generated output file. + * @param sourceMapFilePath The path to the output source map file. + * @param sourceFiles The input source files for the program. + * @param isBundledEmit A value indicating whether the generated output file is a bundle. + */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { if (sourceMapData) { reset(); } currentSourceFile = undefined; + currentSourceText = undefined; + disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -33746,6 +52089,9 @@ var ts; sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); } } + /** + * Reset the SourceMapWriter to an empty state. + */ function reset() { currentSourceFile = undefined; sourceMapDir = undefined; @@ -33754,6 +52100,21 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + disableDepth = 0; + } + /** + * Re-enables the recording of mappings. + */ + function enable() { + if (disableDepth > 0) { + disableDepth--; + } + } + /** + * Disables the recording of mappings. + */ + function disable() { + disableDepth++; } function updateLastEncodedAndRecordedSpans() { if (modifyLastSourcePos) { @@ -33827,10 +52188,21 @@ var ts; lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ function emitPos(pos) { - if (pos === -1) { + if (ts.positionIsSynthesized(pos) || disableDepth > 0) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; @@ -33863,24 +52235,84 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } - function getStartPos(range) { + function getStartPosPastDecorators(range) { var rangeHasDecorators = !!range.decorators; - return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); } - function emitStart(range) { - emitPos(getStartPos(range)); + function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(getStartPosPastDecorators(range)); + } + if (ignoreChildrenCallback(contextNode)) { + disable(); + } + } + else { + emitPos(getStartPosPastDecorators(range)); + } } - function emitEnd(range, stopOverridingEnd) { - emitPos(range.end); - stopOverridingSpan = stopOverridingEnd; + function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (ignoreChildrenCallback(contextNode)) { + enable(); + } + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(range.end); + } + } + else { + emitPos(range.end); + } + stopOverridingSpan = false; } + function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return ts.skipTrivia(currentSourceText, tokenStartPos); + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenStartPos = range.pos; + } + } + tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); + emitPos(tokenStartPos); + return tokenStartPos; + } + function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return tokenEndPos; + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenEndPos = range.end; + } + } + emitPos(tokenEndPos); + return tokenEndPos; + } + // @deprecated function changeEmitSourcePos() { ts.Debug.assert(!modifyLastSourcePos); modifyLastSourcePos = true; } + /** + * Set the current source file. + * + * @param sourceFile The source file. + */ function setSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location @@ -33892,12 +52324,15 @@ var ts; sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); } } } + /** + * Gets the text for the source map. + */ function getText() { encodeLastRecordedSourceMapSpan(); return ts.stringify({ @@ -33910,6 +52345,9 @@ var ts; sourcesContent: sourceMapData.sourceMapSourcesContent }); } + /** + * Gets the SourceMappingURL for the source map. + */ function getSourceMappingURL() { if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url @@ -33921,7 +52359,46 @@ var ts; } } } - ts.createSourceMapWriter = createSourceMapWriter; + function createSourceMapWriterWithExtendedDiagnostics(host, writer) { + var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; + return { + initialize: initialize, + reset: reset, + getSourceMapData: getSourceMapData, + setSourceFile: setSourceFile, + emitPos: function (pos) { + ts.performance.mark("sourcemapStart"); + emitPos(pos); + ts.performance.measure("sourceMapTime", "sourcemapStart"); + }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitStart"); + emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); + }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitEnd"); + emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); + }, + emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenStart"); + tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); + return tokenStartPos; + }, + emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenEnd"); + tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); + return tokenEndPos; + }, + changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: stopOverridingSpan, + getText: getText, + getSourceMappingURL: getSourceMappingURL + }; + } var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -33955,6 +52432,299 @@ var ts; return encodedStr; } })(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function createCommentWriter(host, writer, sourceMap) { + var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; + var newLine = host.getNewLine(); + var emitPos = sourceMap.emitPos; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentSourceFile; + var currentText; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var disabled = compilerOptions.removeComments; + return { + reset: reset, + setSourceFile: setSourceFile, + emitNodeWithComments: emitNodeWithComments, + emitBodyWithDetachedComments: emitBodyWithDetachedComments, + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + }; + function emitNodeWithComments(node, emitCallback) { + if (disabled) { + emitCallback(node); + return; + } + if (node) { + var _a = node.commentRange || node, pos = _a.pos, end = _a.end; + var emitFlags = node.emitFlags; + if ((pos < 0 && end < 0) || (pos === end)) { + // Both pos and end are synthesized, so just emit the node without comments. + if (emitFlags & 65536 /* NoNestedComments */) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + } + else { + if (extendedDiagnostics) { + ts.performance.mark("preEmitNodeWithComment"); + } + var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; + var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if (!skipLeadingComments) { + containerPos = pos; + } + if (!skipTrailingComments) { + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 219 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitNodeWithComment"); + } + if (emitFlags & 65536 /* NoNestedComments */) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitNodeWithComment"); + } + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitNodeWithComment"); + } + } + } + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + if (extendedDiagnostics) { + ts.performance.mark("preEmitBodyWithDetachedComments"); + } + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = node.emitFlags; + var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); + } + if (emitFlags & 65536 /* NoNestedComments */) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + } + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + } + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.write(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos) { + if (disabled) { + return; + } + if (extendedDiagnostics) { + ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); + } + forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); + } + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (containerPos === -1 || pos !== containerPos) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { + ts.forEachTrailingCommentRange(currentText, end, cb); + } + } + function reset() { + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentText = currentSourceFile.text; + currentLineMap = ts.getLineStarts(currentSourceFile); + detachedCommentsInfo = undefined; + } + function disableCommentsAndEmit(node, emitCallback) { + if (disabled) { + emitCallback(node); + } + else { + disabled = true; + emitCallback(node); + disabled = false; + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + **/ + function isTripleSlashComment(commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (currentText.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + currentText.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = currentText.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? + true : false; + } + return false; + } + } + ts.createCommentWriter = createCommentWriter; +})(ts || (ts = {})); /// /* @internal */ var ts; @@ -34070,9 +52840,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -34170,11 +52938,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = {}; + usedTypeDirectiveReferences = ts.createMap(); } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { + if (!(directive in usedTypeDirectiveReferences)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -34201,7 +52969,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -34263,7 +53031,7 @@ var ts; var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -34282,7 +53050,7 @@ var ts; case 93 /* NullKeyword */: case 127 /* NeverKeyword */: case 165 /* ThisType */: - case 166 /* StringLiteralType */: + case 166 /* LiteralType */: return writeTextOfNode(currentText, type); case 194 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); @@ -34333,7 +53101,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 172 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { @@ -34407,15 +53175,15 @@ var ts; // do not need to keep track of created temp names. function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentIdentifiers, baseName)) { + if (!(baseName in currentIdentifiers)) { return baseName; } var count = 0; while (true) { count++; - var name_23 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_23)) { - return name_23; + var name_40 = baseName + "_" + count; + if (!(name_40 in currentIdentifiers)) { + return name_40; } } } @@ -34518,11 +53286,12 @@ var ts; function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export if (node.parent.kind === 256 /* SourceFile */) { + var modifiers = ts.getModifierFlags(node); // If the node is exported - if (node.flags & 1 /* Export */) { + if (modifiers & 1 /* Export */) { write("export "); } - if (node.flags & 512 /* Default */) { + if (modifiers & 512 /* Default */) { write("default "); } else if (node.kind !== 222 /* InterfaceDeclaration */ && !noDeclare) { @@ -34551,7 +53320,7 @@ var ts; // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { write("export "); } write("import "); @@ -34587,7 +53356,7 @@ var ts; } function writeImportDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { write("export "); } write("import "); @@ -34685,7 +53454,7 @@ var ts; write("global "); } else { - if (node.flags & 4096 /* Namespace */) { + if (node.flags & 16 /* Namespace */) { write("namespace "); } else { @@ -34768,7 +53537,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 /* MethodDeclaration */ && (node.parent.flags & 8 /* Private */); + return node.parent.kind === 147 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -34812,7 +53581,7 @@ var ts; break; case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.parent.flags & 32 /* Static */) { + if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 221 /* ClassDeclaration */) { @@ -34847,7 +53616,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { @@ -34882,7 +53651,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 92 /* ParameterPropertyModifier */) { + if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { emitPropertyDeclaration(param); } }); @@ -34890,7 +53659,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 128 /* Abstract */) { + if (ts.hasModifier(node, 128 /* Abstract */)) { write("abstract "); } write("class "); @@ -34936,7 +53705,7 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); emitVariableDeclaration(node); write(";"); writeLine(); @@ -34953,14 +53722,20 @@ var ts; // it if it's not a well known symbol. In that case, the text of the name will be exactly // what we want, namely the name expression enclosed in brackets. writeTextOfNode(currentText, node.name); - // If optional property emit ? - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || node.kind === 142 /* Parameter */) && ts.hasQuestionToken(node)) { + // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor + // we don't want to emit property declaration with "?" + if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || + (node.kind === 142 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) && node.parent.kind === 159 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 8 /* Private */)) { + else if (resolver.isLiteralConstDeclaration(node)) { + write(" = "); + resolver.writeLiteralConstValue(node, writer); + } + else if (!ts.hasModifier(node, 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -34975,7 +53750,7 @@ var ts; } else if (node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & 32 /* Static */) { + if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -35077,9 +53852,9 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64 /* Readonly */)); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64 /* Readonly */)); writeTextOfNode(currentText, node.name); - if (!(node.flags & 8 /* Private */)) { + if (!ts.hasModifier(node, 8 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -35108,7 +53883,7 @@ var ts; var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 150 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & 32 /* Static */) { + if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -35126,7 +53901,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 32 /* Static */) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -35160,7 +53935,7 @@ var ts; emitModuleElementDeclarationFlags(node); } else if (node.kind === 147 /* MethodDeclaration */ || node.kind === 148 /* Constructor */) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } if (node.kind === 220 /* FunctionDeclaration */) { write("function "); @@ -35188,7 +53963,7 @@ var ts; var closeParenthesizedFunctionType = false; if (node.kind === 153 /* IndexSignature */) { // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { @@ -35226,7 +54001,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 148 /* Constructor */ && !(node.flags & 8 /* Private */)) { + else if (node.kind !== 148 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -35260,7 +54035,7 @@ var ts; break; case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.flags & 32 /* Static */) { + if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -35321,7 +54096,7 @@ var ts; node.parent.parent.kind === 159 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 8 /* Private */)) { + else if (!ts.hasModifier(node.parent, 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { @@ -35352,7 +54127,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.parent.flags & 32 /* Static */) { + if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -35546,284 +54321,13 @@ var ts; ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); /// -/// +/// /// +/// +/// /* @internal */ var ts; (function (ts) { - function getResolvedExternalModuleName(host, file) { - return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); - } - ts.getResolvedExternalModuleName = getResolvedExternalModuleName; - function getExternalModuleNameFromDeclaration(host, resolver, declaration) { - var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || ts.isDeclarationFile(file)) { - return undefined; - } - return getResolvedExternalModuleName(host, file); - } - ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); - var entities = { - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }; // Flags enum to track count of temp variables and a few dedicated names var TempFlags; (function (TempFlags) { @@ -35831,15 +54335,15 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var CopyDirection; - (function (CopyDirection) { - CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; - CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; - })(CopyDirection || (CopyDirection = {})); // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature function emitFiles(resolver, host, targetSourceFile) { + var delimiters = createDelimiterMap(); + var brackets = createBracketsMap(); // emit output for the __extends helper function var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; + // Emit output for the __assign helper function. + // This is typically used for JSX spread attributes, + // and can be used for object literal spread properties. var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; // emit output for the __decorate helper function var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; @@ -35847,7071 +54351,130 @@ var ts; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; + // emit output for the __awaiter helper function var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // thisArg The value to use as the `this` binding for the transformed generator body. + // body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; + // emit output for the __export helper function + var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; + // emit output for the UMD helper function. + var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; + var superHelper = "\nconst _super = name => super[name];"; + var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var emitSkipped = false; var newLine = host.getNewLine(); - var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); + var transformers = ts.getTransformers(compilerOptions); + var writer = ts.createTextWriter(newLine); + var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = ts.createSourceMapWriter(host, writer); + var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var comments = ts.createCommentWriter(host, writer, sourceMap); + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var nodeIdToGeneratedName; + var autoGeneratedIdToGeneratedName; + var generatedNameSet; + var tempFlags; + var currentSourceFile; + var currentText; + var currentFileIdentifiers; + var extendsEmitted; + var assignEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; + var isOwnFileEmit; + var emitSkipped = false; + ts.performance.mark("beforeTransform"); + // Transform the source files + var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.measure("transformTime", "beforeTransform"); + // Extract helpers from the result + var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; + ts.performance.mark("beforePrint"); + // Emit each output file + ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); + // Clean up after transformation + transformed.dispose(); + ts.performance.measure("printTime", "beforePrint"); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList }; - function isUniqueLocalName(name, container) { - for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name)) { - // We conservatively include alias symbols to cover cases where they're emitted as locals - if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { - return false; - } - } - } - return true; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function hoistVariableDeclarationFromLoop(state, declaration) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(declaration.name); - function visit(node) { - if (node.kind === 69 /* Identifier */) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _a = 0, _b = node.elements; _a < _b.length; _a++) { - var element = _b[_a]; - visit(element.name); - } - } - } - } - function createFileEmitter() { - var writer = ts.createTextWriter(newLine); - var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; - var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); - var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; - var currentSourceFile; - var currentText; - var currentLineMap; - var currentFileIdentifiers; - var renamedDependencies; - var isEs6Module; - var isCurrentFileExternalModule; - // name of an exporter function if file is a System external module - // System.register([...], function () {...}) - // exporting in System modules looks like: - // export var x; ... x = 1 - // => - // var x;... exporter("x", x = 1) - var exportFunctionForFile; - var contextObjectForFile; - var generatedNameSet; - var nodeToGeneratedName; - var computedPropertyNamesToGeneratedNames; - var decoratedClassAliases; - var convertedLoopState; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; - var tempFlags = 0; - var tempVariables; - var tempParameters; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var detachedCommentsInfo; - /** Sourcemap data that will get encoded */ - var sourceMapData; - /** Is the file being emitted into its own file */ - var isOwnFileEmit; - /** If removeComments is true, no leading-comments needed to be emitted **/ - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; - var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, - _a[ts.ModuleKind.ES6] = emitES6Module, - _a[ts.ModuleKind.AMD] = emitAMDModule, - _a[ts.ModuleKind.System] = emitSystemModule, - _a[ts.ModuleKind.UMD] = emitUMDModule, - _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, - _a - ); - var bundleEmitDelegates = (_b = {}, - _b[ts.ModuleKind.ES6] = function () { }, - _b[ts.ModuleKind.AMD] = emitAMDModule, - _b[ts.ModuleKind.System] = emitSystemModule, - _b[ts.ModuleKind.UMD] = function () { }, - _b[ts.ModuleKind.CommonJS] = function () { }, - _b - ); - return doEmit; - function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = {}; - nodeToGeneratedName = []; - decoratedClassAliases = []; - isOwnFileEmit = !isBundledEmit; - // Emit helpers from all the files - if (isBundledEmit && modulekind) { - ts.forEach(sourceFiles, emitEmitHelpers); - } - // Do not call emit directly. It does not set the currentSourceFile. - ts.forEach(sourceFiles, emitSourceFile); - writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); - if (sourceMappingURL) { - write("//# sourceMappingURL=" + sourceMappingURL); - } - writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles); - // reset the state - sourceMap.reset(); - writer.reset(); - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - generatedNameSet = undefined; - nodeToGeneratedName = undefined; - decoratedClassAliases = undefined; - computedPropertyNamesToGeneratedNames = undefined; - convertedLoopState = undefined; - extendsEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; - assignEmitted = false; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = undefined; - detachedCommentsInfo = undefined; - sourceMapData = undefined; - isEs6Module = false; - renamedDependencies = undefined; - isCurrentFileExternalModule = false; - } - function emitSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = sourceFile.text; - currentLineMap = ts.getLineStarts(sourceFile); - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; - renamedDependencies = sourceFile.renamedDependencies; - currentFileIdentifiers = sourceFile.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - setSourceFile(sourceFile); - emitNodeWithCommentsAndWithoutSourcemap(sourceFile); - } - function isUniqueName(name) { - return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); - } - // Return the next available name in the pattern _a ... _z, _0, _1, ... - // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. - // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. - function makeTempVariableName(flags) { - if (flags && !(tempFlags & flags)) { - var name_24 = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name_24)) { - tempFlags |= flags; - return name_24; - } - } - while (true) { - var count = tempFlags & 268435455 /* CountMask */; - tempFlags++; - // Skip over 'i' and 'n' - if (count !== 8 && count !== 13) { - var name_25 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_25)) { - return name_25; - } - } - } - } - // Generate a name that is unique within the current file and doesn't conflict with any names - // in global scope. The name is formed by adding an '_n' suffix to the specified base name, - // where n is a positive integer. Note that names generated by makeTempVariableName and - // makeUniqueName are guaranteed to never conflict. - function makeUniqueName(baseName) { - // Find the first unique 'name_n', where n is a positive number - if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { - baseName += "_"; - } - var i = 1; - while (true) { - var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - return generatedNameSet[generatedName] = generatedName; - } - i++; - } - } - function generateNameForModuleOrEnum(node) { - var name = node.name.text; - // Use module/enum name itself if it is unique, otherwise make a unique variation - return isUniqueLocalName(name, node) ? name : makeUniqueName(name); - } - function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 /* StringLiteral */ ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - return makeUniqueName(baseName); - } - function generateNameForExportDefault() { - return makeUniqueName("default"); - } - function generateNameForClassExpression() { - return makeUniqueName("class"); - } - function generateNameForNode(node) { - switch (node.kind) { - case 69 /* Identifier */: - return makeUniqueName(node.text); - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: - return generateNameForModuleOrEnum(node); - case 230 /* ImportDeclaration */: - case 236 /* ExportDeclaration */: - return generateNameForImportOrExportDeclaration(node); - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 235 /* ExportAssignment */: - return generateNameForExportDefault(); - case 192 /* ClassExpression */: - return generateNameForClassExpression(); - default: - ts.Debug.fail(); - } - } - function getGeneratedNameForNode(node) { - var id = ts.getNodeId(node); - return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); - } - /** Write emitted output to disk */ - function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark, sourceFiles) { - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); - } - ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark, sourceFiles); - } - // Create a temporary variable with a unique unused name. - function createTempVariable(flags) { - var result = ts.createSynthesizedNode(69 /* Identifier */); - result.text = makeTempVariableName(flags); - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function createAndRecordTempVariable(flags) { - var temp = createTempVariable(flags); - recordTempDeclaration(temp); - return temp; - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - /** Emit the text for the given token that comes after startPos - * This by default writes the text provided with the given tokenKind - * but if optional emitFn callback is provided the text is emitted using the callback instead of default text - * @param tokenKind the kind of the token to search and emit - * @param startPos the position in the source to start searching for the token - * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - function emitToken(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - emitPos(tokenStartPos); - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - var tokenEndPos = tokenStartPos + tokenString.length; - emitPos(tokenEndPos); - return tokenEndPos; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitParenthesizedIf(node, parenthesized) { - if (parenthesized) { - write("("); - } - emit(node); - if (parenthesized) { - write(")"); - } - } - function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { - ts.Debug.assert(nodes.length > 0); - increaseIndent(); - if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - for (var i = 0, n = nodes.length; i < n; i++) { - if (i) { - if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { - write(", "); - } - else { - write(","); - writeLine(); - } - } - emit(nodes[i]); - } - if (nodes.hasTrailingComma && allowTrailingComma) { - write(","); - } - decreaseIndent(); - if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - } - function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) { - if (!emitNode) { - emitNode = emit; - } - for (var i = 0; i < count; i++) { - if (multiLine) { - if (i || leadingComma) { - write(","); - } - writeLine(); - } - else { - if (i || leadingComma) { - write(", "); - } - } - var node = nodes[start + i]; - // This emitting is to make sure we emit following comment properly - // ...(x, /*comment1*/ y)... - // ^ => node.pos - // "comment1" is not considered leading comment for "y" but rather - // considered as trailing comment of the previous node. - emitTrailingCommentsOfPosition(node.pos); - emitNode(node); - leadingComma = true; - } - if (trailingComma) { - write(","); - } - if (multiLine && !noTrailingNewLine) { - writeLine(); - } - return count; - } - function emitCommaList(nodes) { - if (nodes) { - emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false); - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, /*startIndex*/ 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(node, text) { - if (node.kind === 8 /* NumericLiteral */ && text.length > 1) { - switch (text.charCodeAt(1)) { - case 98 /* b */: - case 66 /* B */: - case 111 /* o */: - case 79 /* O */: - return true; - } - } - return false; - } - function emitLiteral(node) { - var text = getLiteralText(node); - if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { - write(node.text); - } - else { - write(text); - } - } - function getLiteralText(node) { - // Any template literal or string literal with an extended escape - // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. - if (languageVersion < 2 /* ES6 */ && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { - return getQuotedEscapedLiteralText('"', node.text, '"'); - } - // If we don't need to downlevel and we can reach the original source text using - // the node's parent reference, then simply get the text as it was originally written. - if (node.parent) { - return ts.getTextOfNodeFromSourceText(currentText, node); - } - // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. - switch (node.kind) { - case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); - case 12 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); - case 13 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); - case 14 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); - case 8 /* NumericLiteral */: - return node.text; - } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); - } - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; - } - function emitDownlevelRawTemplateLiteral(node) { - // Find original source text, since we need to emit the raw strings of the tagged template. - // The raw strings contain the (escaped) strings of what the user wrote. - // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = ts.getTextOfNodeFromSourceText(currentText, node); - // text contains the original source, it will also contain quotes ("`"), dollar signs and braces ("${" and "}"), - // thus we need to remove those characters. - // First template piece starts with "`", others with "}" - // Last template piece ends with "`", others with "${" - var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - // Newline normalization: - // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's - // and LineTerminatorSequences are normalized to for both TV and TRV. - text = text.replace(/\r\n?/g, "\n"); - text = ts.escapeString(text); - write("\"" + text + "\""); - } - function emitDownlevelTaggedTemplateArray(node, literalEmitter) { - write("["); - if (node.template.kind === 11 /* NoSubstitutionTemplateLiteral */) { - literalEmitter(node.template); - } - else { - literalEmitter(node.template.head); - ts.forEach(node.template.templateSpans, function (child) { - write(", "); - literalEmitter(child.literal); - }); - } - write("]"); - } - function emitDownlevelTaggedTemplate(node) { - var tempVariable = createAndRecordTempVariable(0 /* Auto */); - write("("); - emit(tempVariable); - write(" = "); - emitDownlevelTaggedTemplateArray(node, emit); - write(", "); - emit(tempVariable); - write(".raw = "); - emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral); - write(", "); - emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); - write("("); - emit(tempVariable); - // Now we emit the expressions - if (node.template.kind === 189 /* TemplateExpression */) { - ts.forEach(node.template.templateSpans, function (templateSpan) { - write(", "); - var needsParens = templateSpan.expression.kind === 187 /* BinaryExpression */ - && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; - emitParenthesizedIf(templateSpan.expression, needsParens); - }); - } - write("))"); - } - function emitTemplateExpression(node) { - // In ES6 mode and above, we can simply emit each portion of a template in order, but in - // ES3 & ES5 we must convert the template expression into a series of string concatenations. - if (languageVersion >= 2 /* ES6 */) { - ts.forEachChild(node, emit); - return; - } - var emitOuterParens = ts.isExpression(node.parent) - && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - var headEmitted = false; - if (shouldEmitTemplateHead()) { - emitLiteral(node.head); - headEmitted = true; - } - for (var i = 0, n = node.templateSpans.length; i < n; i++) { - var templateSpan = node.templateSpans[i]; - // Check if the expression has operands and binds its operands less closely than binary '+'. - // If it does, we need to wrap the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 178 /* ParenthesizedExpression */ - && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; - if (i > 0 || headEmitted) { - // If this is the first span and the head was not emitted, then this templateSpan's - // expression will be the first to be emitted. Don't emit the preceding ' + ' in that - // case. - write(" + "); - } - emitParenthesizedIf(templateSpan.expression, needsParens); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - } - if (emitOuterParens) { - write(")"); - } - function shouldEmitTemplateHead() { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - return parent.expression === template; - case 176 /* TaggedTemplateExpression */: - case 178 /* ParenthesizedExpression */: - return false; - default: - return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; - } - } - /** - * Returns whether the expression has lesser, greater, - * or equal precedence to the binary '+' operator - */ - function comparePrecedenceToBinaryPlus(expression) { - // All binary expressions have lower precedence than '+' apart from '*', '/', and '%' - // which have greater precedence and '-' which has equal precedence. - // All unary operators have a higher precedence apart from yield. - // Arrow functions and conditionals have a lower precedence, - // although we convert the former into regular function expressions in ES5 mode, - // and in ES6 mode this function won't get called anyway. - // - // TODO (drosen): Note that we need to account for the upcoming 'yield' and - // spread ('...') unary operators that are anticipated for ES6. - switch (expression.kind) { - case 187 /* BinaryExpression */: - switch (expression.operatorToken.kind) { - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: - return 1 /* GreaterThan */; - case 35 /* PlusToken */: - case 36 /* MinusToken */: - return 0 /* EqualTo */; - default: - return -1 /* LessThan */; - } - case 190 /* YieldExpression */: - case 188 /* ConditionalExpression */: - return -1 /* LessThan */; - default: - return 1 /* GreaterThan */; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - function jsxEmitReact(node) { - /// Emit a tag name, which is either '"div"' for lower-cased names, or - /// 'Div' for upper-cased or dotted names - function emitTagName(name) { - if (name.kind === 69 /* Identifier */ && ts.isIntrinsicJsxName(name.text)) { - write('"'); - emit(name); - write('"'); - } - else { - emit(name); - } - } - /// Emit an attribute name, which is quoted if it needs to be quoted. Because - /// these emit into an object literal property name, we don't need to be worried - /// about keywords, just non-identifier characters - function emitAttributeName(name) { - if (/^[A-Za-z_]\w*$/.test(name.text)) { - emit(name); - } - else { - write('"'); - emit(name); - write('"'); - } - } - /// Emit an name/value pair for an attribute (e.g. "x: 3") - function emitJsxAttribute(node) { - emitAttributeName(node.name); - write(": "); - if (node.initializer) { - emit(node.initializer); - } - else { - write("true"); - } - } - function emitJsxElement(openingNode, children) { - var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); - syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; - syntheticReactRef.parent = openingNode; - // Call React.createElement(tag, ... - emitLeadingComments(openingNode); - emitExpressionIdentifier(syntheticReactRef); - write(".createElement("); - emitTagName(openingNode.tagName); - write(", "); - // Attribute list - if (openingNode.attributes.length === 0) { - // When there are no attributes, React wants "null" - write("null"); - } - else { - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper - var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 247 /* JsxSpreadAttribute */; })) { - write("__assign("); - var haveOpenedObjectLiteral = false; - for (var i = 0; i < attrs.length; i++) { - if (attrs[i].kind === 247 /* JsxSpreadAttribute */) { - // If this is the first argument, we need to emit a {} as the first argument - if (i === 0) { - write("{}, "); - } - if (haveOpenedObjectLiteral) { - write("}"); - haveOpenedObjectLiteral = false; - } - if (i > 0) { - write(", "); - } - emit(attrs[i].expression); - } - else { - ts.Debug.assert(attrs[i].kind === 246 /* JsxAttribute */); - if (haveOpenedObjectLiteral) { - write(", "); - } - else { - haveOpenedObjectLiteral = true; - if (i > 0) { - write(", "); - } - write("{"); - } - emitJsxAttribute(attrs[i]); - } - } - if (haveOpenedObjectLiteral) - write("}"); - write(")"); // closing paren to React.__spread( - } - else { - // One object literal with all the attributes in them - write("{"); - for (var i = 0, n = attrs.length; i < n; i++) { - if (i > 0) { - write(", "); - } - emitJsxAttribute(attrs[i]); - } - write("}"); - } - } - // Children - if (children) { - var firstChild = void 0; - var multipleEmittableChildren = false; - for (var i = 0, n = children.length; i < n; i++) { - var jsxChild = children[i]; - if (isJsxChildEmittable(jsxChild)) { - // we need to decide whether to emit in single line or multiple lines as indented list - // store firstChild reference, if we see another emittable child, then emit accordingly - if (!firstChild) { - write(", "); - firstChild = jsxChild; - } - else { - // more than one emittable child, emit indented list - if (!multipleEmittableChildren) { - multipleEmittableChildren = true; - increaseIndent(); - writeLine(); - emit(firstChild); - } - write(", "); - writeLine(); - emit(jsxChild); - } - } - } - if (multipleEmittableChildren) { - decreaseIndent(); - } - else if (firstChild) { - if (firstChild.kind !== 241 /* JsxElement */ && firstChild.kind !== 242 /* JsxSelfClosingElement */) { - emit(firstChild); - } - else { - // If the only child is jsx element, put it on a new indented line - increaseIndent(); - writeLine(); - emit(firstChild); - writeLine(); - decreaseIndent(); - } - } - } - // Closing paren - write(")"); // closes "React.createElement(" - emitTrailingComments(openingNode); - } - if (node.kind === 241 /* JsxElement */) { - emitJsxElement(node.openingElement, node.children); - } - else { - ts.Debug.assert(node.kind === 242 /* JsxSelfClosingElement */); - emitJsxElement(node); - } - } - function jsxEmitPreserve(node) { - function emitJsxAttribute(node) { - emit(node.name); - if (node.initializer) { - write("="); - emit(node.initializer); - } - } - function emitJsxSpreadAttribute(node) { - write("{..."); - emit(node.expression); - write("}"); - } - function emitAttributes(attribs) { - for (var i = 0, n = attribs.length; i < n; i++) { - if (i > 0) { - write(" "); - } - if (attribs[i].kind === 247 /* JsxSpreadAttribute */) { - emitJsxSpreadAttribute(attribs[i]); - } - else { - ts.Debug.assert(attribs[i].kind === 246 /* JsxAttribute */); - emitJsxAttribute(attribs[i]); - } - } - } - function emitJsxOpeningOrSelfClosingElement(node) { - write("<"); - emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 242 /* JsxSelfClosingElement */)) { - write(" "); - } - emitAttributes(node.attributes); - if (node.kind === 242 /* JsxSelfClosingElement */) { - write("/>"); - } - else { - write(">"); - } - } - function emitJsxClosingElement(node) { - write(""); - } - function emitJsxElement(node) { - emitJsxOpeningOrSelfClosingElement(node.openingElement); - for (var i = 0, n = node.children.length; i < n; i++) { - emit(node.children[i]); - } - emitJsxClosingElement(node.closingElement); - } - if (node.kind === 241 /* JsxElement */) { - emitJsxElement(node); - } - else { - ts.Debug.assert(node.kind === 242 /* JsxSelfClosingElement */); - emitJsxOpeningOrSelfClosingElement(node); - } - } - // This function specifically handles numeric/string literals for enum and accessor 'identifiers'. - // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. - // For example, this is utilized when feeding in a result to Object.defineProperty. - function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 169 /* BindingElement */); - if (node.kind === 9 /* StringLiteral */) { - emitLiteral(node); - } - else if (node.kind === 140 /* ComputedPropertyName */) { - // if this is a decorated computed property, we will need to capture the result - // of the property expression so that we can apply decorators later. This is to ensure - // we don't introduce unintended side effects: - // - // class C { - // [_a = x]() { } - // } - // - // The emit for the decorated computed property decorator is: - // - // __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a)); - // - if (ts.nodeIsDecorated(node.parent)) { - if (!computedPropertyNamesToGeneratedNames) { - computedPropertyNamesToGeneratedNames = []; - } - var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)]; - if (generatedName) { - // we have already generated a variable for this node, write that value instead. - write(generatedName); - return; - } - generatedName = createAndRecordTempVariable(0 /* Auto */).text; - computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName; - write(generatedName); - write(" = "); - } - emit(node.expression); - } - else { - write('"'); - if (node.kind === 8 /* NumericLiteral */) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - write('"'); - } - } - function isExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 170 /* ArrayLiteralExpression */: - case 195 /* AsExpression */: - case 184 /* AwaitExpression */: - case 187 /* BinaryExpression */: - case 174 /* CallExpression */: - case 249 /* CaseClause */: - case 140 /* ComputedPropertyName */: - case 188 /* ConditionalExpression */: - case 143 /* Decorator */: - case 181 /* DeleteExpression */: - case 204 /* DoStatement */: - case 173 /* ElementAccessExpression */: - case 235 /* ExportAssignment */: - case 202 /* ExpressionStatement */: - case 194 /* ExpressionWithTypeArguments */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 203 /* IfStatement */: - case 245 /* JsxClosingElement */: - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: - case 247 /* JsxSpreadAttribute */: - case 248 /* JsxExpression */: - case 175 /* NewExpression */: - case 196 /* NonNullExpression */: - case 178 /* ParenthesizedExpression */: - case 186 /* PostfixUnaryExpression */: - case 185 /* PrefixUnaryExpression */: - case 211 /* ReturnStatement */: - case 254 /* ShorthandPropertyAssignment */: - case 191 /* SpreadElementExpression */: - case 213 /* SwitchStatement */: - case 176 /* TaggedTemplateExpression */: - case 197 /* TemplateSpan */: - case 215 /* ThrowStatement */: - case 177 /* TypeAssertionExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 190 /* YieldExpression */: - return true; - case 169 /* BindingElement */: - case 255 /* EnumMember */: - case 142 /* Parameter */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 218 /* VariableDeclaration */: - return parent.initializer === node; - case 172 /* PropertyAccessExpression */: - return parent.expression === node; - case 180 /* ArrowFunction */: - case 179 /* FunctionExpression */: - return parent.body === node; - case 229 /* ImportEqualsDeclaration */: - return parent.moduleReference === node; - case 139 /* QualifiedName */: - return parent.left === node; - } - return false; - } - function emitExpressionIdentifier(node) { - var container = resolver.getReferencedExportContainer(node); - if (container) { - if (container.kind === 256 /* SourceFile */) { - // Identifier references module export - if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - else { - // Identifier references namespace export - write(getGeneratedNameForNode(container)); - write("."); - } - } - else { - if (modulekind !== ts.ModuleKind.ES6) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (declaration.kind === 231 /* ImportClause */) { - // Identifier references default import - write(getGeneratedNameForNode(declaration.parent)); - write(languageVersion === 0 /* ES3 */ ? '["default"]' : ".default"); - return; - } - else if (declaration.kind === 234 /* ImportSpecifier */) { - // Identifier references named import - write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_26 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_26); - if (languageVersion === 0 /* ES3 */ && identifier === "default") { - write('["default"]'); - } - else { - write("."); - write(identifier); - } - return; - } - } - } - if (languageVersion < 2 /* ES6 */) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - else if (resolver.getNodeCheckFlags(node) & 1048576 /* BodyScopedClassBinding */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; - if (classAlias !== undefined) { - write(classAlias); - return; - } - } - } - } - if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { - if (languageVersion < 2 /* ES6 */) { - var parent_13 = node.parent; - switch (parent_13.kind) { - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 218 /* VariableDeclaration */: - return parent_13.name === node && resolver.isDeclarationWithCollidingName(parent_13); - } - } - return false; - } - function getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node) { - if (languageVersion >= 2 /* ES6 */) { - var parent_14 = node.parent; - if (parent_14.kind === 172 /* PropertyAccessExpression */ && parent_14.expression === node) { - parent_14 = parent_14.parent; - while (parent_14 && parent_14.kind !== 145 /* PropertyDeclaration */) { - parent_14 = parent_14.parent; - } - return parent_14 && parent_14.kind === 145 /* PropertyDeclaration */ && (parent_14.flags & 32 /* Static */) !== 0 && - parent_14.parent.kind === 192 /* ClassExpression */ ? parent_14.parent : undefined; - } - } - return undefined; - } - function emitIdentifier(node) { - if (convertedLoopState) { - if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - // in converted loop body arguments cannot be used directly. - var name_27 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_27); - return; - } - } - if (!node.parent) { - write(node.text); - } - else if (isExpressionIdentifier(node)) { - var classExpression = getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node); - if (classExpression) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration === classExpression) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - emitExpressionIdentifier(node); - } - else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { - write(getGeneratedNameForNode(node)); - } - else if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { - write("_this"); - } - else if (convertedLoopState) { - write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); - } - else { - write("this"); - } - } - function emitSuper(node) { - if (languageVersion >= 2 /* ES6 */) { - write("super"); - } - else { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 256 /* SuperInstance */) { - write("_super.prototype"); - } - else { - write("_super"); - } - } - } - function emitObjectBindingPattern(node) { - write("{ "); - var elements = node.elements; - emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - var elements = node.elements; - emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); - write("]"); - } - function emitBindingElement(node) { - if (node.propertyName) { - emit(node.propertyName); - write(": "); - } - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emit(node.name); - } - else { - emitModuleMemberName(node); - } - emitOptional(" = ", node.initializer); - } - function emitSpreadElementExpression(node) { - write("..."); - emit(node.expression); - } - function emitYieldExpression(node) { - write(ts.tokenToString(114 /* YieldKeyword */)); - if (node.asteriskToken) { - write("*"); - } - if (node.expression) { - write(" "); - emit(node.expression); - } - } - function emitAwaitExpression(node) { - var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); - if (needsParenthesis) { - write("("); - } - write(ts.tokenToString(114 /* YieldKeyword */)); - write(" "); - emit(node.expression); - if (needsParenthesis) { - write(")"); - } - } - function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 187 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { - return true; - } - else if (node.parent.kind === 188 /* ConditionalExpression */ && node.parent.condition === node) { - return true; - } - return false; - } - function needsParenthesisForPropertyAccessOrInvocation(node) { - switch (node.kind) { - case 69 /* Identifier */: - case 170 /* ArrayLiteralExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: - case 174 /* CallExpression */: - case 178 /* ParenthesizedExpression */: - // This list is not exhaustive and only includes those cases that are relevant - // to the check in emitArrayLiteral. More cases can be added as needed. - return false; - } - return true; - } - function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { - var pos = 0; - var group = 0; - var length = elements.length; - while (pos < length) { - // Emit using the pattern .concat(, , ...) - if (group === 1 && useConcat) { - write(".concat("); - } - else if (group > 0) { - write(", "); - } - var e = elements[pos]; - if (e.kind === 191 /* SpreadElementExpression */) { - e = e.expression; - emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); - pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 170 /* ArrayLiteralExpression */) { - write(".slice()"); - } - } - else { - var i = pos; - while (i < length && elements[i].kind !== 191 /* SpreadElementExpression */) { - i++; - } - write("["); - if (multiLine) { - increaseIndent(); - } - emitList(elements, pos, i - pos, multiLine, trailingComma && i === length); - if (multiLine) { - decreaseIndent(); - } - write("]"); - pos = i; - } - group++; - } - if (group > 1) { - if (useConcat) { - write(")"); - } - } - } - function isSpreadElementExpression(node) { - return node.kind === 191 /* SpreadElementExpression */; - } - function emitArrayLiteral(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { - write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false); - write("]"); - } - else { - emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ node.multiLine, - /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); - } - } - function emitObjectLiteralBody(node, numElements) { - if (numElements === 0) { - write("{}"); - return; - } - write("{"); - if (numElements > 0) { - var properties = node.properties; - // If we are not doing a downlevel transformation for object literals, - // then try to preserve the original shape of the object literal. - // Otherwise just try to preserve the formatting. - if (numElements === properties.length) { - emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= 1 /* ES5 */, /*spacesBetweenBraces*/ true); - } - else { - var multiLine = node.multiLine; - if (!multiLine) { - write(" "); - } - else { - increaseIndent(); - } - emitList(properties, 0, numElements, /*multiLine*/ multiLine, /*trailingComma*/ false); - if (!multiLine) { - write(" "); - } - else { - decreaseIndent(); - } - } - } - write("}"); - } - function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = node.multiLine; - var properties = node.properties; - write("("); - if (multiLine) { - increaseIndent(); - } - // For computed properties, we need to create a unique handle to the object - // literal so we can modify it without risking internal assignments tainting the object. - var tempVar = createAndRecordTempVariable(0 /* Auto */); - // Write out the first non-computed properties - // (or all properties if none of them are computed), - // then emit the rest through indexing on the temp variable. - emit(tempVar); - write(" = "); - emitObjectLiteralBody(node, firstComputedPropertyIndex); - for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); - var property = properties[i]; - emitStart(property); - if (property.kind === 149 /* GetAccessor */ || property.kind === 150 /* SetAccessor */) { - // TODO (drosen): Reconcile with 'emitMemberFunctions'. - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property !== accessors.firstAccessor) { - continue; - } - write("Object.defineProperty("); - emit(tempVar); - write(", "); - emitStart(property.name); - emitExpressionForPropertyName(property.name); - emitEnd(property.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("})"); - emitEnd(property); - } - else { - emitLeadingComments(property); - emitStart(property.name); - emit(tempVar); - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - if (property.kind === 253 /* PropertyAssignment */) { - emit(property.initializer); - } - else if (property.kind === 254 /* ShorthandPropertyAssignment */) { - emitExpressionIdentifier(property.name); - } - else if (property.kind === 147 /* MethodDeclaration */) { - emitFunctionDeclaration(property); - } - else { - ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); - } - } - emitEnd(property); - } - writeComma(); - emit(tempVar); - if (multiLine) { - decreaseIndent(); - writeLine(); - } - write(")"); - function writeComma() { - if (multiLine) { - write(","); - writeLine(); - } - else { - write(", "); - } - } - } - function emitObjectLiteral(node) { - var properties = node.properties; - if (languageVersion < 2 /* ES6 */) { - var numProperties = properties.length; - // Find the first computed property. - // Everything until that point can be emitted as part of the initial object literal. - var numInitialNonComputedProperties = numProperties; - for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 140 /* ComputedPropertyName */) { - numInitialNonComputedProperties = i; - break; - } - } - var hasComputedProperty = numInitialNonComputedProperties !== properties.length; - if (hasComputedProperty) { - emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); - return; - } - } - // Ordinary case: either the object has no computed properties - // or we're compiling with an ES6+ target. - emitObjectLiteralBody(node, properties.length); - } - function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(187 /* BinaryExpression */, startsOnNewLine); - result.operatorToken = ts.createSynthesizedNode(operator); - result.left = left; - result.right = right; - return result; - } - function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(172 /* PropertyAccessExpression */); - result.expression = parenthesizeForAccess(expression); - result.name = name; - return result; - } - function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(173 /* ElementAccessExpression */); - result.expression = parenthesizeForAccess(expression); - result.argumentExpression = argumentExpression; - return result; - } - function parenthesizeForAccess(expr) { - // When diagnosing whether the expression needs parentheses, the decision should be based - // on the innermost expression in a chain of nested type assertions. - while (expr.kind === 177 /* TypeAssertionExpression */ || - expr.kind === 195 /* AsExpression */ || - expr.kind === 196 /* NonNullExpression */) { - expr = expr.expression; - } - // isLeftHandSideExpression is almost the correct criterion for when it is not necessary - // to parenthesize the expression before a dot. The known exceptions are: - // - // NewExpression: - // new C.x -> not the same as (new C).x - // NumberLiteral - // 1.x -> not the same as (1).x - // - if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 175 /* NewExpression */ && - expr.kind !== 8 /* NumericLiteral */) { - return expr; - } - var node = ts.createSynthesizedNode(178 /* ParenthesizedExpression */); - node.expression = expr; - return node; - } - function emitComputedPropertyName(node) { - write("["); - emitExpressionForPropertyName(node); - write("]"); - } - function emitMethod(node) { - if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { - write("*"); - } - emit(node.name); - if (languageVersion < 2 /* ES6 */) { - write(": function "); - } - emitSignatureAndBody(node); - } - function emitPropertyAssignment(node) { - emit(node.name); - write(": "); - // This is to ensure that we emit comment in the following case: - // For example: - // obj = { - // id: /*comment1*/ ()=>void - // } - // "comment1" is not considered to be leading comment for node.initializer - // but rather a trailing comment on the previous node. - emitTrailingCommentsOfPosition(node.initializer.pos); - emit(node.initializer); - } - // Return true if identifier resolves to an exported member of a namespace - function isExportReference(node) { - var container = resolver.getReferencedExportContainer(node); - return !!container; - } - // Return true if identifier resolves to an imported identifier - function isImportedReference(node) { - var declaration = resolver.getReferencedImportDeclaration(node); - return declaration && (declaration.kind === 231 /* ImportClause */ || declaration.kind === 234 /* ImportSpecifier */); - } - function emitShorthandPropertyAssignment(node) { - // The name property of a short-hand property assignment is considered an expression position, so here - // we manually emit the identifier to avoid rewriting. - writeTextOfNode(currentText, node.name); - // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier, - // we emit a normal property assignment. For example: - // module m { - // export let y; - // } - // module m { - // let obj = { y }; - // } - // Here we need to emit obj = { y : m.y } regardless of the output target. - // The same rules apply for imported identifiers when targeting module formats with indirect access to - // the imported identifiers. For example, when targeting CommonJS: - // - // import {foo} from './foo'; - // export const baz = { foo }; - // - // Must be transformed into: - // - // const foo_1 = require('./foo'); - // exports.baz = { foo: foo_1.foo }; - // - if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { - // Emit identifier as an identifier - write(": "); - emitExpressionIdentifier(node.name); - } - if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) { - write(" = "); - emit(node.objectAssignmentInitializer); - } - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(constantValue.toString()); - if (!compilerOptions.removeComments) { - var propertyName = node.kind === 172 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return node.kind === 172 /* PropertyAccessExpression */ || node.kind === 173 /* ElementAccessExpression */ - ? resolver.getConstantValue(node) - : undefined; - } - // Returns 'true' if the code was actually indented, false otherwise. - // If the code is not indented, an optional valueToWriteWhenNotIndenting will be - // emitted instead. - function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) { - var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); - // Always use a newline for synthesized code if the synthesizer desires it. - var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); - if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { - increaseIndent(); - writeLine(); - return true; - } - else { - if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); - } - return false; - } - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 /* ES6 */ && - node.expression.kind === 95 /* SuperKeyword */ && - isInAsyncMethodWithSuperInES6(node)) { - var name_28 = ts.createSynthesizedNode(9 /* StringLiteral */); - name_28.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_28); - return; - } - emit(node.expression); - var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; - var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); - // 1 .toString is a valid property access, emit a space after the literal - // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal - var shouldEmitSpace = false; - if (!indentedBeforeDot) { - if (node.expression.kind === 8 /* NumericLiteral */) { - // check if numeric literal was originally written with a dot - var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); - shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; - } - else { - // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(node.expression); - // isFinite handles cases when constantValue is undefined - shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; - } - } - if (shouldEmitSpace) { - write(" ."); - } - else { - write("."); - } - var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); - emit(node.name); - decreaseIndentIf(indentedBeforeDot, indentedAfterDot); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitQualifiedNameAsExpression(node, useFallback) { - if (node.left.kind === 69 /* Identifier */) { - emitEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = createAndRecordTempVariable(0 /* Auto */); - write("("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(node.left, /*useFallback*/ true); - write(") && "); - emitNodeWithoutSourceMap(temp); - } - else { - emitEntityNameAsExpression(node.left, /*useFallback*/ false); - } - write("."); - emit(node.right); - } - function emitEntityNameAsExpression(node, useFallback) { - switch (node.kind) { - case 69 /* Identifier */: - if (useFallback) { - write("typeof "); - emitExpressionIdentifier(node); - write(" !== 'undefined' && "); - } - emitExpressionIdentifier(node); - break; - case 139 /* QualifiedName */: - emitQualifiedNameAsExpression(node, useFallback); - break; - default: - emitNodeWithoutSourceMap(node); - break; - } - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 /* ES6 */ && - node.expression.kind === 95 /* SuperKeyword */ && - isInAsyncMethodWithSuperInES6(node)) { - emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 191 /* SpreadElementExpression */; }); - } - function skipParentheses(node) { - while (node.kind === 178 /* ParenthesizedExpression */ || - node.kind === 177 /* TypeAssertionExpression */ || - node.kind === 195 /* AsExpression */ || - node.kind === 196 /* NonNullExpression */) { - node = node.expression; - } - return node; - } - function emitCallTarget(node) { - if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || node.kind === 95 /* SuperKeyword */) { - emit(node); - return node; - } - var temp = createAndRecordTempVariable(0 /* Auto */); - write("("); - emit(temp); - write(" = "); - emit(node); - write(")"); - return temp; - } - function emitCallWithSpread(node) { - var target; - var expr = skipParentheses(node.expression); - if (expr.kind === 172 /* PropertyAccessExpression */) { - // Target will be emitted as "this" argument - target = emitCallTarget(expr.expression); - write("."); - emit(expr.name); - } - else if (expr.kind === 173 /* ElementAccessExpression */) { - // Target will be emitted as "this" argument - target = emitCallTarget(expr.expression); - write("["); - emit(expr.argumentExpression); - write("]"); - } - else if (expr.kind === 95 /* SuperKeyword */) { - target = expr; - write("_super"); - } - else { - emit(node.expression); - } - write(".apply("); - if (target) { - if (target.kind === 95 /* SuperKeyword */) { - // Calls of form super(...) and super.foo(...) - emitThis(target); - } - else { - // Calls of form obj.foo(...) - emit(target); - } - } - else { - // Calls of form foo(...) - write("void 0"); - } - write(", "); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true); - write(")"); - } - function isInAsyncMethodWithSuperInES6(node) { - if (languageVersion === 2 /* ES6 */) { - var container = ts.getSuperContainer(node, /*includeFunctions*/ false); - if (container && resolver.getNodeCheckFlags(container) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */)) { - return true; - } - } - return false; - } - function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { - var container = ts.getSuperContainer(superNode, /*includeFunctions*/ false); - var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096 /* AsyncMethodWithSuperBinding */; - write("_super("); - emit(argumentExpression); - write(isSuperBinding ? ").value" : ")"); - } - function emitCallExpression(node) { - if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) { - emitCallWithSpread(node); - return; - } - var expression = node.expression; - var superCall = false; - var isAsyncMethodWithSuper = false; - if (expression.kind === 95 /* SuperKeyword */) { - emitSuper(expression); - superCall = true; - } - else { - superCall = ts.isSuperPropertyOrElementAccess(expression); - isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); - emit(expression); - } - if (superCall && (languageVersion < 2 /* ES6 */ || isAsyncMethodWithSuper)) { - write(".call("); - emitThis(expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - // Spread operator logic is supported in new expressions in ES5 using a combination - // of Function.prototype.bind() and Function.prototype.apply(). - // - // Example: - // - // var args = [1, 2, 3, 4, 5]; - // new Array(...args); - // - // is compiled into the following ES5: - // - // var args = [1, 2, 3, 4, 5]; - // new (Array.bind.apply(Array, [void 0].concat(args))); - // - // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new', - // Thus, we set it to undefined ('void 0'). - if (languageVersion === 1 /* ES5 */ && - node.arguments && - hasSpreadElement(node.arguments)) { - write("("); - var target = emitCallTarget(node.expression); - write(".bind.apply("); - emit(target); - write(", [void 0].concat("); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false); - write(")))"); - write("()"); - } - else { - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - } - function emitTaggedTemplateExpression(node) { - if (languageVersion >= 2 /* ES6 */) { - emit(node.tag); - write(" "); - emit(node.template); - } - else { - emitDownlevelTaggedTemplate(node); - } - } - function emitParenExpression(node) { - // If the node is synthesized, it means the emitter put the parentheses there, - // not the user. If we didn't want them, the emitter would not have put them - // there. - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 180 /* ArrowFunction */) { - if (node.expression.kind === 177 /* TypeAssertionExpression */ || - node.expression.kind === 195 /* AsExpression */ || - node.expression.kind === 196 /* NonNullExpression */) { - var operand = node.expression.expression; - // Make sure we consider all nested cast expressions, e.g.: - // (-A).x; - while (operand.kind === 177 /* TypeAssertionExpression */ || - operand.kind === 195 /* AsExpression */ || - operand.kind === 196 /* NonNullExpression */) { - operand = operand.expression; - } - // We have an expression of the form: (SubExpr) - // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is. - // Omitting the parentheses, however, could cause change in the semantics of the generated - // code if the casted expression has a lower precedence than the rest of the expression, e.g.: - // (new A).foo should be emitted as (new A).foo and not new A.foo - // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() - // new (A()) should be emitted as new (A()) and not new A() - // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () - if (operand.kind !== 185 /* PrefixUnaryExpression */ && - operand.kind !== 183 /* VoidExpression */ && - operand.kind !== 182 /* TypeOfExpression */ && - operand.kind !== 181 /* DeleteExpression */ && - operand.kind !== 186 /* PostfixUnaryExpression */ && - operand.kind !== 175 /* NewExpression */ && - !(operand.kind === 174 /* CallExpression */ && node.parent.kind === 175 /* NewExpression */) && - !(operand.kind === 179 /* FunctionExpression */ && node.parent.kind === 174 /* CallExpression */) && - !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 172 /* PropertyAccessExpression */)) { - emit(operand); - return; - } - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(78 /* DeleteKeyword */)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(103 /* VoidKeyword */)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(101 /* TypeOfKeyword */)); - write(" "); - emit(node.expression); - } - function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) { - if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { - return false; - } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 218 /* VariableDeclaration */ || node.parent.kind === 169 /* BindingElement */); - var targetDeclaration = isVariableDeclarationOrBindingElement - ? node.parent - : resolver.getReferencedValueDeclaration(node); - return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); - } - function isNameOfExportedDeclarationInNonES6Module(node) { - if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { - return false; - } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); - } - function emitPrefixUnaryExpression(node) { - var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ - || node.operator === 42 /* MinusMinusToken */); - var externalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - if (externalExportChanged) { - // emit - // ++x - // as - // exports('x', ++x) - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - } - var internalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedDeclarationInNonES6Module(node.operand); - if (internalExportChanged) { - emitAliasEqual(node.operand); - } - write(ts.tokenToString(node.operator)); - // In some cases, we need to emit a space between the operator and the operand. One obvious case - // is when the operator is an identifier, like delete or typeof. We also need to do this for plus - // and minus expressions in certain cases. Specifically, consider the following two cases (parens - // are just for clarity of exposition, and not part of the source code): - // - // (+(+1)) - // (+(++1)) - // - // We need to emit a space in both cases. In the first case, the absence of a space will make - // the resulting expression a prefix increment operation. And in the second, it will make the resulting - // expression a prefix increment whose operand is a plus expression - (++(+x)) - // The same is true of minus of course. - if (node.operand.kind === 185 /* PrefixUnaryExpression */) { - var operand = node.operand; - if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { - write(" "); - } - else if (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */)) { - write(" "); - } - } - emit(node.operand); - if (externalExportChanged) { - write(")"); - } - } - function emitPostfixUnaryExpression(node) { - var externalExportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - var internalExportChanged = isNameOfExportedDeclarationInNonES6Module(node.operand); - if (externalExportChanged) { - // export function returns the value that was passes as the second argument - // however for postfix unary expressions result value should be the value before modification. - // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' - write("(" + exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - write(ts.tokenToString(node.operator)); - emit(node.operand); - if (node.operator === 41 /* PlusPlusToken */) { - write(") - 1)"); - } - else { - write(") + 1)"); - } - } - else if (internalExportChanged) { - emitAliasEqual(node.operand); - emit(node.operand); - if (node.operator === 41 /* PlusPlusToken */) { - write(" += 1"); - } - else { - write(" -= 1"); - } - } - else { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - } - function shouldHoistDeclarationInSystemJsModule(node) { - return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false); - } - /* - * Checks if given node is a source file level declaration (not nested in module/function). - * If 'isExported' is true - then declaration must also be exported. - * This function is used in two cases: - * - check if node is a exported source file level value to determine - * if we should also export the value after its it changed - * - check if node is a source level declaration to emit it differently, - * i.e non-exported variable statement 'var x = 1' is hoisted so - * we we emit variable statement 'var' should be dropped. - */ - function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { - if (!node || !isCurrentFileSystemExternalModule()) { - return false; - } - var current = ts.getRootDeclaration(node).parent; - while (current) { - if (current.kind === 256 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); - } - else if (ts.isDeclaration(current)) { - return false; - } - else { - current = current.parent; - } - } - } - /** - * Emit ES7 exponentiation operator downlevel using Math.pow - * @param node a binary expression node containing exponentiationOperator (**, **=) - */ - function emitExponentiationOperator(node) { - var leftHandSideExpression = node.left; - if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - var synthesizedLHS = void 0; - var shouldEmitParentheses = false; - if (ts.isElementAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(173 /* ElementAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); - synthesizedLHS.expression = identifier; - if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ && - leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) { - var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */); - synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true, leftHandSideExpression.expression); - } - else { - synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; - } - write(", "); - } - else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(172 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); - synthesizedLHS.expression = identifier; - synthesizedLHS.name = leftHandSideExpression.name; - write(", "); - } - emit(synthesizedLHS || leftHandSideExpression); - write(" = "); - write("Math.pow("); - emit(synthesizedLHS || leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - if (shouldEmitParentheses) { - write(")"); - } - } - else { - write("Math.pow("); - emit(leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - } - } - function emitAliasEqual(name) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - emitStart(specifier.name); - emitContainingModuleName(specifier); - if (languageVersion === 0 /* ES3 */ && name.text === "default") { - write('["default"]'); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - } - emitEnd(specifier.name); - write(" = "); - } - return true; - } - function emitBinaryExpression(node) { - if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ && - (node.left.kind === 171 /* ObjectLiteralExpression */ || node.left.kind === 170 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 202 /* ExpressionStatement */); - } - else { - var isAssignment = ts.isAssignmentOperator(node.operatorToken.kind); - var externalExportChanged = isAssignment && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left); - if (externalExportChanged) { - // emit assignment 'x y' as 'exports("x", x y)' - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.left); - write("\", "); - } - var internalExportChanged = isAssignment && - isNameOfExportedDeclarationInNonES6Module(node.left); - if (internalExportChanged) { - // export { foo } - // emit foo = 2 as exports.foo = foo = 2 - emitAliasEqual(node.left); - } - if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */ || node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - // Downleveled emit exponentiation operator using Math.pow - emitExponentiationOperator(node); - } - else { - emit(node.left); - // Add indentation before emit the operator if the operator is on different line - // For example: - // 3 - // + 2; - // emitted as - // 3 - // + 2; - var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 /* CommaToken */ ? " " : undefined); - write(ts.tokenToString(node.operatorToken.kind)); - var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); - emit(node.right); - decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); - } - if (externalExportChanged) { - write(")"); - } - } - } - function synthesizedNodeStartsOnNewLine(node) { - return ts.nodeIsSynthesized(node) && node.startsOnNewLine; - } - function emitConditionalExpression(node) { - emit(node.condition); - var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); - write("?"); - var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); - emit(node.whenTrue); - decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); - write(":"); - var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); - emit(node.whenFalse); - decreaseIndentIf(indentedBeforeColon, indentedAfterColon); - } - // Helper function to decrease the indent if we previously indented. Allows multiple - // previous indent values to be considered at a time. This also allows caller to just - // call this once, passing in all their appropriate indent values, instead of needing - // to call this helper function multiple times. - function decreaseIndentIf(value1, value2) { - if (value1) { - decreaseIndent(); - } - if (value2) { - decreaseIndent(); - } - } - function isSingleLineEmptyBlock(node) { - if (node && node.kind === 199 /* Block */) { - var block = node; - return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); - } - } - function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - emitToken(15 /* OpenBraceToken */, node.pos); - write(" "); - emitToken(16 /* CloseBraceToken */, node.statements.end); - return; - } - emitToken(15 /* OpenBraceToken */, node.pos); - increaseIndent(); - if (node.kind === 226 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 225 /* ModuleDeclaration */); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 226 /* ModuleBlock */) { - emitTempDeclarations(/*newLine*/ true); - } - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.statements.end); - } - function emitEmbeddedStatement(node) { - if (node.kind === 199 /* Block */) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 180 /* ArrowFunction */); - write(";"); - } - function emitIfStatement(node) { - var endPos = emitToken(88 /* IfKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - emit(node.expression); - emitToken(18 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(80 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 203 /* IfStatement */) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - } - function emitDoStatement(node) { - emitLoop(node, emitDoStatementWorker); - } - function emitDoStatementWorker(node, loop) { - write("do"); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - if (node.statement.kind === 199 /* Block */) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - emitLoop(node, emitWhileStatementWorker); - } - function emitWhileStatementWorker(node, loop) { - write("while ("); - emit(node.expression); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - } - /** - * Returns true if start of variable declaration list was emitted. - * Returns false if nothing was written - this can happen for source file level variable declarations - * in system modules where such variable declarations are hoisted. - */ - function tryEmitStartOfVariableDeclarationList(decl) { - if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) { - // variables in variable declaration list were already hoisted - return false; - } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072 /* BlockScoped */) === 0) { - // we are inside a converted loop - this can only happen in downlevel scenarios - // record names for all variable declarations - for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { - var varDecl = _b[_a]; - hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); - } - return false; - } - emitStart(decl); - if (decl && languageVersion >= 2 /* ES6 */) { - if (ts.isLet(decl)) { - write("let "); - } - else if (ts.isConst(decl)) { - write("const "); - } - else { - write("var "); - } - } - else { - write("var "); - } - // Note here we specifically dont emit end so that if we are going to emit binding pattern - // we can alter the source map correctly - return true; - } - function emitVariableDeclarationListSkippingUninitializedEntries(list) { - var started = false; - for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) { - var decl = _b[_a]; - if (!decl.initializer) { - continue; - } - if (!started) { - started = true; - } - else { - write(", "); - } - emit(decl); - } - return started; - } - function shouldConvertLoopBody(node) { - return languageVersion < 2 /* ES6 */ && - (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; - } - function emitLoop(node, loopEmitter) { - var shouldConvert = shouldConvertLoopBody(node); - if (!shouldConvert) { - loopEmitter(node, /* convertedLoop*/ undefined); - } - else { - var loop = convertLoopBody(node); - if (node.parent.kind === 214 /* LabeledStatement */) { - // if parent of the loop was labeled statement - attach the label to loop skipping converted loop body - emitLabelAndColon(node.parent); - } - loopEmitter(node, loop); - } - } - function convertLoopBody(node) { - var functionName = makeUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - var initializer = node.initializer; - if (initializer && initializer.kind === 219 /* VariableDeclarationList */) { - loopInitializer = node.initializer; - } - break; - } - var loopParameters; - var loopOutParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072 /* BlockScoped */)) { - // if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters - loopParameters = []; - for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { - var varDeclaration = _b[_a]; - processVariableDeclaration(varDeclaration.name); - } - } - var bodyIsBlock = node.statement.kind === 199 /* Block */; - var paramList = loopParameters ? loopParameters.join(", ") : ""; - writeLine(); - write("var " + functionName + " = function(" + paramList + ")"); - var convertedOuterLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (convertedOuterLoopState) { - // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. - // if outer converted loop has already accumulated some state - pass it through - if (convertedOuterLoopState.argumentsName) { - // outer loop has already used 'arguments' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; - } - if (convertedOuterLoopState.thisName) { - // outer loop has already used 'this' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.thisName = convertedOuterLoopState.thisName; - } - if (convertedOuterLoopState.hoistedLocalVariables) { - // we've already collected some non-block scoped variable declarations in enclosing loop - // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; - } - } - write(" {"); - writeLine(); - increaseIndent(); - if (bodyIsBlock) { - emitLines(node.statement.statements); - } - else { - emit(node.statement); - } - writeLine(); - // end of loop body -> copy out parameter - copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ true); - decreaseIndent(); - writeLine(); - write("};"); - writeLine(); - if (loopOutParameters) { - // declare variables to hold out params for loop body - write("var "); - for (var i = 0; i < loopOutParameters.length; i++) { - if (i !== 0) { - write(", "); - } - write(loopOutParameters[i].outParamName); - } - write(";"); - writeLine(); - } - if (convertedLoopState.argumentsName) { - // if alias for arguments is set - if (convertedOuterLoopState) { - // pass it to outer converted loop - convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; - } - else { - // this is top level converted loop and we need to create an alias for 'arguments' object - write("var " + convertedLoopState.argumentsName + " = arguments;"); - writeLine(); - } - } - if (convertedLoopState.thisName) { - // if alias for this is set - if (convertedOuterLoopState) { - // pass it to outer converted loop - convertedOuterLoopState.thisName = convertedLoopState.thisName; - } - else { - // this is top level converted loop so we need to create an alias for 'this' here - // NOTE: - // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. - // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - write("var " + convertedLoopState.thisName + " = this;"); - writeLine(); - } - } - if (convertedLoopState.hoistedLocalVariables) { - // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (convertedOuterLoopState) { - // pass them to outer converted loop - convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; - } - else { - // deduplicate and hoist collected variable declarations - write("var "); - var seen = void 0; - for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { - var id = _d[_c]; - // Don't initialize seen unless we have at least one element. - // Emit a comma to separate for all but the first element. - if (!seen) { - seen = {}; - } - else { - write(", "); - } - if (!ts.hasProperty(seen, id.text)) { - emit(id); - seen[id.text] = id.text; - } - } - write(";"); - writeLine(); - } - } - var currentLoopState = convertedLoopState; - convertedLoopState = convertedOuterLoopState; - return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function processVariableDeclaration(name) { - if (name.kind === 69 /* Identifier */) { - var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) - ? getGeneratedNameForNode(name) - : name.text; - loopParameters.push(nameText); - if (resolver.getNodeCheckFlags(name.parent) & 2097152 /* NeedsLoopOutParameter */) { - var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; - (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); - } - } - else { - for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { - var element = _b[_a]; - processVariableDeclaration(element.name); - } - } - } - } - function emitNormalLoopBody(node, emitAsEmbeddedStatement) { - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - // we get here if we are trying to emit normal loop loop inside converted loop - // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; - } - if (emitAsEmbeddedStatement) { - emitEmbeddedStatement(node.statement); - } - else if (node.statement.kind === 199 /* Block */) { - emitLines(node.statement.statements); - } - else { - writeLine(); - emit(node.statement); - } - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function copyLoopOutParameters(state, copyDirection, emitAsStatements) { - if (state.loopOutParameters) { - for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { - var outParam = _b[_a]; - if (copyDirection === 0 /* ToOriginal */) { - emitIdentifier(outParam.originalName); - write(" = " + outParam.outParamName); - } - else { - write(outParam.outParamName + " = "); - emitIdentifier(outParam.originalName); - } - if (emitAsStatements) { - write(";"); - writeLine(); - } - else { - write(", "); - } - } - } - } - function emitConvertedLoopCall(loop, emitAsBlock) { - if (emitAsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } - // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop - // simple loops are emitted as just 'loop()'; - // NOTE: if loop uses only 'continue' it still will be emitted as simple loop - var isSimpleLoop = !(loop.state.nonLocalJumps & ~4 /* Continue */) && - !loop.state.labeledNonLocalBreaks && - !loop.state.labeledNonLocalContinues; - var loopResult = makeUniqueName("state"); - if (!isSimpleLoop) { - write("var " + loopResult + " = "); - } - write(loop.functionName + "(" + loop.paramList + ");"); - writeLine(); - copyLoopOutParameters(loop.state, 0 /* ToOriginal */, /*emitAsStatements*/ true); - if (!isSimpleLoop) { - // for non simple loops we need to store result returned from converted loop function and use it to do dispatching - // converted loop function can return: - // - object - used when body of the converted loop contains return statement. Property "value" of this object stores retuned value - // - string - used to dispatch jumps. "break" and "continue" are used to non-labeled jumps, other values are used to transfer control to - // different labels - writeLine(); - if (loop.state.nonLocalJumps & 8 /* Return */) { - write("if (typeof " + loopResult + " === \"object\") "); - if (convertedLoopState) { - // we are currently nested in another converted loop - return unwrapped result - write("return " + loopResult + ";"); - // propagate 'hasReturn' flag to outer loop - convertedLoopState.nonLocalJumps |= 8 /* Return */; - } - else { - // top level converted loop - return unwrapped value - write("return " + loopResult + ".value;"); - } - writeLine(); - } - if (loop.state.nonLocalJumps & 2 /* Break */) { - write("if (" + loopResult + " === \"break\") break;"); - writeLine(); - } - // in case of labeled breaks emit code that either breaks to some known label inside outer loop or delegates jump decision to outer loop - emitDispatchTableForLabeledJumps(loopResult, loop.state, convertedLoopState); - } - if (emitAsBlock) { - writeLine(); - decreaseIndent(); - write("}"); - } - function emitDispatchTableForLabeledJumps(loopResultVariable, currentLoop, outerLoop) { - if (!currentLoop.labeledNonLocalBreaks && !currentLoop.labeledNonLocalContinues) { - return; - } - write("switch(" + loopResultVariable + ") {"); - increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop); - decreaseIndent(); - writeLine(); - write("}"); - } - function emitDispatchEntriesForLabeledJumps(table, isBreak, loopResultVariable, outerLoop) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - writeLine(); - write("case \"" + labelMarker + "\": "); - // if there are no outer converted loop or outer label in question is located inside outer converted loop - // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - if (isBreak) { - write("break "); - } - else { - write("continue "); - } - write(labelText + ";"); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - write("return " + loopResultVariable + ";"); - } - } - } - } - function emitForStatement(node) { - emitLoop(node, emitForStatementWorker); - } - function emitForStatementWorker(node, loop) { - var endPos = emitToken(86 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 219 /* VariableDeclarationList */) { - var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); - if (startIsEmitted) { - emitCommaList(variableDeclarationList.declarations); - } - else { - emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList); - } - } - else if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.incrementor); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - } - function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 208 /* ForOfStatement */) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } - else { - emitLoop(node, emitForInOrForOfStatementWorker); - } - } - function emitForInOrForOfStatementWorker(node, loop) { - var endPos = emitToken(86 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer.kind === 219 /* VariableDeclarationList */) { - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList); - emit(variableDeclarationList.declarations[0]); - } - } - else { - emit(node.initializer); - } - if (node.kind === 207 /* ForInStatement */) { - write(" in "); - } - else { - write(" of "); - } - emit(node.expression); - emitToken(18 /* CloseParenToken */, node.expression.end); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - } - function emitDownLevelForOfStatementWorker(node, loop) { - // The following ES6 code: - // - // for (let v of expr) { } - // - // should be emitted as - // - // for (let _i = 0, _a = expr; _i < _a.length; _i++) { - // let v = _a[_i]; - // } - // - // where _a and _i are temps emitted to capture the RHS and the counter, - // respectively. - // When the left hand side is an expression instead of a let declaration, - // the "let v" is not emitted. - // When the left hand side is a let/const, the v is renamed if there is - // another v in scope. - // Note that all assignments to the LHS are emitted in the body, including - // all destructuring. - // Note also that because an extra statement is needed to assign to the LHS, - // for-of bodies are always emitted as blocks. - var endPos = emitToken(86 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - // Do not emit the LHS let declaration yet, because it might contain destructuring. - // Do not call recordTempDeclaration because we are declaring the temps - // right here. Recording means they will be declared later. - // In the case where the user wrote an identifier as the RHS, like this: - // - // for (let v of arr) { } - // - // we can't reuse 'arr' because it might be modified within the body of the loop. - var counter = createTempVariable(268435456 /* _i */); - var rhsReference = ts.createSynthesizedNode(69 /* Identifier */); - rhsReference.text = node.expression.kind === 69 /* Identifier */ ? - makeUniqueName(node.expression.text) : - makeTempVariableName(0 /* Auto */); - // This is the let keyword for the counter and rhsReference. The let keyword for - // the LHS will be emitted inside the body. - emitStart(node.expression); - write("var "); - // _i = 0 - emitNodeWithoutSourceMap(counter); - write(" = 0"); - emitEnd(node.expression); - // , _a = expr - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - write("; "); - // _i < _a.length; - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write(" < "); - emitNodeWithCommentsAndWithoutSourcemap(rhsReference); - write(".length"); - emitEnd(node.expression); - write("; "); - // _i++) - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write("++"); - emitEnd(node.expression); - emitToken(18 /* CloseParenToken */, node.expression.end); - // Body - write(" {"); - writeLine(); - increaseIndent(); - // Initialize LHS - // let v = _a[_i]; - var rhsIterationValue = createElementAccessExpression(rhsReference, counter); - emitStart(node.initializer); - if (node.initializer.kind === 219 /* VariableDeclarationList */) { - write("var "); - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length > 0) { - var declaration = variableDeclarationList.declarations[0]; - if (ts.isBindingPattern(declaration.name)) { - // This works whether the declaration is a var, let, or const. - // It will use rhsIterationValue _a[_i] as the initializer. - emitDestructuring(declaration, /*isAssignmentExpressionStatement*/ false, rhsIterationValue); - } - else { - // The following call does not include the initializer, so we have - // to emit it separately. - emitNodeWithCommentsAndWithoutSourcemap(declaration); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - // It's an empty declaration list. This can only happen in an error case, if the user wrote - // for (let of []) {} - emitNodeWithoutSourceMap(createTempVariable(0 /* Auto */)); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - // Initializer is an expression. Emit the expression in the body, so that it's - // evaluated on every iteration. - var assignmentExpression = createBinaryExpression(node.initializer, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false); - if (node.initializer.kind === 170 /* ArrayLiteralExpression */ || node.initializer.kind === 171 /* ObjectLiteralExpression */) { - // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause - // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. - emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression); - } - } - emitEnd(node.initializer); - write(";"); - if (loop) { - writeLine(); - emitConvertedLoopCall(loop, /*emitAsBlock*/ false); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false); - } - writeLine(); - decreaseIndent(); - write("}"); - } - function emitBreakOrContinueStatement(node) { - if (convertedLoopState) { - // check if we can emit break\continue as is - // it is possible if either - // - break\continue is statement labeled and label is located inside the converted loop - // - break\continue is non-labeled and located in non-converted loop\switch statement - var jump = node.kind === 210 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - write("return "); - // explicit exit from loop -> copy out parameters - copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ false); - if (!node.label) { - if (node.kind === 210 /* BreakStatement */) { - convertedLoopState.nonLocalJumps |= 2 /* Break */; - write("\"break\";"); - } - else { - convertedLoopState.nonLocalJumps |= 4 /* Continue */; - // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. - write("\"continue\";"); - } - } - else { - var labelMarker = void 0; - if (node.kind === 210 /* BreakStatement */) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); - } - write("\"" + labelMarker + "\";"); - } - return; - } - } - emitToken(node.kind === 210 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - if (convertedLoopState) { - convertedLoopState.nonLocalJumps |= 8 /* Return */; - write("return { value: "); - if (node.expression) { - emit(node.expression); - } - else { - write("void 0"); - } - write(" };"); - return; - } - emitToken(94 /* ReturnKeyword */, node.pos); - emitOptional(" ", node.expression); - write(";"); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(96 /* SwitchKeyword */, node.pos); - write(" "); - emitToken(17 /* OpenParenToken */, endPos); - emit(node.expression); - endPos = emitToken(18 /* CloseParenToken */, node.expression.end); - write(" "); - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - // for switch statement allow only non-labeled break - convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; - } - emitCaseBlock(node.caseBlock, endPos); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function emitCaseBlock(node, startPos) { - emitToken(15 /* OpenBraceToken */, startPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.clauses.end); - } - function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); - } - function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 249 /* CaseClause */) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(72 /* CatchKeyword */, node.pos); - write(" "); - emitToken(17 /* OpenParenToken */, endPos); - emit(node.variableDeclaration); - emitToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : endPos); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(76 /* DebuggerKeyword */, node.pos); - write(";"); - } - function emitLabelAndColon(node) { - emit(node.label); - write(": "); - } - function emitLabeledStatement(node) { - if (!ts.isIterationStatement(node.statement, /* lookInLabeledStatements */ false) || !shouldConvertLoopBody(node.statement)) { - emitLabelAndColon(node); - } - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - emit(node.statement); - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 225 /* ModuleDeclaration */); - return node; - } - function emitContainingModuleName(node) { - var container = getContainingModule(node); - write(container ? getGeneratedNameForNode(container) : "exports"); - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { - var container = getContainingModule(node); - if (container) { - write(getGeneratedNameForNode(container)); - write("."); - } - else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - emitNodeWithCommentsAndWithoutSourcemap(node.name); - emitEnd(node.name); - } - function createVoidZero() { - var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); - zero.text = "0"; - var result = ts.createSynthesizedNode(183 /* VoidExpression */); - result.expression = zero; - return result; - } - function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 256 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 235 /* ExportAssignment */); - // only allow export default at a source file level - if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { - if (!isEs6Module) { - if (languageVersion !== 0 /* ES3 */) { - // default value of configurable, enumerable, writable are `false`. - write('Object.defineProperty(exports, "__esModule", { value: true });'); - writeLine(); - } - else { - write("exports.__esModule = true;"); - writeLine(); - } - } - } - } - } - function emitExportMemberAssignment(node) { - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - // emit call to exporter only for top level nodes - if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { - // emit export default as - // export("default", ) - write(exportFunctionForFile + "(\""); - if (node.flags & 512 /* Default */) { - write("default"); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - write("\", "); - emitDeclarationName(node); - write(")"); - } - else { - if (node.flags & 512 /* Default */) { - emitEs6ExportDefaultCompat(node); - if (languageVersion === 0 /* ES3 */) { - write('exports["default"]'); - } - else { - write("exports.default"); - } - } - else { - emitModuleMemberName(node); - } - write(" = "); - emitDeclarationName(node); - } - emitEnd(node); - write(";"); - } - } - function emitExportMemberAssignments(name) { - if (modulekind === ts.ModuleKind.System) { - return; - } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - writeLine(); - emitStart(specifier.name); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - emitEnd(specifier.name); - write(" = "); - emitExpressionIdentifier(name); - write(";"); - } - } - } - function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === ts.ModuleKind.System); - if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { - return; - } - writeLine(); - emitStart(specifier.name); - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write("\", "); - emitExpressionIdentifier(specifier.propertyName || specifier.name); - write(")"); - emitEnd(specifier.name); - write(";"); - } - /** - * Emit an assignment to a given identifier, 'name', with a given expression, 'value'. - * @param name an identifier as a left-hand-side operand of the assignment - * @param value an expression as a right-hand-side operand of the assignment - * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma - */ - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { - if (shouldEmitCommaBeforeAssignment) { - write(", "); - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(name); - write("\", "); - } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 218 /* VariableDeclaration */ || name.parent.kind === 169 /* BindingElement */); - // If this is first var declaration, we need to start at var/let/const keyword instead - // otherwise use nodeForSourceMap as the start position - emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); - withTemporaryNoSourceMap(function () { - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - }); - emitEnd(nodeForSourceMap, /*stopOverridingSpan*/ true); - if (exportChanged) { - write(")"); - } - } - /** - * Create temporary variable, emit an assignment of the variable the given expression - * @param expression an expression to assign to the newly created temporary variable - * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location - * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma - */ - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { - var identifier = createTempVariable(0 /* Auto */); - if (!canDefineTempVariablesInPlace) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); - return identifier; - } - function isFirstVariableDeclaration(root) { - return root.kind === 218 /* VariableDeclaration */ && - root.parent.kind === 219 /* VariableDeclarationList */ && - root.parent.declarations[0] === root; - } - function emitDestructuring(root, isAssignmentExpressionStatement, value) { - var emitCount = 0; - // An exported declaration is actually emitted as an assignment (to a property on the module object), so - // temporary variables in an exported declaration need to have real declarations elsewhere - // Also temporary variables should be explicitly allocated for source level declarations when module target is system - // because actual variable declarations are hoisted - var canDefineTempVariablesInPlace = false; - if (root.kind === 218 /* VariableDeclaration */) { - var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; - var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); - canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; - } - else if (root.kind === 142 /* Parameter */) { - canDefineTempVariablesInPlace = true; - } - if (root.kind === 187 /* BinaryExpression */) { - emitAssignmentExpression(root); - } - else { - ts.Debug.assert(!isAssignmentExpressionStatement); - // If first variable declaration of variable statement correct the start location - if (isFirstVariableDeclaration(root)) { - // Use emit location of "var " as next emit start entry - sourceMap.changeEmitSourcePos(); - } - emitBindingElement(root, value); - } - /** - * Ensures that there exists a declared identifier whose value holds the given expression. - * This function is useful to ensure that the expression's value can be read from in subsequent expressions. - * Unless 'reuseIdentifierExpressions' is false, 'expr' will be returned if it is just an identifier. - * - * @param expr the expression whose value needs to be bound. - * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; - * false if it is necessary to always emit an identifier. - */ - function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { - if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) { - return expr; - } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); - emitCount++; - return identifier; - } - function createDefaultValueCheck(value, defaultValue, sourceMapNode) { - // The value expression will be evaluated twice, so for anything but a simple identifier - // we need to generate a temporary variable - // If the temporary variable needs to be emitted use the source Map node for assignment of that statement - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); - // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(187 /* BinaryExpression */); - equals.left = value; - equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */); - equals.right = createVoidZero(); - return createConditionalExpression(equals, defaultValue, value); - } - function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(188 /* ConditionalExpression */); - cond.condition = condition; - cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); - cond.whenTrue = whenTrue; - cond.colonToken = ts.createSynthesizedNode(54 /* ColonToken */); - cond.whenFalse = whenFalse; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createSynthesizedNode(8 /* NumericLiteral */); - node.text = "" + value; - return node; - } - function createPropertyAccessForDestructuringProperty(object, propName) { - var index; - var nameIsComputed = propName.kind === 140 /* ComputedPropertyName */; - if (nameIsComputed) { - // TODO to handle when we look into sourcemaps for computed properties, for now use propName - index = ensureIdentifier(propName.expression, /*reuseIdentifierExpressions*/ false, propName); - } - else { - // We create a synthetic copy of the identifier in order to avoid the rewriting that might - // otherwise occur when the identifier is emitted. - index = ts.createSynthesizedNode(propName.kind); - // We need to unescape identifier here because when parsing an identifier prefixing with "__" - // the parser need to append "_" in order to escape colliding with magic identifiers such as "__proto__" - // Therefore, in order to correctly emit identifiers that are written in original TypeScript file, - // we will unescapeIdentifier to remove additional underscore (if no underscore is added, the function will return original input string) - index.text = ts.unescapeIdentifier(propName.text); - } - return !nameIsComputed && index.kind === 69 /* Identifier */ - ? createPropertyAccessExpression(object, index) - : createElementAccessExpression(object, index); - } - function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(174 /* CallExpression */); - var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); - sliceIdentifier.text = "slice"; - call.expression = createPropertyAccessExpression(value, sliceIdentifier); - call.arguments = ts.createSynthesizedNodeArray(); - call.arguments[0] = createNumericLiteral(sliceIndex); - return call; - } - function emitObjectLiteralAssignment(target, value, sourceMapNode) { - var properties = target.properties; - if (properties.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); - } - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var p = properties_5[_a]; - if (p.kind === 253 /* PropertyAssignment */ || p.kind === 254 /* ShorthandPropertyAssignment */) { - var propName = p.name; - var target_1 = p.kind === 254 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; - // Assignment for target = value.propName should highlight whole property, hence use p as source map node - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, sourceMapNode) { - var elements = target.elements; - if (elements.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 193 /* OmittedExpression */) { - // Assignment for target = value.propName should highlight whole property, hence use e as source map node - if (e.kind !== 191 /* SpreadElementExpression */) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); - } - else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); - } - } - } - } - function emitDestructuringAssignment(target, value, sourceMapNode) { - // When emitting target = value use source map node to highlight, including any temporary assignments needed for this - if (target.kind === 254 /* ShorthandPropertyAssignment */) { - if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); - } - target = target.name; - } - else if (target.kind === 187 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right, sourceMapNode); - target = target.left; - } - if (target.kind === 171 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value, sourceMapNode); - } - else if (target.kind === 170 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value, sourceMapNode); - } - else { - emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, sourceMapNode); - emitCount++; - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) { - emit(value); - } - else if (isAssignmentExpressionStatement) { - // Source map node for root.left = root.right is root - // but if root is synthetic, which could be in below case, use the target which is { a } - // for ({a} of {a: string}) { - // } - emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); - } - else { - if (root.parent.kind !== 178 /* ParenthesizedExpression */) { - write("("); - } - // Temporary assignment needed to emit root should highlight whole binary expression - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, root); - // Source map node for root.left = root.right is root - emitDestructuringAssignment(target, value, root); - write(", "); - emit(value); - if (root.parent.kind !== 178 /* ParenthesizedExpression */) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - // Any temporary assignments needed to emit target = value should point to target - if (target.initializer) { - // Combine value and initializer - value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; - } - else if (!value) { - // Use 'void 0' in absence of value and initializer - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - var numElements = elements.length; - if (numElements !== 1) { - // For anything other than a single-element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. Additionally, if we have zero elements - // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, - // so in that case, we'll intentionally create that temporary. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (pattern.kind === 167 /* ObjectBindingPattern */) { - // Rewrite element to a declaration with an initializer that fetches property - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); - } - else if (element.kind !== 193 /* OmittedExpression */) { - if (!element.dotDotDotToken) { - // Rewrite element to a declaration that accesses array element at index i - emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); - } - else if (i === numElements - 1) { - emitBindingElement(element, createSliceCall(value, i)); - } - } - } - } - else { - emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, target); - emitCount++; - } - } - } - function emitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name)) { - var isExported = ts.getCombinedNodeFlags(node) & 1 /* Export */; - if (languageVersion >= 2 /* ES6 */ && (!isExported || modulekind === ts.ModuleKind.ES6)) { - // emit ES6 destructuring only if target module is ES6 or variable is not exported - // exported variables in CJS/AMD are prefixed with 'exports.' so result javascript { exports.toString } = 1; is illegal - var isTopLevelDeclarationInSystemModule = modulekind === ts.ModuleKind.System && - shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); - if (isTopLevelDeclarationInSystemModule) { - // In System modules top level variables are hoisted - // so variable declarations with destructuring are turned into destructuring assignments. - // As a result, they will need parentheses to disambiguate object binding assignments from blocks. - write("("); - } - emit(node.name); - emitOptional(" = ", node.initializer); - if (isTopLevelDeclarationInSystemModule) { - write(")"); - } - } - else { - emitDestructuring(node, /*isAssignmentExpressionStatement*/ false); - } - } - else { - var initializer = node.initializer; - if (!initializer && - languageVersion < 2 /* ES6 */ && - // for names - binding patterns that lack initializer there is no point to emit explicit initializer - // since downlevel codegen for destructuring will fail in the absence of initializer so all binding elements will say uninitialized - node.name.kind === 69 /* Identifier */) { - var container = ts.getEnclosingBlockScopeContainer(node); - var flags = resolver.getNodeCheckFlags(node); - // nested let bindings might need to be initialized explicitly to preserve ES6 semantic - // { let x = 1; } - // { let x; } // x here should be undefined. not 1 - // NOTES: - // Top level bindings never collide with anything and thus don't require explicit initialization. - // As for nested let bindings there are two cases: - // - nested let bindings that were not renamed definitely should be initialized explicitly - // { let x = 1; } - // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } - // Without explicit initialization code in /*1*/ can be executed even if some-condition is evaluated to false - // - renaming introduces fresh name that should not collide with any existing names, however renamed bindings sometimes also should be - // explicitly initialized. One particular case: non-captured binding declared inside loop body (but not in loop initializer) - // let x; - // for (;;) { - // let x; - // } - // in downlevel codegen inner 'x' will be renamed so it won't collide with outer 'x' however it will should be reset on every iteration - // as if it was declared anew. - // * Why non-captured binding - because if loop contains block scoped binding captured in some function then loop body will be rewritten - // to have a fresh scope on every iteration so everything will just work. - // * Why loop initializer is excluded - since we've introduced a fresh name it already will be undefined. - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || - (isCapturedInFunction && isDeclaredInLoop && container.kind === 199 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false)); - var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 /* Let */ && - !emittedAsTopLevel; - var emitExplicitInitializer = emittedAsNestedLetDeclaration && - container.kind !== 207 /* ForInStatement */ && - container.kind !== 208 /* ForOfStatement */ && - (!resolver.isDeclarationWithCollidingName(node) || - (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, /*lookInLabeledStatements*/ false))); - if (emitExplicitInitializer) { - initializer = createVoidZero(); - } - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(node.name); - write("\", "); - } - emitModuleMemberName(node); - emitOptional(" = ", initializer); - if (exportChanged) { - write(")"); - } - } - } - function emitExportVariableAssignments(node) { - if (node.kind === 193 /* OmittedExpression */) { - return; - } - var name = node.name; - if (name.kind === 69 /* Identifier */) { - emitExportMemberAssignments(name); - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, emitExportVariableAssignments); - } - } - function isES6ExportedDeclaration(node) { - return !!(node.flags & 1 /* Export */) && - modulekind === ts.ModuleKind.ES6 && - node.parent.kind === 256 /* SourceFile */; - } - function emitVariableStatement(node) { - var startIsEmitted = false; - if (node.flags & 1 /* Export */) { - if (isES6ExportedDeclaration(node)) { - // Exported ES6 module member - write("export "); - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - } - else { - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - if (startIsEmitted) { - emitCommaList(node.declarationList.declarations); - write(";"); - } - else { - var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); - if (atLeastOneItem) { - write(";"); - } - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); - } - } - function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - // If we're not exporting the variables, there's nothing special here. - // Always emit comments for these nodes. - if (!(node.flags & 1 /* Export */)) { - return true; - } - // If we are exporting, but it's a top-level ES6 module exports, - // we'll emit the declaration list verbatim, so emit comments too. - if (isES6ExportedDeclaration(node)) { - return true; - } - // Otherwise, only emit if we have at least one initializer present. - for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { - var declaration = _b[_a]; - if (declaration.initializer) { - return true; - } - } - return false; - } - function emitParameter(node) { - if (languageVersion < 2 /* ES6 */) { - if (ts.isBindingPattern(node.name)) { - var name_29 = createTempVariable(0 /* Auto */); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name_29); - emit(name_29); - } - else { - emit(node.name); - } - } - else { - if (node.dotDotDotToken) { - write("..."); - } - emit(node.name); - emitOptional(" = ", node.initializer); - } - } - function emitDefaultValueAssignments(node) { - if (languageVersion < 2 /* ES6 */) { - var tempIndex_1 = 0; - ts.forEach(node.parameters, function (parameter) { - // A rest parameter cannot have a binding pattern or an initializer, - // so let's just ignore it. - if (parameter.dotDotDotToken) { - return; - } - var paramName = parameter.name, initializer = parameter.initializer; - if (ts.isBindingPattern(paramName)) { - // In cases where a binding pattern is simply '[]' or '{}', - // we usually don't want to emit a var declaration; however, in the presence - // of an initializer, we must emit that expression to preserve side effects. - var hasBindingElements = paramName.elements.length > 0; - if (hasBindingElements || initializer) { - writeLine(); - write("var "); - if (hasBindingElements) { - emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex_1]); - } - else { - emit(tempParameters[tempIndex_1]); - write(" = "); - emit(initializer); - } - write(";"); - } - // Regardless of whether we will emit a var declaration for the binding pattern, we generate the temporary - // variable for the parameter (see: emitParameter) - tempIndex_1++; - } - else if (initializer) { - writeLine(); - emitStart(parameter); - write("if ("); - emitNodeWithoutSourceMap(paramName); - write(" === void 0)"); - emitEnd(parameter); - write(" { "); - emitStart(parameter); - emitNodeWithCommentsAndWithoutSourcemap(paramName); - write(" = "); - emitNodeWithCommentsAndWithoutSourcemap(initializer); - emitEnd(parameter); - write("; }"); - } - }); - } - } - function emitRestParameter(node) { - if (languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. - if (ts.isBindingPattern(restParam.name)) { - return; - } - var tempName = createTempVariable(268435456 /* _i */).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - write(node.kind === 149 /* GetAccessor */ ? "get " : "set "); - emit(node.name); - emitSignatureAndBody(node); - } - function shouldEmitAsArrowFunction(node) { - return node.kind === 180 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; - } - function emitDeclarationName(node) { - if (node.name) { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - else { - write(getGeneratedNameForNode(node)); - } - } - function shouldEmitFunctionName(node) { - if (node.kind === 179 /* FunctionExpression */) { - // Emit name if one is present - return !!node.name; - } - if (node.kind === 220 /* FunctionDeclaration */) { - // Emit name if one is present, or emit generated name in down-level case (for export default case) - return !!node.name || modulekind !== ts.ModuleKind.ES6; - } - } - function emitFunctionDeclaration(node) { - if (ts.nodeIsMissing(node.body)) { - return emitCommentsOnNotEmittedNode(node); - } - // TODO (yuisu) : we should not have special cases to condition emitting comments - // but have one place to fix check for these conditions. - var kind = node.kind, parent = node.parent; - if (kind !== 147 /* MethodDeclaration */ && - kind !== 146 /* MethodSignature */ && - parent && - parent.kind !== 253 /* PropertyAssignment */ && - parent.kind !== 174 /* CallExpression */ && - parent.kind !== 170 /* ArrayLiteralExpression */) { - // 1. Methods will emit comments at their assignment declaration sites. - // - // 2. If the function is a property of object literal, emitting leading-comments - // is done by emitNodeWithoutSourceMap which then call this function. - // In particular, we would like to avoid emit comments twice in following case: - // - // var obj = { - // id: - // /*comment*/ () => void - // } - // - // 3. If the function is an argument in call expression, emitting of comments will be - // taken care of in emit list of arguments inside of 'emitCallExpression'. - // - // 4. If the function is in an array literal, 'emitLinePreservingList' will take care - // of leading comments. - emitLeadingComments(node); - } - emitStart(node); - // For targeting below es6, emit functions-like declaration including arrow function using function keyword. - // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead - if (!shouldEmitAsArrowFunction(node)) { - if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512 /* Default */) { - write("default "); - } - } - write("function"); - if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { - write("*"); - } - write(" "); - } - if (shouldEmitFunctionName(node)) { - emitDeclarationName(node); - } - emitSignatureAndBody(node); - if (modulekind !== ts.ModuleKind.ES6 && kind === 220 /* FunctionDeclaration */ && parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - emitEnd(node); - if (kind !== 147 /* MethodDeclaration */ && - kind !== 146 /* MethodSignature */ && - kind !== 180 /* ArrowFunction */) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; - var omitCount = languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node) ? 1 : 0; - emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false); - } - write(")"); - decreaseIndent(); - } - function emitSignatureParametersForArrow(node) { - // Check whether the parameter list needs parentheses and preserve no-parenthesis - if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { - emit(node.parameters[0]); - return; - } - emitSignatureParameters(node); - } - function emitAsyncFunctionBodyForES6(node) { - var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 180 /* ArrowFunction */; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; - // An async function is emit as an outer function that calls an inner - // generator function. To preserve lexical bindings, we pass the current - // `this` and `arguments` objects to `__awaiter`. The generator function - // passed to `__awaiter` is executed inside of the callback to the - // promise constructor. - // - // The emit for an async arrow without a lexical `arguments` binding might be: - // - // // input - // let a = async (b) => { await b; } - // - // // output - // let a = (b) => __awaiter(this, void 0, void 0, function* () { - // yield b; - // }); - // - // The emit for an async arrow with a lexical `arguments` binding might be: - // - // // input - // let a = async (b) => { await arguments[0]; } - // - // // output - // let a = (b) => __awaiter(this, arguments, void 0, function* (arguments) { - // yield arguments[0]; - // }); - // - // The emit for an async function expression without a lexical `arguments` binding - // might be: - // - // // input - // let a = async function (b) { - // await b; - // } - // - // // output - // let a = function (b) { - // return __awaiter(this, void 0, void 0, function* () { - // yield b; - // }); - // } - // - // The emit for an async function expression with a lexical `arguments` binding - // might be: - // - // // input - // let a = async function (b) { - // await arguments[0]; - // } - // - // // output - // let a = function (b) { - // return __awaiter(this, arguments, void 0, function* (_arguments) { - // yield _arguments[0]; - // }); - // } - // - // The emit for an async function expression with a lexical `arguments` binding - // and a return type annotation might be: - // - // // input - // let a = async function (b): MyPromise { - // await arguments[0]; - // } - // - // // output - // let a = function (b) { - // return __awaiter(this, arguments, MyPromise, function* (_arguments) { - // yield _arguments[0]; - // }); - // } - // - // If this is not an async arrow, emit the opening brace of the function body - // and the start of the return statement. - if (!isArrowFunction) { - write(" {"); - increaseIndent(); - writeLine(); - if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); - writeLine(); - } - else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - write("const _super = name => super[name];"); - writeLine(); - } - write("return"); - } - write(" __awaiter(this"); - if (hasLexicalArguments) { - write(", arguments, "); - } - else { - write(", void 0, "); - } - if (languageVersion >= 2 /* ES6 */ || !promiseConstructor) { - write("void 0"); - } - else { - emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false); - } - // Emit the call to __awaiter. - write(", function* ()"); - // Emit the signature and body for the inner generator function. - emitFunctionBody(node); - write(")"); - // If this is not an async arrow, emit the closing brace of the outer function body. - if (!isArrowFunction) { - write(";"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitFunctionBody(node) { - if (!node.body) { - // There can be no body when there are parse errors. Just emit an empty block - // in that case. - write(" { }"); - } - else { - if (node.body.kind === 199 /* Block */) { - emitBlockFunctionBody(node, node.body); - } - else { - emitExpressionFunctionBody(node, node.body); - } - } - } - function emitSignatureAndBody(node) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - // When targeting ES6, emit arrow function natively in ES6 - if (shouldEmitAsArrowFunction(node)) { - emitSignatureParametersForArrow(node); - write(" =>"); - } - else { - emitSignatureParameters(node); - } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAsyncFunctionBodyForES6(node); - } - else { - emitFunctionBody(node); - } - if (!isES6ExportedDeclaration(node)) { - emitExportMemberAssignment(node); - } - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - // Returns true if any preamble code was emitted. - function emitFunctionBodyPreamble(node) { - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - } - function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 /* ES6 */ || node.flags & 256 /* Async */) { - emitDownLevelExpressionFunctionBody(node, body); - return; - } - // For es6 and higher we can emit the expression as is. However, in the case - // where the expression might end up looking like a block when emitted, we'll - // also wrap it in parentheses first. For example if you have: a => {} - // then we need to generate: a => ({}) - write(" "); - // Unwrap all type assertions. - var current = body; - while (current.kind === 177 /* TypeAssertionExpression */) { - current = current.expression; - } - emitParenthesizedIf(body, current.kind === 171 /* ObjectLiteralExpression */); - } - function emitDownLevelExpressionFunctionBody(node, body) { - write(" {"); - increaseIndent(); - var outPos = writer.getTextPos(); - emitDetachedCommentsAndUpdateCommentsInfo(node.body); - emitFunctionBodyPreamble(node); - var preambleEmitted = writer.getTextPos() !== outPos; - decreaseIndent(); - // If we didn't have to emit any preamble code, then attempt to keep the arrow - // function on one line. - if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) { - write(" "); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTempDeclarations(/*newLine*/ false); - write(" "); - } - else { - increaseIndent(); - writeLine(); - emitLeadingComments(node.body); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTrailingComments(node.body); - emitTempDeclarations(/*newLine*/ true); - decreaseIndent(); - writeLine(); - } - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - function emitBlockFunctionBody(node, body) { - write(" {"); - var initialTextPos = writer.getTextPos(); - increaseIndent(); - emitDetachedCommentsAndUpdateCommentsInfo(body.statements); - // Emit all the directive prologues (like "use strict"). These have to come before - // any other preamble code we write (like parameter initializers). - var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); - emitFunctionBodyPreamble(node); - decreaseIndent(); - var preambleEmitted = writer.getTextPos() !== initialTextPos; - if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { - var statement = _b[_a]; - write(" "); - emit(statement); - } - emitTempDeclarations(/*newLine*/ false); - write(" "); - emitLeadingCommentsOfPosition(body.statements.end); - } - else { - increaseIndent(); - emitLinesStartingAt(body.statements, startIndex); - emitTempDeclarations(/*newLine*/ true); - writeLine(); - emitLeadingCommentsOfPosition(body.statements.end); - decreaseIndent(); - } - emitToken(16 /* CloseBraceToken */, body.statements.end); - } - /** - * Return the statement at a given index if it is a super-call statement - * @param ctor a constructor declaration - * @param index an index to constructor's body to check - */ - function getSuperCallAtGivenIndex(ctor, index) { - if (!ctor.body) { - return undefined; - } - var statements = ctor.body.statements; - if (!statements || index >= statements.length) { - return undefined; - } - var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */) { - return ts.isSuperCallExpression(statement.expression) ? statement : undefined; - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 92 /* ParameterPropertyModifier */) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNodeWithoutSourceMap(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - // This does not emit source map because it is emitted by caller as caller - // is aware how the property name changes to the property access - // eg. public x = 10; becomes this.x and static x = 10 becomes className.x - if (memberName.kind === 9 /* StringLiteral */ || memberName.kind === 8 /* NumericLiteral */) { - write("["); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - write("]"); - } - else if (memberName.kind === 140 /* ComputedPropertyName */) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - } - } - function getInitializedProperties(node, isStatic) { - var properties = []; - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 145 /* PropertyDeclaration */ && isStatic === ((member.flags & 32 /* Static */) !== 0) && member.initializer) { - properties.push(member); - } - } - return properties; - } - function emitPropertyDeclarations(node, properties) { - for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { - var property = properties_6[_a]; - emitPropertyDeclaration(node, property); - } - } - function emitPropertyDeclaration(node, property, receiver, isExpression) { - writeLine(); - emitLeadingComments(property); - emitStart(property); - emitStart(property.name); - if (receiver) { - write(receiver); - } - else { - if (property.flags & 32 /* Static */) { - emitDeclarationName(node); - } - else { - write("this"); - } - } - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - emit(property.initializer); - if (!isExpression) { - write(";"); - } - emitEnd(property); - emitTrailingComments(property); - } - function emitMemberFunctionsForES5AndLower(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 198 /* SemicolonClassElement */) { - writeLine(); - write(";"); - } - else if (member.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) { - if (!member.body) { - return emitCommentsOnNotEmittedNode(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitClassMemberPrefix(node, member); - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitFunctionDeclaration(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 149 /* GetAccessor */ || member.kind === 150 /* SetAccessor */) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitMemberFunctionsForES6AndHigher(node) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - else if (member.kind === 147 /* MethodDeclaration */ || - member.kind === 149 /* GetAccessor */ || - member.kind === 150 /* SetAccessor */) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - if (member.flags & 32 /* Static */) { - write("static "); - } - if (member.kind === 149 /* GetAccessor */) { - write("get "); - } - else if (member.kind === 150 /* SetAccessor */) { - write("set "); - } - if (member.asteriskToken) { - write("*"); - } - emit(member.name); - emitSignatureAndBody(member); - emitEnd(member); - emitTrailingComments(member); - } - else if (member.kind === 198 /* SemicolonClassElement */) { - writeLine(); - write(";"); - } - } - } - function emitConstructor(node, baseTypeElement) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - emitConstructorWorker(node, baseTypeElement); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitConstructorWorker(node, baseTypeElement) { - // 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 - var hasInstancePropertyWithInitializer = false; - // Emit the constructor overload pinned comments - ts.forEach(node.members, function (member) { - if (member.kind === 148 /* Constructor */ && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - // Check if there is any non-static property assignment - if (member.kind === 145 /* PropertyDeclaration */ && member.initializer && (member.flags & 32 /* Static */) === 0) { - hasInstancePropertyWithInitializer = true; - } - }); - var ctor = ts.getFirstConstructorWithBody(node); - // For target ES6 and above, if there is no user-defined constructor and there is no property assignment - // do not emit constructor in class declaration. - if (languageVersion >= 2 /* ES6 */ && !ctor && !hasInstancePropertyWithInitializer) { - return; - } - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - if (languageVersion < 2 /* ES6 */) { - write("function "); - emitDeclarationName(node); - emitSignatureParameters(ctor); - } - else { - write("constructor"); - if (ctor) { - emitSignatureParameters(ctor); - } - else { - // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation. - // If constructor is empty, then, - // If ClassHeritageopt is present, then - // Let constructor be the result of parsing the String "constructor(... args){ super (...args);}" using the syntactic grammar with the goal symbol MethodDefinition. - // Else, - // Let constructor be the result of parsing the String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } - } - } - var startIndex = 0; - write(" {"); - increaseIndent(); - if (ctor) { - // Emit all the directive prologues (like "use strict"). These have to come before - // any other preamble code we write (like parameter initializers). - startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true); - emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - var superCall; - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeElement) { - superCall = getSuperCallAtGivenIndex(ctor, startIndex); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeElement) { - writeLine(); - emitStart(baseTypeElement); - if (languageVersion < 2 /* ES6 */) { - write("_super.apply(this, arguments);"); - } - else { - write("super(...args);"); - } - emitEnd(baseTypeElement); - } - } - emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false)); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) { - statements = statements.slice(1); - } - emitLinesStartingAt(statements, startIndex); - } - emitTempDeclarations(/*newLine*/ true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - } - function emitClassExpression(node) { - return emitClassLikeDeclaration(node); - } - function emitClassDeclaration(node) { - return emitClassLikeDeclaration(node); - } - function emitClassLikeDeclaration(node) { - if (languageVersion < 2 /* ES6 */) { - emitClassLikeDeclarationBelowES6(node); - } - else { - emitClassLikeDeclarationForES6AndHigher(node); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - } - function emitClassLikeDeclarationForES6AndHigher(node) { - var decoratedClassAlias; - var isHoistedDeclarationInSystemModule = shouldHoistDeclarationInSystemJsModule(node); - var isDecorated = ts.nodeIsDecorated(node); - var rewriteAsClassExpression = isDecorated || isHoistedDeclarationInSystemModule; - if (node.kind === 221 /* ClassDeclaration */) { - if (rewriteAsClassExpression) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------|------------------------------------ - // @dec | export let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // [Example 1] - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); - // --------------------------------|------------------------------------ - // @dec | let C_1 = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | export let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); - // --------------------------------------------------------------------- - // [Example 2] - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------|------------------------------------ - // @dec | let C = class C { - // export default class { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // [Example 3] - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let C_1 = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | }; - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // [Example 4] - // - // NOTE: we reuse the same rewriting logic for cases when targeting ES6 and module kind is System. - // Because of hoisting top level class declaration need to be emitted as class expressions. - // Double bind case is only required if node is decorated. - if (isDecorated && resolver.getNodeCheckFlags(node) & 524288 /* ClassWithBodyScopedClassBinding */) { - decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); - decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; - } - if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) { - write("export "); - } - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } - if (decoratedClassAlias !== undefined) { - write("" + decoratedClassAlias); - } - else { - emitDeclarationName(node); - } - write(" = "); - } - else if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512 /* Default */) { - write("default "); - } - } - } - // If the class has static properties, and it's a class expression, then we'll need - // to specialize the emit a bit. for a class expression of the form: - // - // class C { static a = 1; static b = 2; ... } - // - // We'll emit: - // - // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp) - // - // This keeps the expression as an expression, while ensuring that the static parts - // of it have been initialized by the time it is used. - var staticProperties = getInitializedProperties(node, /*isStatic*/ true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192 /* ClassExpression */; - var generatedName; - if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); - var synthesizedNode = ts.createSynthesizedNode(69 /* Identifier */); - synthesizedNode.text = generatedName; - recordTempDeclaration(synthesizedNode); - write("("); - increaseIndent(); - emit(synthesizedNode); - write(" = "); - } - write("class"); - // emit name if - // - node has a name - // - this is default export with static initializers - if (node.name || (node.flags & 512 /* Default */ && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !rewriteAsClassExpression)) { - write(" "); - emitDeclarationName(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write(" extends "); - emit(baseTypeNode.expression); - } - write(" {"); - increaseIndent(); - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES6AndHigher(node); - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end); - if (rewriteAsClassExpression) { - if (decoratedClassAlias !== undefined) { - write(";"); - writeLine(); - if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */)) { - write("export "); - } - write("let "); - emitDeclarationName(node); - write(" = " + decoratedClassAlias); - } - decoratedClassAliases[ts.getNodeId(node)] = undefined; - write(";"); - } - // Emit static property assignment. Because classDeclaration is lexically evaluated, - // it is safe to emit static property assignment after classDeclaration - // From ES6 specification: - // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using - // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - if (isClassExpressionWithStaticProperties) { - for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { - var property = staticProperties_1[_a]; - write(","); - writeLine(); - emitPropertyDeclaration(node, property, /*receiver*/ generatedName, /*isExpression*/ true); - } - write(","); - writeLine(); - write(generatedName); - decreaseIndent(); - write(")"); - } - else { - writeLine(); - emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node, decoratedClassAlias); - } - if (!(node.flags & 1 /* Export */)) { - return; - } - if (modulekind !== ts.ModuleKind.ES6) { - emitExportMemberAssignment(node); - } - else { - // If this is an exported class, but not on the top level (i.e. on an internal - // module), export it - if (node.flags & 512 /* Default */) { - // if this is a top level default export of decorated class, write the export after the declaration. - if (isDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - else if (node.parent.kind !== 256 /* SourceFile */) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); - } - } - } - function emitClassLikeDeclarationBelowES6(node) { - var isES6ExportedClass = isES6ExportedDeclaration(node); - if (node.kind === 221 /* ClassDeclaration */) { - if (isES6ExportedClass && !(node.flags & 512 /* Default */)) { - write("export "); - } - // source file level classes in system modules are hoisted so 'var's for them are already defined - if (!shouldHoistDeclarationInSystemJsModule(node)) { - write("var "); - } - emitDeclarationName(node); - write(" = "); - } - write("(function ("); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - var saveConvertedLoopState = convertedLoopState; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - computedPropertyNamesToGeneratedNames = undefined; - increaseIndent(); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emitDeclarationName(node); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true)); - writeLine(); - emitDecoratorsOfClass(node, /*decoratedClassAlias*/ undefined); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end, function () { - write("return "); - emitDeclarationName(node); - }); - write(";"); - emitTempDeclarations(/*newLine*/ true); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames; - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end); - emitStart(node); - write("("); - if (baseTypeNode) { - emit(baseTypeNode.expression); - } - write("))"); - if (node.kind === 221 /* ClassDeclaration */) { - write(";"); - } - emitEnd(node); - if (node.kind === 221 /* ClassDeclaration */ && !isES6ExportedClass) { - emitExportMemberAssignment(node); - } - else if (isES6ExportedClass && (node.flags & 512 /* Default */)) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - function emitClassMemberPrefix(node, member) { - emitDeclarationName(node); - if (!(member.flags & 32 /* Static */)) { - write(".prototype"); - } - } - function emitDecoratorsOfClass(node, decoratedClassAlias) { - emitDecoratorsOfMembers(node, /*staticFlag*/ 0); - emitDecoratorsOfMembers(node, 32 /* Static */); - emitDecoratorsOfConstructor(node, decoratedClassAlias); - } - function emitDecoratorsOfConstructor(node, decoratedClassAlias) { - var decorators = node.decorators; - var constructor = ts.getFirstConstructorWithBody(node); - var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); - // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !firstParameterDecorator) { - return; - } - // Emit the call to __decorate. Given the class: - // - // @dec - // class C { - // } - // - // The emit for the class is: - // - // C = __decorate([dec], C); - // - writeLine(); - emitStart(node.decorators || firstParameterDecorator); - emitDeclarationName(node); - if (decoratedClassAlias !== undefined) { - write(" = " + decoratedClassAlias); - } - write(" = __decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); - } - emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); - decreaseIndent(); - writeLine(); - write("], "); - emitDeclarationName(node); - write(")"); - emitEnd(node.decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - function emitDecoratorsOfMembers(node, staticFlag) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - // only emit members in the correct group - if ((member.flags & 32 /* Static */) !== staticFlag) { - continue; - } - // skip members that cannot be decorated (such as the constructor) - if (!ts.nodeCanBeDecorated(member)) { - continue; - } - // skip an accessor declaration if it is not the first accessor - var decorators = void 0; - var functionLikeMember = void 0; - if (ts.isAccessor(member)) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member !== accessors.firstAccessor) { - continue; - } - // get the decorators from the first accessor with decorators - decorators = accessors.firstAccessor.decorators; - if (!decorators && accessors.secondAccessor) { - decorators = accessors.secondAccessor.decorators; - } - // we only decorate parameters of the set accessor - functionLikeMember = accessors.setAccessor; - } - else { - decorators = member.decorators; - // we only decorate the parameters here if this is a method - if (member.kind === 147 /* MethodDeclaration */) { - functionLikeMember = member; - } - } - var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); - // skip a member if it or any of its parameters are not decorated - if (!decorators && !firstParameterDecorator) { - continue; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", undefined); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", undefined); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - writeLine(); - emitStart(decorators || firstParameterDecorator); - write("__decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); - } - emitSerializedTypeMetadata(member, argumentsWritten > 0); - decreaseIndent(); - writeLine(); - write("], "); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - if (languageVersion > 0 /* ES3 */) { - if (member.kind !== 145 /* PropertyDeclaration */) { - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - write(", null"); - } - else { - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - write(", void 0"); - } - } - write(")"); - emitEnd(decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - } - function emitDecoratorsOfParameters(node, leadingComma) { - var argumentsWritten = 0; - if (node) { - var parameterIndex_1 = 0; - for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { - var parameter = _b[_a]; - if (ts.nodeIsDecorated(parameter)) { - var decorators = parameter.decorators; - argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) { - write("__param(" + parameterIndex_1 + ", "); - emit(decorator.expression); - write(")"); - }); - leadingComma = true; - } - parameterIndex_1++; - } - } - return argumentsWritten; - } - function shouldEmitTypeMetadata(node) { - // This method determines whether to emit the "design:type" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 145 /* PropertyDeclaration */: - return true; - } - return false; - } - function shouldEmitReturnTypeMetadata(node) { - // This method determines whether to emit the "design:returntype" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 147 /* MethodDeclaration */: - return true; - } - return false; - } - function shouldEmitParamTypesMetadata(node) { - // This method determines whether to emit the "design:paramtypes" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 221 /* ClassDeclaration */: - case 147 /* MethodDeclaration */: - case 150 /* SetAccessor */: - return true; - } - return false; - } - /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */ - function emitSerializedTypeOfNode(node) { - // serialization of the type of a declaration uses the following rules: - // - // * The serialized type of a ClassDeclaration is "Function" - // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation. - // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation. - // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter. - // * The serialized type of any other FunctionLikeDeclaration is "Function". - // * The serialized type of any other node is "void 0". - // - // For rules on serializing type annotations, see `serializeTypeNode`. - switch (node.kind) { - case 221 /* ClassDeclaration */: - write("Function"); - return; - case 145 /* PropertyDeclaration */: - emitSerializedTypeNode(node.type); - return; - case 142 /* Parameter */: - emitSerializedTypeNode(node.type); - return; - case 149 /* GetAccessor */: - emitSerializedTypeNode(node.type); - return; - case 150 /* SetAccessor */: - emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - return; - } - if (ts.isFunctionLike(node)) { - write("Function"); - return; - } - write("void 0"); - } - function emitSerializedTypeNode(node) { - if (node) { - switch (node.kind) { - case 103 /* VoidKeyword */: - write("void 0"); - return; - case 164 /* ParenthesizedType */: - emitSerializedTypeNode(node.type); - return; - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - write("Function"); - return; - case 160 /* ArrayType */: - case 161 /* TupleType */: - write("Array"); - return; - case 154 /* TypePredicate */: - case 120 /* BooleanKeyword */: - write("Boolean"); - return; - case 132 /* StringKeyword */: - case 166 /* StringLiteralType */: - write("String"); - return; - case 130 /* NumberKeyword */: - write("Number"); - return; - case 133 /* SymbolKeyword */: - write("Symbol"); - return; - case 155 /* TypeReference */: - emitSerializedTypeReferenceNode(node); - return; - case 158 /* TypeQuery */: - case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 117 /* AnyKeyword */: - case 165 /* ThisType */: - break; - default: - ts.Debug.fail("Cannot serialize unexpected type node."); - break; - } - } - write("Object"); - } - /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function emitSerializedTypeReferenceNode(node) { - var location = node.parent; - while (ts.isDeclaration(location) || ts.isTypeNode(location)) { - location = location.parent; - } - // Clone the type name and parent it to a location outside of the current declaration. - var typeName = ts.cloneEntityName(node.typeName, location); - var result = resolver.getTypeReferenceSerializationKind(typeName); - switch (result) { - case ts.TypeReferenceSerializationKind.Unknown: - var temp = createAndRecordTempVariable(0 /* Auto */); - write("(typeof ("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(typeName, /*useFallback*/ true); - write(") === 'function' && "); - emitNodeWithoutSourceMap(temp); - write(") || Object"); - break; - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - emitEntityNameAsExpression(typeName, /*useFallback*/ false); - break; - case ts.TypeReferenceSerializationKind.VoidType: - write("void 0"); - break; - case ts.TypeReferenceSerializationKind.BooleanType: - write("Boolean"); - break; - case ts.TypeReferenceSerializationKind.NumberLikeType: - write("Number"); - break; - case ts.TypeReferenceSerializationKind.StringLikeType: - write("String"); - break; - case ts.TypeReferenceSerializationKind.ArrayLikeType: - write("Array"); - break; - case ts.TypeReferenceSerializationKind.ESSymbolType: - if (languageVersion < 2 /* ES6 */) { - write("typeof Symbol === 'function' ? Symbol : Object"); - } - else { - write("Symbol"); - } - break; - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - write("Function"); - break; - case ts.TypeReferenceSerializationKind.ObjectType: - write("Object"); - break; - } - } - /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ - function emitSerializedParameterTypesOfNode(node) { - // serialization of parameter types uses the following rules: - // - // * If the declaration is a class, the parameters of the first constructor with a body are used. - // * If the declaration is function-like and has a body, the parameters of the function are used. - // - // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. - if (node) { - var valueDeclaration = void 0; - if (node.kind === 221 /* ClassDeclaration */) { - valueDeclaration = ts.getFirstConstructorWithBody(node); - } - else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { - valueDeclaration = node; - } - if (valueDeclaration) { - var parameters = valueDeclaration.parameters; - var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { - write(", "); - } - if (parameters[i].dotDotDotToken) { - var parameterType = parameters[i].type; - if (parameterType && parameterType.kind === 160 /* ArrayType */) { - parameterType = parameterType.elementType; - } - else if (parameterType && parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { - parameterType = parameterType.typeArguments[0]; - } - else { - parameterType = undefined; - } - emitSerializedTypeNode(parameterType); - } - else { - emitSerializedTypeOfNode(parameters[i]); - } - } - } - } - } - } - /** Serializes the return type of function. Used by the __metadata decorator for a method. */ - function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node)) { - if (node.type) { - emitSerializedTypeNode(node.type); - return; - } - else if (ts.isAsyncFunctionLike(node)) { - write("Promise"); - return; - } - } - write("void 0"); - } - function emitSerializedTypeMetadata(node, writeComma) { - // This method emits the serialized type metadata for a decorator target. - // The caller should have already tested whether the node has decorators. - var argumentsWritten = 0; - if (compilerOptions.emitDecoratorMetadata) { - if (shouldEmitTypeMetadata(node)) { - if (writeComma) { - write(", "); - } - writeLine(); - write("__metadata('design:type', "); - emitSerializedTypeOfNode(node); - write(")"); - argumentsWritten++; - } - if (shouldEmitParamTypesMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:paramtypes', ["); - emitSerializedParameterTypesOfNode(node); - write("])"); - argumentsWritten++; - } - if (shouldEmitReturnTypeMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:returntype', "); - emitSerializedReturnTypeOfNode(node); - write(")"); - argumentsWritten++; - } - } - return argumentsWritten; - } - function emitInterfaceDeclaration(node) { - emitCommentsOnNotEmittedNode(node); - } - function shouldEmitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; - } - function emitEnumDeclaration(node) { - // const enums are completely erased during compilation. - if (!shouldEmitEnumDeclaration(node)) { - return; - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - // do not emit var if variable was already hoisted - var isES6ExportedEnum = isES6ExportedDeclaration(node); - if (!(node.flags & 1 /* Export */) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 224 /* EnumDeclaration */))) { - emitStart(node); - if (isES6ExportedEnum) { - write("export "); - } - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { - // do not emit var if variable was already hoisted - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { - // write the call to exporter for enum - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function emitEnumMember(node) { - var enumParent = node.parent; - emitStart(node); - write(getGeneratedNameForNode(enumParent)); - write("["); - write(getGeneratedNameForNode(enumParent)); - write("["); - emitExpressionForPropertyName(node.name); - write("] = "); - writeEnumMemberDeclarationValue(node); - write("] = "); - emitExpressionForPropertyName(node.name); - emitEnd(node); - write(";"); - } - function writeEnumMemberDeclarationValue(member) { - var value = resolver.getConstantValue(member); - if (value !== undefined) { - write(value.toString()); - return; - } - else if (member.initializer) { - emit(member.initializer); - } - else { - write("undefined"); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); - } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); - } - function isFirstDeclarationOfKind(node, declarations, kind) { - return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); - } - function emitModuleDeclaration(node) { - // Emit only if this module is non-ambient. - var shouldEmit = shouldEmitModuleDeclaration(node); - if (!shouldEmit) { - return emitCommentsOnNotEmittedNode(node); - } - var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); - var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); - if (emitVarForModule) { - var isES6ExportedNamespace = isES6ExportedDeclaration(node); - if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 225 /* ModuleDeclaration */)) { - emitStart(node); - if (isES6ExportedNamespace) { - write("export "); - } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - } - } - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") "); - ts.Debug.assert(node.body !== undefined); // node.body must exist, as this is a non-ambient module - if (node.body.kind === 226 /* ModuleBlock */) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - emit(node.body); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end); - } - write(")("); - // write moduleDecl = containingModule.m only if it is not exported es6 module member - if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - /* - * Some bundlers (SystemJS builder) sometimes want to rename dependencies. - * Here we check if alternative name was provided for a given moduleName and return it if possible. - */ - function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { - return "\"" + renamedDependencies[moduleName.text] + "\""; - } - return undefined; - } - function emitRequire(moduleName) { - if (moduleName.kind === 9 /* StringLiteral */) { - write("require("); - var text = tryRenameExternalModule(moduleName); - if (text) { - write(text); - } - else { - emitStart(moduleName); - emitLiteral(moduleName); - emitEnd(moduleName); - } - emitToken(18 /* CloseParenToken */, moduleName.end); - } - else { - write("require()"); - } - } - function getNamespaceDeclarationNode(node) { - if (node.kind === 229 /* ImportEqualsDeclaration */) { - return node; - } - var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232 /* NamespaceImport */) { - return importClause.namedBindings; - } - } - function isDefaultImport(node) { - return node.kind === 230 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; - } - function emitExportImportAssignments(node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - emitExportMemberAssignments(node.name); - } - ts.forEachChild(node, emitExportImportAssignments); - } - function emitImportDeclaration(node) { - if (modulekind !== ts.ModuleKind.ES6) { - return emitExternalImportDeclaration(node); - } - // ES6 import - if (node.importClause) { - var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true); - if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { - write("import "); - emitStart(node.importClause); - if (shouldEmitDefaultBindings) { - emit(node.importClause.name); - if (shouldEmitNamedBindings) { - write(", "); - } - } - if (shouldEmitNamedBindings) { - emitLeadingComments(node.importClause.namedBindings); - emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 232 /* NamespaceImport */) { - write("* as "); - emit(node.importClause.namedBindings.name); - } - else { - write("{ "); - emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration); - write(" }"); - } - emitEnd(node.importClause.namedBindings); - emitTrailingComments(node.importClause.namedBindings); - } - emitEnd(node.importClause); - write(" from "); - emit(node.moduleSpecifier); - write(";"); - } - } - else { - write("import "); - emit(node.moduleSpecifier); - write(";"); - } - } - function emitExternalImportDeclaration(node) { - if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 229 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; - var namespaceDeclaration = getNamespaceDeclarationNode(node); - var varOrConst = (languageVersion <= 1 /* ES5 */) ? "var " : "const "; - if (modulekind !== ts.ModuleKind.AMD) { - emitLeadingComments(node); - emitStart(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - // import x = require("foo") - // import * as x from "foo" - if (!isExportedImport) { - write(varOrConst); - } - ; - emitModuleMemberName(namespaceDeclaration); - write(" = "); - } - else { - // import "foo" - // import x from "foo" - // import { x, y } from "foo" - // import d, * as x from "foo" - // import d, { x, y } from "foo" - var isNakedImport = 230 /* ImportDeclaration */ && !node.importClause; - if (!isNakedImport) { - write(varOrConst); - write(getGeneratedNameForNode(node)); - write(" = "); - } - } - emitRequire(ts.getExternalModuleName(node)); - if (namespaceDeclaration && isDefaultImport(node)) { - // import d, * as x from "foo" - write(", "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - else { - if (isExportedImport) { - emitModuleMemberName(namespaceDeclaration); - write(" = "); - emit(namespaceDeclaration.name); - write(";"); - } - else if (namespaceDeclaration && isDefaultImport(node)) { - // import d, * as x from "foo" - write(varOrConst); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - write(";"); - } - emitExportImportAssignments(node); - } - } - } - function emitImportEqualsDeclaration(node) { - if (ts.isExternalModuleImportEqualsDeclaration(node)) { - emitExternalImportDeclaration(node); - return; - } - // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when - // - current file is not external module - // - import declaration is top level and target is value imported by entity name - if (resolver.isReferencedAliasDeclaration(node) || - (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { - emitLeadingComments(node); - emitStart(node); - // variable declaration for import-equals declaration can be hoisted in system modules - // in this case 'var' should be omitted and emit should contain only initialization - var variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); - // is it top level export import v = a.b.c in system module? - // if yes - it needs to be rewritten as exporter('v', v = a.b.c) - var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); - if (!variableDeclarationIsHoisted) { - ts.Debug.assert(!isExported); - if (isES6ExportedDeclaration(node)) { - write("export "); - write("var "); - } - else if (!(node.flags & 1 /* Export */)) { - write("var "); - } - } - if (isExported) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.name); - write("\", "); - } - emitModuleMemberName(node); - write(" = "); - emit(node.moduleReference); - if (isExported) { - write(")"); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - } - function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== ts.ModuleKind.System); - if (modulekind !== ts.ModuleKind.ES6) { - if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { - emitStart(node); - var generatedName = getGeneratedNameForNode(node); - if (node.exportClause) { - // export { x, y, ... } from "foo" - if (modulekind !== ts.ModuleKind.AMD) { - write("var "); - write(generatedName); - write(" = "); - emitRequire(ts.getExternalModuleName(node)); - write(";"); - } - for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) { - var specifier = _b[_a]; - if (resolver.isValueAliasDeclaration(specifier)) { - writeLine(); - emitStart(specifier); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write(" = "); - write(generatedName); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name); - write(";"); - emitEnd(specifier); - } - } - } - else { - // export * from "foo" - if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - writeLine(); - write("__export("); - if (modulekind !== ts.ModuleKind.AMD) { - emitRequire(ts.getExternalModuleName(node)); - } - else { - write(generatedName); - } - write(");"); - } - } - emitEnd(node); - } - } - else { - if (!node.exportClause || resolver.isValueAliasDeclaration(node)) { - write("export "); - if (node.exportClause) { - // export { x, y, ... } - write("{ "); - emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emit(node.moduleSpecifier); - } - write(";"); - } - } - } - function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === ts.ModuleKind.ES6); - var needsComma = false; - for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { - var specifier = specifiers_1[_a]; - if (shouldEmit(specifier)) { - if (needsComma) { - write(", "); - } - if (specifier.propertyName) { - emit(specifier.propertyName); - write(" as "); - } - emit(specifier.name); - needsComma = true; - } - } - } - function emitExportAssignment(node) { - if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === ts.ModuleKind.ES6) { - writeLine(); - emitStart(node); - write("export default "); - var expression = node.expression; - emit(expression); - if (expression.kind !== 220 /* FunctionDeclaration */ && - expression.kind !== 221 /* ClassDeclaration */) { - write(";"); - } - emitEnd(node); - } - else { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System) { - write(exportFunctionForFile + "(\"default\","); - emit(node.expression); - write(")"); - } - else { - emitEs6ExportDefaultCompat(node); - emitContainingModuleName(node); - if (languageVersion === 0 /* ES3 */) { - write('["default"] = '); - } - else { - write(".default = "); - } - emit(node.expression); - } - write(";"); - emitEnd(node); - } - } - } - function collectExternalModuleInfo(sourceFile) { - externalImports = []; - exportSpecifiers = {}; - exportEquals = undefined; - hasExportStarsToExportValues = false; - for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { - var node = _b[_a]; - switch (node.kind) { - case 230 /* ImportDeclaration */: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { - // import "mod" - // import x from "mod" where x is referenced - // import * as x from "mod" where x is referenced - // import { x, y } from "mod" where at least one import is referenced - externalImports.push(node); - } - break; - case 229 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 240 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { - // import x = require("mod") where x is referenced - externalImports.push(node); - } - break; - case 236 /* ExportDeclaration */: - if (node.moduleSpecifier) { - if (!node.exportClause) { - // export * from "mod" - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - // export { x, y } from "mod" where at least one export is a value symbol - externalImports.push(node); - } - } - else { - // export { x, y } - for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { - var specifier = _d[_c]; - var name_30 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_30] || (exportSpecifiers[name_30] = [])).push(specifier); - } - } - break; - case 235 /* ExportAssignment */: - if (node.isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; - } - } - } - function emitExportStarHelper() { - if (hasExportStarsToExportValues) { - writeLine(); - write("function __export(m) {"); - increaseIndent(); - writeLine(); - write("for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function getLocalNameForExternalImport(node) { - var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); - } - if (node.kind === 230 /* ImportDeclaration */ && node.importClause) { - return getGeneratedNameForNode(node); - } - if (node.kind === 236 /* ExportDeclaration */ && node.moduleSpecifier) { - return getGeneratedNameForNode(node); - } - } - function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { - if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - return "\"" + name_31 + "\""; - } - } - var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 9 /* StringLiteral */) { - return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); - } - return undefined; - } - function emitVariableDeclarationsForImports() { - if (externalImports.length === 0) { - return; - } - writeLine(); - var started = false; - for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { - var importNode = externalImports_1[_a]; - // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 236 /* ExportDeclaration */ || - (importNode.kind === 230 /* ImportDeclaration */ && !importNode.importClause); - if (skipNode) { - continue; - } - if (!started) { - write("var "); - started = true; - } - else { - write(", "); - } - write(getLocalNameForExternalImport(importNode)); - } - if (started) { - write(";"); - } - } - function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - // 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 exports. - if (!hasExportStarsToExportValues) { - // 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 && ts.isEmpty(exportSpecifiers)) { - // no exported declarations (export var ...) or export specifiers (export {x}) - // check if we have any non star export declarations. - var hasExportDeclarationWithExportClause = false; - for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { - var externalImport = externalImports_2[_a]; - if (externalImport.kind === 236 /* ExportDeclaration */ && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - // we still need to emit exportStar helper - return emitExportStarFunction(/*localNames*/ undefined); - } - } - var exportedNamesStorageRef = makeUniqueName("exportedNames"); - writeLine(); - write("var " + exportedNamesStorageRef + " = {"); - increaseIndent(); - var started = false; - if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; i++) { - // write name of exported declaration, i.e 'export var x...' - writeExportedName(exportedDeclarations[i]); - } - } - if (exportSpecifiers) { - for (var n in exportSpecifiers) { - for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) { - var specifier = _c[_b]; - // write name of export specified, i.e. 'export {x}' - writeExportedName(specifier.name); - } - } - } - for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { - var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 236 /* ExportDeclaration */) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - // export * from ... - continue; - } - for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) { - var element = _f[_e]; - // 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) { - var exportStarFunction = makeUniqueName("exportStar"); - writeLine(); - // define an export star helper function - write("function " + exportStarFunction + "(m) {"); - increaseIndent(); - writeLine(); - write("var exports = {};"); - writeLine(); - write("for(var n in m) {"); - increaseIndent(); - writeLine(); - write("if (n !== \"default\""); - if (localNames) { - write("&& !" + localNames + ".hasOwnProperty(n)"); - } - write(") exports[n] = m[n];"); - decreaseIndent(); - writeLine(); - write("}"); - writeLine(); - write(exportFunctionForFile + "(exports);"); - decreaseIndent(); - writeLine(); - write("}"); - return exportStarFunction; - } - function writeExportedName(node) { - // do not record default exports - // they are local to module and never overwritten (explicitly skipped) by star export - if (node.kind !== 69 /* Identifier */ && node.flags & 512 /* Default */) { - return; - } - if (started) { - write(","); - } - else { - started = true; - } - writeLine(); - write("'"); - if (node.kind === 69 /* Identifier */) { - emitNodeWithCommentsAndWithoutSourcemap(node); - } - else { - emitDeclarationName(node); - } - write("': true"); - } - } - function processTopLevelVariableAndFunctionDeclarations(node) { - // per ES6 spec: - // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method - // - var declarations are initialized to undefined - 14.a.ii - // - function/generator declarations are instantiated - 16.a.iv - // this means that after module is instantiated but before its evaluation - // exported functions are already accessible at import sites - // in theory we should hoist only exported functions and its dependencies - // in practice to simplify things we'll hoist all source level functions and variable declaration - // including variables declarations for module and class declarations - var hoistedVars; - var hoistedFunctionDeclarations; - var exportedDeclarations; - visit(node); - if (hoistedVars) { - writeLine(); - write("var "); - var seen = {}; - for (var i = 0; i < hoistedVars.length; i++) { - var local = hoistedVars[i]; - var name_32 = local.kind === 69 /* Identifier */ - ? local - : local.name; - if (name_32) { - // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_32.text); - if (ts.hasProperty(seen, text)) { - continue; - } - else { - seen[text] = text; - } - } - if (i !== 0) { - write(", "); - } - if (local.kind === 221 /* ClassDeclaration */ || local.kind === 225 /* ModuleDeclaration */ || local.kind === 224 /* EnumDeclaration */) { - emitDeclarationName(local); - } - else { - emit(local); - } - var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); - if (flags & 1 /* Export */) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(local); - } - } - write(";"); - } - if (hoistedFunctionDeclarations) { - for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { - var f = hoistedFunctionDeclarations_1[_a]; - writeLine(); - emit(f); - if (f.flags & 1 /* Export */) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(f); - } - } - } - return exportedDeclarations; - function visit(node) { - if (node.flags & 2 /* Ambient */) { - return; - } - if (node.kind === 220 /* FunctionDeclaration */) { - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = []; - } - hoistedFunctionDeclarations.push(node); - return; - } - if (node.kind === 221 /* ClassDeclaration */) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - return; - } - if (node.kind === 224 /* EnumDeclaration */) { - if (shouldEmitEnumDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 225 /* ModuleDeclaration */) { - if (shouldEmitModuleDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) { - if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - var name_33 = node.name; - if (name_33.kind === 69 /* Identifier */) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(name_33); - } - else { - ts.forEachChild(name_33, visit); - } - } - return; - } - if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node.name); - return; - } - if (ts.isBindingPattern(node)) { - ts.forEach(node.elements, visit); - return; - } - if (!ts.isDeclaration(node)) { - ts.forEachChild(node, visit); - } - } - } - function shouldHoistVariable(node, checkIfSourceFileLevelDecl) { - if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { - return false; - } - // hoist variable if - // - it is not block scoped - // - it is top level block scoped - // if block scoped variables are nested in some another block then - // no other functions can use them except ones that are defined at least in the same block - return (ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 256 /* SourceFile */; - } - function isCurrentFileSystemExternalModule() { - return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; - } - function emitSystemModuleBody(node, dependencyGroups, startIndex) { - // shape of the body in system modules: - // function (exports) { - // - // - // - // return { - // setters: [ - // - // ], - // execute: function() { - // - // } - // } - // - // } - // I.e: - // import {x} from 'file1' - // var y = 1; - // export function foo() { return y + x(); } - // console.log(y); - // will be transformed to - // function(exports) { - // var file1; // local alias - // var y; - // function foo() { return y + file1.x(); } - // exports("foo", foo); - // return { - // setters: [ - // function(v) { file1 = v } - // ], - // execute(): function() { - // y = 1; - // console.log(y); - // } - // }; - // } - emitVariableDeclarationsForImports(); - writeLine(); - var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); - writeLine(); - write("return {"); - increaseIndent(); - writeLine(); - emitSetters(exportStarFunction, dependencyGroups); - writeLine(); - emitExecute(node, startIndex); - decreaseIndent(); - writeLine(); - write("}"); // return - emitTempDeclarations(/*newLine*/ true); - } - function emitSetters(exportStarFunction, dependencyGroups) { - write("setters:["); - for (var i = 0; i < dependencyGroups.length; i++) { - if (i !== 0) { - write(","); - } - writeLine(); - increaseIndent(); - var group = dependencyGroups[i]; - // derive a unique name for parameter from the first named entry in the group - var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); - write("function (" + parameterName + ") {"); - increaseIndent(); - for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { - var entry = group_1[_a]; - var importVariableName = getLocalNameForExternalImport(entry) || ""; - switch (entry.kind) { - case 230 /* ImportDeclaration */: - if (!entry.importClause) { - // 'import "..."' case - // module is imported only for side-effects, no emit required - break; - } - // fall-through - case 229 /* ImportEqualsDeclaration */: - ts.Debug.assert(importVariableName !== ""); - writeLine(); - // save import into the local - write(importVariableName + " = " + parameterName + ";"); - writeLine(); - break; - case 236 /* ExportDeclaration */: - ts.Debug.assert(importVariableName !== ""); - if (entry.exportClause) { - // export {a, b as c} from 'foo' - // emit as: - // exports_({ - // "a": _["a"], - // "c": _["b"] - // }); - writeLine(); - write(exportFunctionForFile + "({"); - writeLine(); - increaseIndent(); - for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { - if (i_1 !== 0) { - write(","); - writeLine(); - } - var e = entry.exportClause.elements[i_1]; - write("\""); - emitNodeWithCommentsAndWithoutSourcemap(e.name); - write("\": " + parameterName + "[\""); - emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name); - write("\"]"); - } - decreaseIndent(); - writeLine(); - write("});"); - } - else { - // collectExternalModuleInfo prefilters star exports to keep only ones that export values - // this means that check 'resolver.moduleExportsSomeValue' is redundant and can be omitted here - writeLine(); - // export * from 'foo' - // emit as: - // exportStar(_foo); - write(exportStarFunction + "(" + parameterName + ");"); - } - writeLine(); - break; - } - } - decreaseIndent(); - write("}"); - decreaseIndent(); - } - write("],"); - } - function emitExecute(node, startIndex) { - write("execute: function() {"); - increaseIndent(); - writeLine(); - for (var i = startIndex; i < node.statements.length; i++) { - var statement = node.statements[i]; - switch (statement.kind) { - // - function declarations are not emitted because they were already hoisted - // - import declarations are not emitted since they are already handled in setters - // - export declarations with module specifiers are not emitted since they were already written in setters - // - export declarations without module specifiers are emitted preserving the order - case 220 /* FunctionDeclaration */: - case 230 /* ImportDeclaration */: - continue; - case 236 /* ExportDeclaration */: - if (!statement.moduleSpecifier) { - for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { - var element = _b[_a]; - // write call to exporter function for every export specifier in exports list - emitExportSpecifierInSystemModule(element); - } - } - continue; - case 229 /* ImportEqualsDeclaration */: - if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { - // - import equals declarations that import external modules are not emitted - continue; - } - // fall-though for import declarations that import internal modules - default: - writeLine(); - emit(statement); - } - } - decreaseIndent(); - writeLine(); - write("}"); // execute - } - function writeModuleName(node, emitRelativePathAsModuleName) { - var moduleName = node.moduleName; - if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { - write("\"" + moduleName + "\", "); - } - } - function emitSystemModule(node, emitRelativePathAsModuleName) { - collectExternalModuleInfo(node); - // System modules has the following shape - // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) - // 'exports' here is a function 'exports(name: string, value: T): T' that is used to publish exported values. - // 'exports' returns its 'value' argument so in most cases expressions - // that mutate exported values can be rewritten as: - // expr -> exports('name', expr). - // The only exception in this rule is postfix unary operators, - // see comment to 'emitPostfixUnaryExpression' for more details - ts.Debug.assert(!exportFunctionForFile); - // make sure that name of 'exports' function does not conflict with existing identifiers - exportFunctionForFile = makeUniqueName("exports"); - contextObjectForFile = makeUniqueName("context"); - writeLine(); - write("System.register("); - writeModuleName(node, emitRelativePathAsModuleName); - write("["); - var groupIndices = {}; - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); - if (text === undefined) { - continue; - } - // text should be quoted string - // for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same - var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { - // deduplicate/group entries in dependency list by the dependency name - var groupIndex = groupIndices[key]; - dependencyGroups[groupIndex].push(externalImports[i]); - continue; - } - else { - groupIndices[key] = dependencyGroups.length; - dependencyGroups.push([externalImports[i]]); - } - if (i !== 0) { - write(", "); - } - write(text); - } - write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); - writeLine(); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - writeLine(); - write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); - writeLine(); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitSystemModuleBody(node, dependencyGroups, startIndex); - decreaseIndent(); - writeLine(); - write("});"); - } - function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - // names of modules with corresponding parameter in the factory function - var aliasedModuleNames = []; - // names of modules with no corresponding parameters in factory function - var unaliasedModuleNames = []; - var importAliasNames = []; // names of the parameters in the factory function; these - // parameters need to match the indexes of the corresponding - // module names in aliasedModuleNames. - // Fill in amd-dependency tags - for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) { - var amdDependency = _b[_a]; - if (amdDependency.name) { - aliasedModuleNames.push('"' + amdDependency.path + '"'); - importAliasNames.push(amdDependency.name); - } - else { - unaliasedModuleNames.push('"' + amdDependency.path + '"'); - } - } - for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { - var importNode = externalImports_4[_c]; - // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); - // Find the name of the module alias, if there is one - var importAliasName = getLocalNameForExternalImport(importNode); - if (includeNonAmdDependencies && importAliasName) { - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(importAliasName); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - // An AMD define function has the following shape: - // define(id?, dependencies?, factory); - // - // This has the shape of - // define(name, ["module1", "module2"], function (module1Alias) { - // The location of the alias in the parameter list in the factory function needs to - // match the position of the module name in the dependency list. - // - // To ensure this is true in cases of modules with no aliases, e.g.: - // `import "module"` or `` - // we need to add modules without alias names to the end of the dependencies list - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); - emitAMDDependencyList(dependencyNames); - write(", "); - emitAMDFactoryHeader(dependencyNames); - } - function emitAMDDependencyList(_a) { - var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames; - write('["require", "exports"'); - if (aliasedModuleNames.length) { - write(", "); - write(aliasedModuleNames.join(", ")); - } - if (unaliasedModuleNames.length) { - write(", "); - write(unaliasedModuleNames.join(", ")); - } - write("]"); - } - function emitAMDFactoryHeader(_a) { - var importAliasNames = _a.importAliasNames; - write("function (require, exports"); - if (importAliasNames.length) { - write(", "); - write(importAliasNames.join(", ")); - } - write(") {"); - } - function emitAMDModule(node, emitRelativePathAsModuleName) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - writeLine(); - write("define("); - writeModuleName(node, emitRelativePathAsModuleName); - emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(/*emitAsReturn*/ true); - emitTempDeclarations(/*newLine*/ true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - emitEmitHelpers(node); - collectExternalModuleInfo(node); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(/*emitAsReturn*/ false); - emitTempDeclarations(/*newLine*/ true); - } - function emitUMDModule(node) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - var dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false); - // Module is detected first to support Browserify users that load into a browser with an AMD loader - writeLines("(function (factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define("); - emitAMDDependencyList(dependencyNames); - write(", factory);"); - writeLines(" }\n})("); - emitAMDFactoryHeader(dependencyNames); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(/*emitAsReturn*/ true); - emitTempDeclarations(/*newLine*/ true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitES6Module(node) { - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(/*newLine*/ true); - // Emit exportDefault if it exists will happen as part - // or normal statement emit. - } - function emitExportEquals(emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - writeLine(); - emitStart(exportEquals); - write(emitAsReturn ? "return " : "module.exports = "); - emit(exportEquals.expression); - write(";"); - emitEnd(exportEquals); - } - } - function emitJsxElement(node) { - switch (compilerOptions.jsx) { - case 2 /* React */: - jsxEmitReact(node); - break; - case 1 /* Preserve */: - // Fall back to preserve if None was specified (we'll error earlier) - default: - jsxEmitPreserve(node); - break; - } - } - function trimReactWhitespaceAndApplyEntities(node) { - var result = undefined; - var text = ts.getTextOfNode(node, /*includeTrivia*/ true); - var firstNonWhitespace = 0; - var lastNonWhitespace = -1; - // JSX trims whitespace at the end and beginning of lines, except that the - // start/end of a tag is considered a start/end of a line only if that line is - // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx - for (var i = 0; i < text.length; i++) { - var c = text.charCodeAt(i); - if (ts.isLineBreak(c)) { - if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { - var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - firstNonWhitespace = -1; - } - else if (!ts.isWhiteSpaceSingleLine(c)) { - lastNonWhitespace = i; - if (firstNonWhitespace === -1) { - firstNonWhitespace = i; - } - } - } - if (firstNonWhitespace !== -1) { - var part = text.substr(firstNonWhitespace); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - if (result) { - // Replace entities like   - result = result.replace(/&(\w+);/g, function (s, m) { - if (entities[m] !== undefined) { - var ch = String.fromCharCode(entities[m]); - // " needs to be escaped - return ch === '"' ? "\\\"" : ch; - } - else { - return s; - } - }); - } - return result; - } - function isJsxChildEmittable(child) { - if (child.kind === 248 /* JsxExpression */) { - // Don't emit empty expressions - return !!child.expression; - } - else if (child.kind === 244 /* JsxText */) { - // Don't emit empty strings - return !!getTextToEmit(child); - } - return true; - } - ; - function getTextToEmit(node) { - switch (compilerOptions.jsx) { - case 2 /* React */: - var text = trimReactWhitespaceAndApplyEntities(node); - if (text === undefined || text.length === 0) { - return undefined; - } - else { - return text; - } - case 1 /* Preserve */: - default: - return ts.getTextOfNode(node, /*includeTrivia*/ true); - } - } - function emitJsxText(node) { - switch (compilerOptions.jsx) { - case 2 /* React */: - write('"'); - write(trimReactWhitespaceAndApplyEntities(node)); - write('"'); - break; - case 1 /* Preserve */: - default: - writer.writeLiteral(ts.getTextOfNode(node, /*includeTrivia*/ true)); - break; - } - } - function emitJsxExpression(node) { - if (node.expression) { - switch (compilerOptions.jsx) { - case 1 /* Preserve */: - default: - write("{"); - emit(node.expression); - write("}"); - break; - case 2 /* React */: - emit(node.expression); - break; - } - } - } - function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; - } - function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { - if (writeUseStrict) { - if (startWithNewLine) { - writeLine(); - } - write("\"use strict\";"); - } - } - function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { - var foundUseStrict = false; - for (var i = 0; i < statements.length; i++) { - if (ts.isPrologueDirective(statements[i])) { - if (isUseStrictPrologue(statements[i])) { - foundUseStrict = true; - } - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); - // return index of the first non prologue directive - return i; - } - } - ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); - return statements.length; - } - function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line.length) { - writeLine(); - write(line); - } - } - } - function emitEmitHelpers(node) { - // 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 < 2 /* ES6 */ && !extendsEmitted && node.flags & 262144 /* HasClassExtends */) { - writeLines(extendsHelper); - extendsEmitted = true; - } - if (compilerOptions.jsx !== 1 /* Preserve */ && !assignEmitted && (node.flags & 1073741824 /* HasJsxSpreadAttribute */)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 524288 /* HasDecorators */) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); - } - decorateEmitted = true; - } - if (!paramEmitted && node.flags & 1048576 /* HasParamDecorators */) { - writeLines(paramHelper); - paramEmitted = true; - } - if (!awaiterEmitted && node.flags & 2097152 /* HasAsyncFunctions */) { - writeLines(awaiterHelper); - awaiterEmitted = true; - } - } - } - function emitSourceFileNode(node) { - // Start new file on new line - writeLine(); - emitShebang(); - emitDetachedCommentsAndUpdateCommentsInfo(node); - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; - emitModule(node); - } - else { - bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/ true); - } - } - else { - // emit prologue directives prior to __extends - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(/*newLine*/ true); - } - emitLeadingComments(node.endOfFileToken); - } - function emit(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - function emitNodeWithCommentsAndWithoutSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); - } - function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { - if (node) { - if (node.flags & 2 /* Ambient */) { - return emitCommentsOnNotEmittedNode(node); - } - if (isSpecializedCommentHandling(node)) { - // This is the node that will handle its own comments and sourcemap - return emitNodeWithoutSourceMap(node); - } - var emitComments_1 = shouldEmitLeadingAndTrailingComments(node); - if (emitComments_1) { - emitLeadingComments(node); - } - emitNodeConsideringSourcemap(node); - if (emitComments_1) { - emitTrailingComments(node); - } - } - } - function emitNodeWithSourceMap(node) { - if (node) { - emitStart(node); - emitNodeWithoutSourceMap(node); - emitEnd(node); - } - } - function emitNodeWithoutSourceMap(node) { - if (node) { - emitJavaScriptWorker(node); - } - } - function changeSourceMapEmit(writer) { - sourceMap = writer; - emitStart = writer.emitStart; - emitEnd = writer.emitEnd; - emitPos = writer.emitPos; - setSourceFile = writer.setSourceFile; - } - function withTemporaryNoSourceMap(callback) { - var prevSourceMap = sourceMap; - setSourceMapWriterEmit(ts.getNullSourceMapWriter()); - callback(); - setSourceMapWriterEmit(prevSourceMap); - } - function isSpecializedCommentHandling(node) { - switch (node.kind) { - // All of these entities are emitted in a specialized fashion. As such, we allow - // the specialized methods for each to handle the comments on the nodes. - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 235 /* ExportAssignment */: - return true; - } - } - function shouldEmitLeadingAndTrailingComments(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 225 /* ModuleDeclaration */: - // Only emit the leading/trailing comments for a module if we're actually - // emitting the module as well. - return shouldEmitModuleDeclaration(node); - case 224 /* EnumDeclaration */: - // Only emit the leading/trailing comments for an enum if we're actually - // emitting the module as well. - return shouldEmitEnumDeclaration(node); - } - // If the node is emitted in specialized fashion, dont emit comments as this node will handle - // emitting comments when emitting itself - ts.Debug.assert(!isSpecializedCommentHandling(node)); - // If this is the expression body of an arrow function that we're down-leveling, - // then we don't want to emit comments when we emit the body. It will have already - // been taken care of when we emitted the 'return' statement for the function - // expression body. - if (node.kind !== 199 /* Block */ && - node.parent && - node.parent.kind === 180 /* ArrowFunction */ && - node.parent.body === node && - languageVersion <= 1 /* ES5 */) { - return false; - } - // Emit comments for everything else. - return true; - } - function emitJavaScriptWorker(node) { - // Check if the node can be emitted regardless of the ScriptTarget - switch (node.kind) { - case 69 /* Identifier */: - return emitIdentifier(node); - case 142 /* Parameter */: - return emitParameter(node); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return emitMethod(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return emitAccessor(node); - case 97 /* ThisKeyword */: - return emitThis(node); - case 95 /* SuperKeyword */: - return emitSuper(node); - case 93 /* NullKeyword */: - return write("null"); - case 99 /* TrueKeyword */: - return write("true"); - case 84 /* FalseKeyword */: - return write("false"); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 10 /* RegularExpressionLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: - return emitLiteral(node); - case 189 /* TemplateExpression */: - return emitTemplateExpression(node); - case 197 /* TemplateSpan */: - return emitTemplateSpan(node); - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - return emitJsxElement(node); - case 244 /* JsxText */: - return emitJsxText(node); - case 248 /* JsxExpression */: - return emitJsxExpression(node); - case 139 /* QualifiedName */: - return emitQualifiedName(node); - case 167 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 168 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 169 /* BindingElement */: - return emitBindingElement(node); - case 170 /* ArrayLiteralExpression */: - return emitArrayLiteral(node); - case 171 /* ObjectLiteralExpression */: - return emitObjectLiteral(node); - case 253 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 254 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 140 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - case 172 /* PropertyAccessExpression */: - return emitPropertyAccess(node); - case 173 /* ElementAccessExpression */: - return emitIndexedAccess(node); - case 174 /* CallExpression */: - return emitCallExpression(node); - case 175 /* NewExpression */: - return emitNewExpression(node); - case 176 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: - case 196 /* NonNullExpression */: - return emit(node.expression); - case 178 /* ParenthesizedExpression */: - return emitParenExpression(node); - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - return emitFunctionDeclaration(node); - case 181 /* DeleteExpression */: - return emitDeleteExpression(node); - case 182 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 183 /* VoidExpression */: - return emitVoidExpression(node); - case 184 /* AwaitExpression */: - return emitAwaitExpression(node); - case 185 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 186 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 187 /* BinaryExpression */: - return emitBinaryExpression(node); - case 188 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 191 /* SpreadElementExpression */: - return emitSpreadElementExpression(node); - case 190 /* YieldExpression */: - return emitYieldExpression(node); - case 193 /* OmittedExpression */: - return; - case 199 /* Block */: - case 226 /* ModuleBlock */: - return emitBlock(node); - case 200 /* VariableStatement */: - return emitVariableStatement(node); - case 201 /* EmptyStatement */: - return write(";"); - case 202 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 203 /* IfStatement */: - return emitIfStatement(node); - case 204 /* DoStatement */: - return emitDoStatement(node); - case 205 /* WhileStatement */: - return emitWhileStatement(node); - case 206 /* ForStatement */: - return emitForStatement(node); - case 208 /* ForOfStatement */: - case 207 /* ForInStatement */: - return emitForInOrForOfStatement(node); - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: - return emitBreakOrContinueStatement(node); - case 211 /* ReturnStatement */: - return emitReturnStatement(node); - case 212 /* WithStatement */: - return emitWithStatement(node); - case 213 /* SwitchStatement */: - return emitSwitchStatement(node); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: - return emitCaseOrDefaultClause(node); - case 214 /* LabeledStatement */: - return emitLabeledStatement(node); - case 215 /* ThrowStatement */: - return emitThrowStatement(node); - case 216 /* TryStatement */: - return emitTryStatement(node); - case 252 /* CatchClause */: - return emitCatchClause(node); - case 217 /* DebuggerStatement */: - return emitDebuggerStatement(node); - case 218 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 192 /* ClassExpression */: - return emitClassExpression(node); - case 221 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 222 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 224 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 255 /* EnumMember */: - return emitEnumMember(node); - case 225 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 230 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 235 /* ExportAssignment */: - return emitExportAssignment(node); - case 256 /* SourceFile */: - return emitSourceFileNode(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - **/ - function isTripleSlashComment(comment) { - // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text - // so that we don't end up computing comment string and doing match for all // comments - if (currentText.charCodeAt(comment.pos + 1) === 47 /* slash */ && - comment.pos + 2 < comment.end && - currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) { - var textSubStr = currentText.substring(comment.pos, comment.end); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; - } - function getLeadingCommentsToEmit(node) { - // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments - if (node.parent) { - if (node.parent.kind === 256 /* SourceFile */ || node.pos !== node.parent.pos) { - if (hasDetachedComments(node.pos)) { - // get comments without detached comments - return getLeadingCommentsWithoutDetachedComments(); - } - else { - // get the leading comments from the node - return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); - } - } - } - } - function getTrailingCommentsToEmit(node) { - // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments - if (node.parent) { - if (node.parent.kind === 256 /* SourceFile */ || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentText, node.end); - } - } - } - /** - * Emit comments associated with node that will not be emitted into JS file - */ - function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, /*isEmittedNode*/ false); - } - function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true); - } - function emitLeadingCommentsWorker(node, isEmittedNode) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (isEmittedNode) { - leadingComments = getLeadingCommentsToEmit(node); - } - else { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - if (node.pos === 0) { - leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); - } - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); - } - function emitTrailingComments(node) { - if (compilerOptions.removeComments) { - return; - } - // Emit the trailing comments only if the parent's end doesn't match - var trailingComments = getTrailingCommentsToEmit(node); - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); - } - /** - * Emit trailing comments at the position. The term trailing comment is used here to describe following comment: - * x, /comment1/ y - * ^ => pos; the function will emit "comment1" in the emitJS - */ - function emitTrailingCommentsOfPosition(pos) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = ts.getTrailingCommentRanges(currentText, pos); - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); - } - function emitLeadingCommentsOfPositionWorker(pos) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (hasDetachedComments(pos)) { - // get comments without detached comments - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - // get the leading comments from the node - leadingComments = ts.getLeadingCommentRanges(currentText, pos); - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); - } - function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, comment, newLine) { - emitPos(comment.pos); - ts.writeCommentRange(text, lineMap, writer, comment, newLine); - emitPos(comment.end); - } - function emitShebang() { - var shebang = ts.getShebang(currentText); - if (shebang) { - write(shebang); - writeLine(); - } - } - var _a, _b; - } - function emitFile(_a, sourceFiles, isBundledEmit) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - // Make sure not to write js File and source map file if any of them cannot be written + function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { + // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { emittedFilesList.push(jsFilePath); @@ -42923,25 +54486,2342 @@ var ts; } } } + function printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNameSet = ts.createMap(); + isOwnFileEmit = !isBundledEmit; + // Emit helpers from all the files + if (isBundledEmit && moduleKind) { + for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { + var sourceFile = sourceFiles_4[_a]; + emitEmitHelpers(sourceFile); + } + } + // Print each transformed source file. + ts.forEach(sourceFiles, printSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); + } + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); + } + // Write the output file + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + // Reset state + sourceMap.reset(); + comments.reset(); + writer.reset(); + tempFlags = 0 /* Auto */; + currentSourceFile = undefined; + currentText = undefined; + extendsEmitted = false; + assignEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + isOwnFileEmit = false; + } + function printSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + currentFileIdentifiers = node.identifiers; + sourceMap.setSourceFile(node); + comments.setSourceFile(node); + emitNodeWithNotification(node, emitWorker); + } + /** + * Emits a node. + */ + function emit(node) { + emitNodeWithNotification(node, emitWithComments); + } + /** + * Emits a node with comments. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from emit. + */ + function emitWithComments(node) { + emitNodeWithComments(node, emitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from emitWithComments. + */ + function emitWithSourceMap(node) { + emitNodeWithSourceMap(node, emitWorker); + } + function emitIdentifierName(node) { + if (node) { + emitNodeWithNotification(node, emitIdentifierNameWithComments); + } + } + function emitIdentifierNameWithComments(node) { + emitNodeWithComments(node, emitWorker); + } + /** + * Emits an expression node. + */ + function emitExpression(node) { + emitNodeWithNotification(node, emitExpressionWithComments); + } + /** + * Emits an expression with comments. + * + * NOTE: Do not call this method directly. It is part of the emitExpression pipeline + * and should only be called indirectly from emitExpression. + */ + function emitExpressionWithComments(node) { + emitNodeWithComments(node, emitExpressionWithSourceMap); + } + /** + * Emits an expression with source maps. + * + * NOTE: Do not call this method directly. It is part of the emitExpression pipeline + * and should only be called indirectly from emitExpressionWithComments. + */ + function emitExpressionWithSourceMap(node) { + emitNodeWithSourceMap(node, emitExpressionWorker); + } + /** + * Emits a node with emit notification if available. + */ + function emitNodeWithNotification(node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(node, emitCallback); + } + else { + emitCallback(node); + } + } + } + function emitNodeWithSourceMap(node, emitCallback) { + if (node) { + emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + emitCallback(node); + emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + /** + * Determines whether to skip leading comment emit for a node. + * + * We do not emit comments for NotEmittedStatement nodes or any node that has + * NodeEmitFlags.NoLeadingComments. + * + * @param node A Node. + */ + function shouldSkipLeadingCommentsForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; + } + /** + * Determines whether to skip source map emit for the start position of a node. + * + * We do not emit source maps for NotEmittedStatement nodes or any node that + * has NodeEmitFlags.NoLeadingSourceMap. + * + * @param node A Node. + */ + function shouldSkipLeadingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; + } + /** + * Determines whether to skip source map emit for the end position of a node. + * + * We do not emit source maps for NotEmittedStatement nodes or any node that + * has NodeEmitFlags.NoTrailingSourceMap. + * + * @param node A Node. + */ + function shouldSkipTrailingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; + } + /** + * Determines whether to skip source map emit for a node and its children. + * + * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. + */ + function shouldSkipSourceMapForChildren(node) { + return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; + } + function emitWorker(node) { + if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + return; + } + var kind = node.kind; + switch (kind) { + // Pseudo-literals + case 12 /* TemplateHead */: + case 13 /* TemplateMiddle */: + case 14 /* TemplateTail */: + return emitLiteral(node); + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 74 /* ConstKeyword */: + case 77 /* DefaultKeyword */: + case 82 /* ExportKeyword */: + case 103 /* VoidKeyword */: + // Strict mode reserved words + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 112 /* PublicKeyword */: + case 113 /* StaticKeyword */: + // Contextual keywords + case 115 /* AbstractKeyword */: + case 117 /* AnyKeyword */: + case 118 /* AsyncKeyword */: + case 120 /* BooleanKeyword */: + case 122 /* DeclareKeyword */: + case 130 /* NumberKeyword */: + case 128 /* ReadonlyKeyword */: + case 132 /* StringKeyword */: + case 133 /* SymbolKeyword */: + case 137 /* GlobalKeyword */: + return writeTokenNode(node); + // Parse tree nodes + // Names + case 139 /* QualifiedName */: + return emitQualifiedName(node); + case 140 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 141 /* TypeParameter */: + return emitTypeParameter(node); + case 142 /* Parameter */: + return emitParameter(node); + case 143 /* Decorator */: + return emitDecorator(node); + // Type members + case 144 /* PropertySignature */: + return emitPropertySignature(node); + case 145 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 146 /* MethodSignature */: + return emitMethodSignature(node); + case 147 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 148 /* Constructor */: + return emitConstructor(node); + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 151 /* CallSignature */: + return emitCallSignature(node); + case 152 /* ConstructSignature */: + return emitConstructSignature(node); + case 153 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 154 /* TypePredicate */: + return emitTypePredicate(node); + case 155 /* TypeReference */: + return emitTypeReference(node); + case 156 /* FunctionType */: + return emitFunctionType(node); + case 157 /* ConstructorType */: + return emitConstructorType(node); + case 158 /* TypeQuery */: + return emitTypeQuery(node); + case 159 /* TypeLiteral */: + return emitTypeLiteral(node); + case 160 /* ArrayType */: + return emitArrayType(node); + case 161 /* TupleType */: + return emitTupleType(node); + case 162 /* UnionType */: + return emitUnionType(node); + case 163 /* IntersectionType */: + return emitIntersectionType(node); + case 164 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 194 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 165 /* ThisType */: + return emitThisType(node); + case 166 /* LiteralType */: + return emitLiteralType(node); + // Binding patterns + case 167 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 168 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 169 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 197 /* TemplateSpan */: + return emitTemplateSpan(node); + case 198 /* SemicolonClassElement */: + return emitSemicolonClassElement(node); + // Statements + case 199 /* Block */: + return emitBlock(node); + case 200 /* VariableStatement */: + return emitVariableStatement(node); + case 201 /* EmptyStatement */: + return emitEmptyStatement(node); + case 202 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 203 /* IfStatement */: + return emitIfStatement(node); + case 204 /* DoStatement */: + return emitDoStatement(node); + case 205 /* WhileStatement */: + return emitWhileStatement(node); + case 206 /* ForStatement */: + return emitForStatement(node); + case 207 /* ForInStatement */: + return emitForInStatement(node); + case 208 /* ForOfStatement */: + return emitForOfStatement(node); + case 209 /* ContinueStatement */: + return emitContinueStatement(node); + case 210 /* BreakStatement */: + return emitBreakStatement(node); + case 211 /* ReturnStatement */: + return emitReturnStatement(node); + case 212 /* WithStatement */: + return emitWithStatement(node); + case 213 /* SwitchStatement */: + return emitSwitchStatement(node); + case 214 /* LabeledStatement */: + return emitLabeledStatement(node); + case 215 /* ThrowStatement */: + return emitThrowStatement(node); + case 216 /* TryStatement */: + return emitTryStatement(node); + case 217 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 218 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 219 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 220 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 221 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 222 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 223 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 224 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 225 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 226 /* ModuleBlock */: + return emitModuleBlock(node); + case 227 /* CaseBlock */: + return emitCaseBlock(node); + case 229 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 230 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 231 /* ImportClause */: + return emitImportClause(node); + case 232 /* NamespaceImport */: + return emitNamespaceImport(node); + case 233 /* NamedImports */: + return emitNamedImports(node); + case 234 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 235 /* ExportAssignment */: + return emitExportAssignment(node); + case 236 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 237 /* NamedExports */: + return emitNamedExports(node); + case 238 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 239 /* MissingDeclaration */: + return; + // Module references + case 240 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 244 /* JsxText */: + return emitJsxText(node); + case 243 /* JsxOpeningElement */: + return emitJsxOpeningElement(node); + case 245 /* JsxClosingElement */: + return emitJsxClosingElement(node); + case 246 /* JsxAttribute */: + return emitJsxAttribute(node); + case 247 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 248 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 249 /* CaseClause */: + return emitCaseClause(node); + case 250 /* DefaultClause */: + return emitDefaultClause(node); + case 251 /* HeritageClause */: + return emitHeritageClause(node); + case 252 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 253 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 254 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + // Enum + case 255 /* EnumMember */: + return emitEnumMember(node); + // Top-level nodes + case 256 /* SourceFile */: + return emitSourceFile(node); + } + if (ts.isExpression(node)) { + return emitExpressionWorker(node); + } + } + function emitExpressionWorker(node) { + if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { + return; + } + var kind = node.kind; + switch (kind) { + // Literals + case 8 /* NumericLiteral */: + return emitNumericLiteral(node); + case 9 /* StringLiteral */: + case 10 /* RegularExpressionLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 84 /* FalseKeyword */: + case 93 /* NullKeyword */: + case 95 /* SuperKeyword */: + case 99 /* TrueKeyword */: + case 97 /* ThisKeyword */: + return writeTokenNode(node); + // Expressions + case 170 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 171 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 172 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 174 /* CallExpression */: + return emitCallExpression(node); + case 175 /* NewExpression */: + return emitNewExpression(node); + case 176 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 177 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 178 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 179 /* FunctionExpression */: + return emitFunctionExpression(node); + case 180 /* ArrowFunction */: + return emitArrowFunction(node); + case 181 /* DeleteExpression */: + return emitDeleteExpression(node); + case 182 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 183 /* VoidExpression */: + return emitVoidExpression(node); + case 184 /* AwaitExpression */: + return emitAwaitExpression(node); + case 185 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 186 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 187 /* BinaryExpression */: + return emitBinaryExpression(node); + case 188 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 189 /* TemplateExpression */: + return emitTemplateExpression(node); + case 190 /* YieldExpression */: + return emitYieldExpression(node); + case 191 /* SpreadElementExpression */: + return emitSpreadElementExpression(node); + case 192 /* ClassExpression */: + return emitClassExpression(node); + case 193 /* OmittedExpression */: + return; + case 195 /* AsExpression */: + return emitAsExpression(node); + case 196 /* NonNullExpression */: + return emitNonNullExpression(node); + // JSX + case 241 /* JsxElement */: + return emitJsxElement(node); + case 242 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + // Transformation nodes + case 288 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + } + } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral + function emitNumericLiteral(node) { + emitLiteral(node); + if (node.trailingComment) { + write(" /*" + node.trailingComment + "*/"); + } + } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node) { + var text = getLiteralTextOfNode(node); + if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) + && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else { + write(text); + } + } + // + // Identifiers + // + function emitIdentifier(node) { + if (node.emitFlags & 16 /* UMDDefine */) { + writeLines(umdHelper); + } + else { + write(getTextOfNode(node, /*includeTrivia*/ false)); + } + } + // + // Names + // + function emitQualifiedName(node) { + emitEntityName(node.left); + write("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 69 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + write("["); + emitExpression(node.expression); + write("]"); + } + // + // Signature elements + // + function emitTypeParameter(node) { + emit(node.name); + emitWithPrefix(" extends ", node.constraint); + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitExpressionWithPrefix(" = ", node.initializer); + emitWithPrefix(": ", node.type); + } + function emitDecorator(decorator) { + write("@"); + emitExpression(decorator.expression); + } + // + // Type members + // + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emitWithPrefix(": ", node.type); + emitExpressionWithPrefix(" = ", node.initializer); + write(";"); + } + function emitMethodSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.asteriskToken, "*"); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + write("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.kind === 149 /* GetAccessor */ ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitConstructSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitSemicolonClassElement(node) { + write(";"); + } + // + // Types + // + function emitTypePredicate(node) { + emit(node.parameterName); + write(" is "); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitConstructorType(node) { + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitTypeQuery(node) { + write("typeof "); + emit(node.exprName); + } + function emitTypeLiteral(node) { + write("{"); + emitList(node, node.members, 65 /* TypeLiteralMembers */); + write("}"); + } + function emitArrayType(node) { + emit(node.elementType); + write("[]"); + } + function emitTupleType(node) { + write("["); + emitList(node, node.elementTypes, 336 /* TupleTypeElements */); + write("]"); + } + function emitUnionType(node) { + emitList(node, node.types, 260 /* UnionTypeConstituents */); + } + function emitIntersectionType(node) { + emitList(node, node.types, 264 /* IntersectionTypeConstituents */); + } + function emitParenthesizedType(node) { + write("("); + emit(node.type); + write(")"); + } + function emitThisType(node) { + write("this"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + // + // Binding patterns + // + function emitObjectBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("{}"); + } + else { + write("{"); + emitList(node, elements, 432 /* ObjectBindingPatternElements */); + write("}"); + } + } + function emitArrayBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + write("["); + emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); + write("]"); + } + } + function emitBindingElement(node) { + emitWithSuffix(node.propertyName, ": "); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + // + // Expressions + // + function emitArrayLiteralExpression(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); + } + } + function emitObjectLiteralExpression(node) { + var properties = node.properties; + if (properties.length === 0) { + write("{}"); + } + else { + var indentedFlag = node.emitFlags & 524288 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, properties, 978 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + } + function emitPropertyAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot); + write(shouldEmitDotDot ? ".." : "."); + increaseIndentIf(indentAfterDot); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression) { + if (expression.kind === 8 /* NumericLiteral */) { + // check if numeric literal was originally written with a dot + var text = getLiteralTextOfNode(expression); + return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; + } + else { + // check if constant enum value is integer + var constantValue = tryGetConstEnumValue(expression); + // isFinite handles cases when constantValue is undefined + return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + function emitElementAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + emitExpression(node.expression); + write("["); + emitExpression(node.argumentExpression); + write("]"); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); + } + function emitNewExpression(node) { + write("new "); + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + write(" "); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + if (node.type) { + write("<"); + emit(node.type); + write(">"); + } + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + write("("); + emitExpression(node.expression); + write(")"); + } + function emitFunctionExpression(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitWithPrefix(": ", node.type); + write(" =>"); + } + function emitDeleteExpression(node) { + write("delete "); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + write("typeof "); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + write("void "); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + write("await "); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + write(" "); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + var operand = node.operand; + return operand.kind === 185 /* PrefixUnaryExpression */ + && ((node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) + || (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 24 /* CommaToken */; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + writeTokenText(node.operatorToken.kind); + increaseIndentIf(indentAfterOperator, " "); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, " "); + write("?"); + increaseIndentIf(indentAfterQuestion, " "); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, " "); + write(":"); + increaseIndentIf(indentAfterColon, " "); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + write(node.asteriskToken ? "yield*" : "yield"); + emitExpressionWithPrefix(" ", node.expression); + } + function emitSpreadElementExpression(node) { + write("..."); + emitExpression(node.expression); + } + function emitClassExpression(node) { + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + write(" as "); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + write("!"); + } + // + // Misc + // + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + // + // Statements + // + function emitBlock(node, format) { + if (isSingleLineEmptyBlock(node)) { + writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + write(" "); + writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + } + else { + writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + emitBlockStatements(node); + writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + } + } + function emitBlockStatements(node) { + if (node.emitFlags & 32 /* SingleLine */) { + emitList(node, node.statements, 384 /* SingleLineBlockStatements */); + } + else { + emitList(node, node.statements, 65 /* MultiLineBlockStatements */); + } + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + write(";"); + } + function emitEmptyStatement(node) { + write(";"); + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + write(";"); + } + function emitIfStatement(node) { + var openParenPos = writeToken(88 /* IfKeyword */, node.pos, node); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos, node); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end, node); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + writeToken(80 /* ElseKeyword */, node.thenStatement.end, node); + if (node.elseStatement.kind === 203 /* IfStatement */) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (ts.isBlock(node.statement)) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emitExpression(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + emitForBinding(node.initializer); + write(";"); + emitExpressionWithPrefix(" ", node.condition); + write(";"); + emitExpressionWithPrefix(" ", node.incrementor); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emitForBinding(node.initializer); + write(" in "); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForOfStatement(node) { + var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emitForBinding(node.initializer); + write(" of "); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 219 /* VariableDeclarationList */) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + writeToken(75 /* ContinueKeyword */, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitBreakStatement(node) { + writeToken(70 /* BreakKeyword */, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + writeToken(94 /* ReturnKeyword */, node.pos, /*contextNode*/ node); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitWithStatement(node) { + write("with ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = writeToken(96 /* SwitchKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end); + write(" "); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function emitThrowStatement(node) { + write("throw"); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(76 /* DebuggerKeyword */, node.pos); + write(";"); + } + // + // Declarations + // + function emitVariableDeclaration(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitVariableDeclarationList(node) { + write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + emitList(node, node.declarations, 272 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.asteriskToken ? "function* " : "function "); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = node.emitFlags & 524288 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + tempFlags = savedTempFlags; + } + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + write(" "); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + write(";"); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (body.emitFlags & 32 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(parentNode, body) { + write(" {"); + increaseIndent(); + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker); + decreaseIndent(); + writeToken(16 /* CloseBraceToken */, body.statements.end, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var helpersEmitted = emitHelpers(body); + if (statementOffset === 0 && !helpersEmitted && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } + else { + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("class"); + emitNodeWithPrefix(" ", node.name, emitIdentifierName); + var indentedFlag = node.emitFlags & 524288 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 65 /* ClassMembers */); + write("}"); + if (indentedFlag) { + decreaseIndent(); + } + tempFlags = savedTempFlags; + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("interface "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256 /* HeritageClauses */); + write(" {"); + emitList(node, node.members, 65 /* InterfaceMembers */); + write("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("type "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + write(" = "); + emit(node.type); + write(";"); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + write("enum "); + emit(node.name); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 81 /* EnumMembers */); + write("}"); + tempFlags = savedTempFlags; + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + emit(node.name); + var body = node.body; + while (body.kind === 225 /* ModuleDeclaration */) { + write("."); + emit(body.name); + body = body.body; + } + write(" "); + emit(body); + } + function emitModuleBlock(node) { + if (isSingleLineEmptyBlock(node)) { + write("{ }"); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + write("{"); + increaseIndent(); + emitBlockStatements(node); + write("}"); + tempFlags = savedTempFlags; + } + } + function emitCaseBlock(node) { + writeToken(15 /* OpenBraceToken */, node.pos); + emitList(node, node.clauses, 65 /* CaseBlockClauses */); + writeToken(16 /* CloseBraceToken */, node.clauses.end); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + emit(node.name); + write(" = "); + emitModuleReference(node.moduleReference); + write(";"); + } + function emitModuleReference(node) { + if (node.kind === 69 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + if (node.importClause) { + emit(node.importClause); + write(" from "); + } + emitExpression(node.moduleSpecifier); + write(";"); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + write(", "); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + write("* as "); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + write(node.isExportEquals ? "export = " : "export default "); + emitExpression(node.expression); + write(";"); + } + function emitExportDeclaration(node) { + write("export "); + if (node.exportClause) { + emit(node.exportClause); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + emitExpression(node.moduleSpecifier); + } + write(";"); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + write("{"); + emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); + write("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + write(" as "); + } + emit(node.name); + } + // + // Module references + // + function emitExternalModuleReference(node) { + write("require("); + emitExpression(node.expression); + write(")"); + } + // + // JSX + // + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 131072 /* JsxElementChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + write("<"); + emitJsxTagName(node.tagName); + write(" "); + emitList(node, node.attributes, 131328 /* JsxElementAttributes */); + write("/>"); + } + function emitJsxOpeningElement(node) { + write("<"); + emitJsxTagName(node.tagName); + writeIfAny(node.attributes, " "); + emitList(node, node.attributes, 131328 /* JsxElementAttributes */); + write(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + function emitJsxClosingElement(node) { + write(""); + } + function emitJsxAttribute(node) { + emit(node.name); + emitWithPrefix("=", node.initializer); + } + function emitJsxSpreadAttribute(node) { + write("{..."); + emitExpression(node.expression); + write("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + write("{"); + emitExpression(node.expression); + write("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 69 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + // + // Clauses + // + function emitCaseClause(node) { + write("case "); + emitExpression(node.expression); + write(":"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitDefaultClause(node) { + write("default:"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitCaseOrDefaultClauseStatements(parentNode, statements) { + var emitAsSingleStatement = statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (emitAsSingleStatement) { + write(" "); + emit(statements[0]); + } + else { + emitList(parentNode, statements, 81985 /* CaseOrDefaultClauseStatements */); + } + } + function emitHeritageClause(node) { + write(" "); + writeTokenText(node.token); + write(" "); + emitList(node, node.types, 272 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + writeLine(); + var openParenPos = writeToken(72 /* CatchKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emit(node.variableDeclaration); + writeToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + write(" "); + emit(node.block); + } + // + // Property assignments + // + function emitPropertyAssignment(node) { + emit(node.name); + write(": "); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + var initializer = node.initializer; + if (!shouldSkipLeadingCommentsForNode(initializer)) { + var commentRange = initializer.commentRange || initializer; + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + write(" = "); + emitExpression(node.objectAssignmentInitializer); + } + } + // + // Enum + // + function emitEnumMember(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + // + // Top-level nodes + // + function emitSourceFile(node) { + writeLine(); + emitShebang(); + emitBodyWithDetachedComments(node, node.statements, emitSourceFileWorker); + } + function emitSourceFileWorker(node) { + var statements = node.statements; + var statementOffset = emitPrologueDirectives(statements); + var savedTempFlags = tempFlags; + tempFlags = 0; + emitHelpers(node); + emitList(node, statements, 1 /* MultiLine */, statementOffset); + tempFlags = savedTempFlags; + } + // Transformation nodes + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements, startWithNewLine) { + for (var i = 0; i < statements.length; i++) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function emitHelpers(node) { + var emitFlags = node.emitFlags; + var helpersEmitted = false; + if (emitFlags & 1 /* EmitEmitHelpers */) { + helpersEmitted = emitEmitHelpers(currentSourceFile); + } + if (emitFlags & 2 /* EmitExportStar */) { + writeLines(exportStarHelper); + helpersEmitted = true; + } + if (emitFlags & 4 /* EmitSuperHelper */) { + writeLines(superHelper); + helpersEmitted = true; + } + if (emitFlags & 8 /* EmitAdvancedSuperHelper */) { + writeLines(advancedSuperHelper); + helpersEmitted = true; + } + return helpersEmitted; + } + function emitEmitHelpers(node) { + // Only emit helpers if the user did not say otherwise. + if (compilerOptions.noEmitHelpers) { + return false; + } + // Don't emit helpers if we can import them. + if (compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + return false; + } + var helpersEmitted = false; + // Only Emit __extends function when target ES5. + // For target ES6 and above, we can emit classDeclaration as is. + if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && node.flags & 1024 /* HasClassExtends */)) { + writeLines(extendsHelper); + extendsEmitted = true; + helpersEmitted = true; + } + if (compilerOptions.jsx !== 1 /* Preserve */ && !assignEmitted && (node.flags & 16384 /* HasJsxSpreadAttributes */)) { + writeLines(assignHelper); + assignEmitted = true; + } + if (!decorateEmitted && node.flags & 2048 /* HasDecorators */) { + writeLines(decorateHelper); + if (compilerOptions.emitDecoratorMetadata) { + writeLines(metadataHelper); + } + decorateEmitted = true; + helpersEmitted = true; + } + if (!paramEmitted && node.flags & 4096 /* HasParamDecorators */) { + writeLines(paramHelper); + paramEmitted = true; + helpersEmitted = true; + } + if (!awaiterEmitted && node.flags & 8192 /* HasAsyncFunctions */) { + writeLines(awaiterHelper); + if (languageVersion < 2 /* ES6 */) { + writeLines(generatorHelper); + } + awaiterEmitted = true; + helpersEmitted = true; + } + if (helpersEmitted) { + writeLine(); + } + return helpersEmitted; + } + function writeLines(text) { + var lines = text.split(/\r\n|\r|\n/g); + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line.length) { + if (i > 0) { + writeLine(); + } + write(line); + } + } + } + // + // Helpers + // + function emitShebang() { + var shebang = ts.getShebang(currentText); + if (shebang) { + write(shebang); + writeLine(); + } + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 256 /* Modifiers */); + write(" "); + } + } + function emitWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emit); + } + function emitExpressionWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emitExpression); + } + function emitNodeWithPrefix(prefix, node, emit) { + if (node) { + write(prefix); + emit(node); + } + } + function emitWithSuffix(node, suffix) { + if (node) { + emit(node); + write(suffix); + } + } + function tryEmitSubstitute(node, emitNode, isExpression) { + if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { + var substitute = onSubstituteNode(node, isExpression); + if (substitute !== node) { + substitute.emitFlags |= 128 /* NoSubstitution */; + emitNode(substitute); + return true; + } + } + return false; + } + function tryEmitConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + write(String(constantValue)); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : getTextOfNode(node.argumentExpression); + write(" /* " + propertyName + " */"); + } + return true; + } + return false; + } + function emitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + write(" "); + emit(node); + } + else { + writeLine(); + increaseIndent(); + emit(node); + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 24577 /* Decorators */); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + } + function emitTypeParameters(parentNode, typeParameters) { + emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 1360 /* Parameters */); + } + function emitParametersForArrow(parentNode, parameters) { + if (parameters && + parameters.length === 1 && + parameters[0].type === undefined && + parameters[0].pos === parentNode.pos) { + emit(parameters[0]); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 8192 /* OptionalIfUndefined */) { + return; + } + var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + return; + } + if (format & 7680 /* BracketsMask */) { + write(getOpeningBracket(format)); + } + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { + writeLine(); + } + else if (format & 128 /* SpaceBetweenBraces */) { + write(" "); + } + } + else { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 128 /* SpaceBetweenBraces */) { + write(" "); + } + // Increase the indent, if requested. + if (format & 64 /* Indented */) { + increaseIndent(); + } + // Emit each child. + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = void 0; + var delimiter = getDelimiter(format); + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (previousSibling) { + write(delimiter); + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { + write(" "); + } + } + if (shouldEmitInterveningComments) { + var commentRange = child.commentRange || child; + emitTrailingCommentsOfPosition(commentRange.pos); + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + // Emit this child. + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { + write(","); + } + // Decrease the indent, if requested. + if (format & 64 /* Indented */) { + decreaseIndent(); + } + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 128 /* SpaceBetweenBraces */) { + write(" "); + } + } + if (format & 7680 /* BracketsMask */) { + write(getClosingBracket(format)); + } + } + function writeIfAny(nodes, text) { + if (nodes && nodes.length > 0) { + write(text); + } + } + function writeIfPresent(node, text) { + if (node !== undefined) { + write(text); + } + } + function writeToken(token, pos, contextNode) { + var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); + var tokenEndPos = writeTokenText(token, tokenStartPos); + return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); + } + function shouldSkipLeadingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; + } + function shouldSkipTrailingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + } + function writeTokenText(token, pos) { + var tokenString = ts.tokenToString(token); + write(tokenString); + return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; + } + function writeTokenNode(node) { + if (node) { + emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + writeTokenText(node.kind); + emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (valueToWriteWhenNotIndenting) { + write(valueToWriteWhenNotIndenting); + } + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return true; + } + if (format & 2 /* PreserveLines */) { + if (format & 32768 /* PreferNewLine */) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1 /* MultiLine */) { + return true; + } + else if (format & 2 /* PreserveLines */) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return nextNode.startsOnNewLine; + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return (format & 65536 /* NoTrailingNewLine */) === 0; + } + else if (format & 2 /* PreserveLines */) { + if (format & 32768 /* PreferNewLine */) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = node.startsOnNewLine; + if (startsOnNewLine === undefined) { + return (format & 32768 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 32768 /* PreferNewLine */) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + // Always use a newline for synthesized code if the synthesizer desires it. + if (node2.startsOnNewLine) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 178 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return getGeneratedIdentifier(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return ts.unescapeIdentifier(node.text); + } + else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node) { + if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode); + } + } + return ts.getLiteralText(node, currentSourceFile, languageVersion); + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } + function isSingleLineEmptyBlock(block) { + return !block.multiLine + && block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function isUniqueName(name) { + return !resolver.hasGlobalName(name) && + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); + } + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals && ts.hasProperty(node.locals, name)) { + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { + return false; + } + } + } + return true; + } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ + function makeTempVariableName(flags) { + if (flags && !(tempFlags & flags)) { + var name_41 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_41)) { + tempFlags |= flags; + return name_41; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name_42 = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) + : "_" + (count - 26); + if (isUniqueName(name_42)) { + return name_42; + } + } + } + } + // Generate a name that is unique within the current file and doesn't conflict with any names + // in global scope. The name is formed by adding an '_n' suffix to the specified base name, + // where n is a positive integer. Note that names generated by makeTempVariableName and + // makeUniqueName are guaranteed to never conflict. + function makeUniqueName(baseName) { + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (isUniqueName(generatedName)) { + return generatedNameSet[generatedName] = generatedName; + } + i++; + } + } + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); + var baseName = expr.kind === 9 /* StringLiteral */ ? + ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + return makeUniqueName(baseName); + } + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + /** + * Generates a unique name from a node. + * + * @param node A node. + */ + function generateNameForNode(node) { + switch (node.kind) { + case 69 /* Identifier */: + return makeUniqueName(getTextOfNode(node)); + case 225 /* ModuleDeclaration */: + case 224 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 230 /* ImportDeclaration */: + case 236 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 220 /* FunctionDeclaration */: + case 221 /* ClassDeclaration */: + case 235 /* ExportAssignment */: + return generateNameForExportDefault(); + case 192 /* ClassExpression */: + return generateNameForClassExpression(); + default: + return makeTempVariableName(0 /* Auto */); + } + } + /** + * Generates a unique identifier for a node. + * + * @param name A generated name. + */ + function generateName(name) { + switch (name.autoGenerateKind) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */); + case 3 /* Unique */: + return makeUniqueName(name.text); + } + ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + /** + * Gets the node from which a name should be generated. + * + * @param name A generated name wrapper. + */ + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. + if (ts.isIdentifier(node) + && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source; + return node; + } + /** + * Gets the generated identifier text from a generated identifier. + * + * @param name The generated identifier. + */ + function getGeneratedIdentifier(name) { + if (name.autoGenerateKind === 4 /* Node */) { + // Generated names generate unique names based on their original node + // and are cached based on that node's id + var node = getNodeForGeneratedName(name); + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + } + else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(generateName(name))); + } + } + function createDelimiterMap() { + var delimiters = []; + delimiters[0 /* None */] = ""; + delimiters[16 /* CommaDelimited */] = ","; + delimiters[4 /* BarDelimited */] = " |"; + delimiters[8 /* AmpersandDelimited */] = " &"; + return delimiters; + } + function getDelimiter(format) { + return delimiters[format & 28 /* DelimitersMask */]; + } + function createBracketsMap() { + var brackets = []; + brackets[512 /* Braces */] = ["{", "}"]; + brackets[1024 /* Parenthesis */] = ["(", ")"]; + brackets[2048 /* AngleBrackets */] = ["<", ">"]; + brackets[4096 /* SquareBrackets */] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 7680 /* BracketsMask */][0]; + } + function getClosingBracket(format) { + return brackets[format & 7680 /* BracketsMask */][1]; + } } ts.emitFiles = emitFiles; + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); /// /// /// var ts; (function (ts) { - /* @internal */ ts.programTime = 0; - /* @internal */ ts.emitTime = 0; - /* @internal */ ts.ioReadTime = 0; - /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - ts.version = "2.0.0"; + ts.version = "2.1.0"; var emptyArray = []; - var defaultTypeRoots = ["node_modules/@types"]; - function findConfigFile(searchPath, fileExists) { + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } while (true) { - var fileName = ts.combinePaths(searchPath, "tsconfig.json"); + var fileName = ts.combinePaths(searchPath, configName); if (fileExists(fileName)) { return fileName; } @@ -43025,54 +56905,29 @@ var ts; return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; } function moduleHasNonRelativeName(moduleName) { - if (ts.isRootedDiskPath(moduleName)) { - return false; - } - var i = moduleName.lastIndexOf("./", 1); - var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */); - return !startsWithDotSlashOrDotDotSlash; + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent; - try { - var jsonText = state.host.readFile(packageJsonPath); - jsonContent = jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - jsonContent = {}; - } - var typesFile; - var fieldName; - // first try to read content of 'typings' section (backward compatibility) - if (jsonContent.typings) { - if (typeof jsonContent.typings === "string") { - fieldName = "typings"; - typesFile = jsonContent.typings; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } } } } - // then read 'types' - if (!typesFile && jsonContent.types) { - if (typeof jsonContent.types === "string") { - fieldName = "types"; - typesFile = jsonContent.types; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); - } - } - } - if (typesFile) { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { return typesFilePath; } // Use the main module for inferring types if no types package specified and the allowJs is set @@ -43085,6 +56940,16 @@ var ts; } return undefined; } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -43097,11 +56962,32 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - if (!currentDirectory) { - return undefined; - } - return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); + return currentDirectory && getDefaultTypeRoots(currentDirectory, host); } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_15 = ts.getDirectoryPath(currentDirectory); + if (parent_15 === currentDirectory) { + break; + } + currentDirectory = parent_15; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -43381,7 +57267,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); @@ -43512,7 +57398,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } /* @internal */ @@ -43526,22 +57412,24 @@ var ts; * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First try to keep/add an extension: importing "./foo.ts" can be matched by a file "./foo.ts", and "./foo" by "./foo.d.ts" - var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingOrKeepingExtension) { - return resolvedByAddingOrKeepingExtension; + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; } - // Then try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one, e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" if (ts.hasJavaScriptFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); } } - function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); @@ -43549,29 +57437,28 @@ var ts; onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } - return ts.forEach(extensions, tryLoad); - function tryLoad(ext) { - if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { - return undefined; + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } - var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } + failedLookupLocation.push(fileName); + return undefined; } } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var packageJsonPath = pathToPackageJson(candidate); var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { @@ -43579,7 +57466,10 @@ var ts; } var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); if (typesFile) { - var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); if (result) { return result; } @@ -43599,6 +57489,9 @@ var ts; } return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); @@ -43674,15 +57567,8 @@ var ts; : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } ts.classicNameResolver = classicNameResolver; - /* @internal */ - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1 /* ES5 */, - noImplicitAny: false, - sourceMap: false - }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = {}; + var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. @@ -43693,9 +57579,10 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - var start = new Date().getTime(); + ts.performance.mark("beforeIORead"); text = ts.sys.readFile(fileName, options.charset); - ts.ioReadTime += new Date().getTime() - start; + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } catch (e) { if (onError) { @@ -43708,7 +57595,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (ts.hasProperty(existingDirectories, directoryPath)) { + if (directoryPath in existingDirectories) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -43727,11 +57614,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = {}; + outputFingerprints = ts.createMap(); } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { + if (mtimeBefore && fileName in outputFingerprints) { var fingerprint = outputFingerprints[fileName]; // If output has not been changed, and the file has no external modification if (fingerprint.byteOrderMark === writeByteOrderMark && @@ -43750,7 +57637,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - var start = new Date().getTime(); + ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -43758,7 +57645,8 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.ioWriteTime += new Date().getTime() - start; + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } catch (e) { if (onError) { @@ -43784,6 +57672,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -43797,6 +57686,22 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; + } + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -43825,33 +57730,25 @@ var ts; return []; } var resolutions = []; - var cache = {}; - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_34 = names_1[_i]; - var result = void 0; - if (ts.hasProperty(cache, name_34)) { - result = cache[name_34]; - } - else { - result = loader(name_34, containingFile); - cache[name_34] = result; - } + var cache = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_43 = names_2[_i]; + var result = name_43 in cache + ? cache[name_43] + : cache[name_43] = loader(name_43, containingFile); resolutions.push(result); } return resolutions; } - function getInferredTypesRoot(options, rootFiles, host) { - return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - } /** - * Given a set of options and a set of root files, returns the set of type directive names + * Given a set of options, returns the set of type directive names * that should be included for this program automatically. * This list could either come from the config file, * or from enumerating the types root + initial secondary types lookup location. * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options, rootFiles, host) { + function getAutomaticTypeDirectiveNames(options, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; @@ -43864,7 +57761,17 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - result = result.concat(host.getDirectories(root)); + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } } } } @@ -43879,7 +57786,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. // This works as imported modules are discovered recursively in a depth first manner, specifically: @@ -43888,14 +57795,14 @@ var ts; // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; - var currentNodeModulesJsDepth = 0; + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. - var modulesWithElidedImports = {}; - // Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled. - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -43926,10 +57833,10 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, host); if (typeReferences) { - var inferredRoot = getInferredTypesRoot(options, rootNames, host); - var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + // This containingFilename needs to match with the one used in managed-side + var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -43980,7 +57887,8 @@ var ts; getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.programTime += new Date().getTime() - start; + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -44004,10 +57912,10 @@ var ts; if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); - classifiableNames = {}; + classifiableNames = ts.createMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyMap(sourceFile.classifiableNames, classifiableNames); + ts.copyProperties(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -44032,7 +57940,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { + !ts.equalOwnProperties(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -44138,7 +58046,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, + isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -44150,8 +58058,7 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken) { - var _this = this; - return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); @@ -44187,9 +58094,10 @@ var ts; // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - var start = new Date().getTime(); + ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); - ts.emitTime += new Date().getTime() - start; + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; } function getSourceFile(fileName) { @@ -44341,16 +58249,16 @@ var ts; case 175 /* NewExpression */: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start_2 = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142 /* Parameter */: var parameter = node; if (parameter.modifiers) { - var start_3 = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -44394,8 +58302,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start_4 = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -44477,6 +58385,16 @@ var ts; var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + var externalHelpersModuleReference = ts.createNode(9 /* StringLiteral */); + externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; + externalHelpersModuleReference.parent = file; + imports = [externalHelpersModuleReference]; + } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); @@ -44507,7 +58425,7 @@ var ts; } break; case 225 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -44603,9 +58521,19 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - // See if we need to reprocess the imports due to prior skipped imports - if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { - if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { + sourceFilesFoundSearchingNodeModules[file_1.path] = false; + if (!options.noResolve) { + processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processTypeReferenceDirectives(file_1); + } + modulesWithElidedImports[file_1.path] = false; + processImportedModules(file_1, ts.getDirectoryPath(fileName)); + } + else if (file_1 && modulesWithElidedImports[file_1.path]) { + if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -44623,6 +58551,7 @@ var ts; }); filesByName.set(path, file); if (file) { + sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -44658,14 +58587,16 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; // store resolved type directive on the file - ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -44686,7 +58617,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } // don't overwrite previous resolution result saveResolution = false; @@ -44722,7 +58653,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = {}; + file.resolvedModules = ts.createMap(); var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -44737,12 +58668,9 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - sourceFilesFoundSearchingNodeModules[resolvedPath] = true; + currentNodeModulesDepth++; } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth++; - } - var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -44751,8 +58679,8 @@ var ts; findSourceFile(resolution.resolvedFileName, resolvedPath, /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth--; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; } } } @@ -44764,8 +58692,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var file = sourceFiles_5[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -44776,8 +58704,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -44824,6 +58752,9 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { + if (options.paths[key].length === 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; @@ -44870,30 +58801,30 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -44915,7 +58846,7 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files @@ -44982,6 +58913,11 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean", + experimental: true + }, { name: "emitBOM", type: "boolean" @@ -45012,10 +58948,10 @@ var ts; }, { name: "jsx", - type: { + type: ts.createMap({ "preserve": 1 /* Preserve */, "react": 2 /* React */ - }, + }), paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -45042,7 +58978,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -45050,16 +58986,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }, + }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: { + type: ts.createMap({ "crlf": 0 /* CarriageReturnLineFeed */, "lf": 1 /* LineFeed */ - }, + }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -45077,6 +59013,10 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, + { + name: "noErrorTruncation", + type: "boolean" + }, { name: "noImplicitAny", type: "boolean", @@ -45090,12 +59030,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Locals + description: ts.Diagnostics.Report_errors_on_unused_locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters }, { name: "noLib", @@ -45201,12 +59141,12 @@ var ts; { name: "target", shortName: "t", - type: { + type: ts.createMap({ "es3": 0 /* ES3 */, "es5": 1 /* ES5 */, "es6": 2 /* ES6 */, "es2015": 2 /* ES2015 */ - }, + }), description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -45235,11 +59175,12 @@ var ts; }, { name: "moduleResolution", - type: { + type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }, - description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 + }), + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + paramType: ts.Diagnostics.STRATEGY }, { name: "allowUnusedLabels", @@ -45343,7 +59284,7 @@ var ts; type: "list", element: { name: "lib", - type: { + type: ts.createMap({ // JavaScript only "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", @@ -45353,6 +59294,7 @@ var ts; "es2017": "lib.es2017.d.ts", // Host only "dom": "lib.dom.d.ts", + "dom.iterable": "lib.dom.iterable.d.ts", "webworker": "lib.webworker.d.ts", "scripthost": "lib.scripthost.d.ts", // ES2015 Or ESNext By-feature options @@ -45368,7 +59310,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - } + }) }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -45380,6 +59322,11 @@ var ts; name: "strictNullChecks", type: "boolean", description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "importHelpers", + type: "boolean", + description: ts.Diagnostics.Import_emit_helpers_from_tslib } ]; /* @internal */ @@ -45405,14 +59352,21 @@ var ts; } } ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + noImplicitAny: false, + sourceMap: false + }; var optionNameMapCache; /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = {}; - var shortOptionNames = {}; + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -45426,9 +59380,9 @@ var ts; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - ts.forEachKey(opt.type, function (key) { + for (var key in opt.type) { namesOfType.push(" '" + key + "'"); - }); + } return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; @@ -45436,7 +59390,7 @@ var ts; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (ts.hasProperty(map, key)) { + if (key in map) { return map[key]; } else { @@ -45488,10 +59442,10 @@ var ts; else if (s.charCodeAt(0) === 45 /* minus */) { s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); // Try to translate short option names to their full equivalents. - if (ts.hasProperty(shortOptionNames, s)) { + if (s in shortOptionNames) { s = shortOptionNames[s]; } - if (ts.hasProperty(optionNameMap, s)) { + if (s in optionNameMap) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -45603,6 +59557,90 @@ var ts; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var configurations = { + compilerOptions: serializeCompilerOptions(compilerOptions) + }; + if (fileNames && fileNames.length) { + // only set the files property if we have at least one file + configurations.files = fileNames; + } + return configurations; + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + for (var key in customTypeMap) { + if (customTypeMap[key] === value) { + return key; + } + } + return undefined; + } + function serializeCompilerOptions(options) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name_44 in options) { + if (ts.hasProperty(options, name_44)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + switch (name_44) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_44]; + var optionDefinition = optionsNameMap[name_44.toLowerCase()]; + if (optionDefinition) { + var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + result[name_44] = value; + } + else { + if (optionDefinition.type === "list") { + var convertedValue = []; + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); + } + result[name_44] = convertedValue; + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result[name_44] = getNameOfCompilerOptionValue(value, customTypeMap); + } + } + } + break; + } + } + } + return result; + } + } + ts.generateTSConfig = generateTSConfig; /** * Remove the comments from a json like text. * Comments can be single line comments (starting with # or //) or multiline comments using / * * / @@ -45627,9 +59665,6 @@ var ts; } return output; } - // Skip over any minified JavaScript files (ending in ".min.js") - // Skip over dotted files and folders as well - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -45637,14 +59672,46 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } var errors = []; - var compilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var options = ts.extend(existingOptions, compilerOptions); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + return { + options: {}, + fileNames: [], + typingOptions: {}, + raw: json, + errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], + wildcardDirectories: {} + }; + } + var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + if (json["extends"]) { + var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; + if (typeof json["extends"] === "string") { + _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseOptions = _b[3]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + if (include && !json["include"]) { + json["include"] = include; + } + if (exclude && !json["exclude"]) { + json["exclude"] = exclude; + } + if (files && !json["files"]) { + json["files"] = files; + } + options = ts.assign({}, baseOptions, options); + } + options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; return { options: options, fileNames: fileNames, @@ -45653,6 +59720,38 @@ var ts; errors: errors, wildcardDirectories: wildcardDirectories }; + function tryExtendsName(extendedConfig) { + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + return; + } + var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) + var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); + errors.push.apply(errors, result.errors); + var _a = ts.map(["include", "exclude", "files"], function (key) { + if (!json[key] && extendedResult.config[key]) { + return ts.map(extendedResult.config[key], updatePath); + } + }), include = _a[0], exclude = _a[1], files = _a[2]; + return [include, exclude, files, result.options]; + } function getFileNames(errors) { var fileNames; if (ts.hasProperty(json, "files")) { @@ -45685,19 +59784,19 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - // By default, exclude common package folders + // By default, exclude common package folders and the outDir excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; - } - // Always exclude the output directory unless explicitly included - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - excludeSpecs.push(outDir); + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } + var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { @@ -45713,7 +59812,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -45730,7 +59829,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (ts.hasProperty(optionNameMap, id)) { + if (id in optionNameMap) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -45765,7 +59864,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (ts.hasProperty(opt.type, key)) { + if (key in opt.type) { return opt.type[key]; } else { @@ -45865,11 +59964,11 @@ var ts; // Literal file names (provided via the "files" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map later when when including // wildcard paths. - var literalFileMap = {}; + var literalFileMap = ts.createMap(); // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. - var wildcardFileMap = {}; + var wildcardFileMap = ts.createMap(); if (include) { include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); } @@ -45905,16 +60004,13 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } - if (ignoreFileNamePattern.test(file)) { - continue; - } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // "include" array. If there is a lower priority extension in the // same directory, we should remove it. removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + if (!(key in literalFileMap) && !(key in wildcardFileMap)) { wildcardFileMap[key] = file; } } @@ -45963,20 +60059,20 @@ var ts; // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = {}; + var wildcardDirectories = ts.createMap(); if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_35 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_35)) { + var name_45 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_45)) { continue; } - var match = wildcardDirectoryPattern.exec(name_35); + var match = wildcardDirectoryPattern.exec(name_45); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; - var existingFlags = ts.getProperty(wildcardDirectories, key); + var flags = watchRecursivePattern.test(name_45) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1 /* Recursive */) { @@ -45987,12 +60083,10 @@ var ts; } // Remove any subpaths under an existing recursively watched directory. for (var key in wildcardDirectories) { - if (ts.hasProperty(wildcardDirectories, key)) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; - } + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; } } } @@ -46013,7 +60107,7 @@ var ts; for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { return true; } } @@ -46063,193 +60157,6485 @@ var ts; return key.toLowerCase(); } })(ts || (ts = {})); +var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + var TextChange = (function () { + function TextChange() { + } + return TextChange; + }()); + ts.TextChange = TextChange; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind.none = "none"; + HighlightSpanKind.definition = "definition"; + HighlightSpanKind.reference = "reference"; + HighlightSpanKind.writtenReference = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(ts.IndentStyle || (ts.IndentStyle = {})); + var IndentStyle = ts.IndentStyle; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(ts.OutputFileType || (ts.OutputFileType = {})); + var OutputFileType = ts.OutputFileType; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["None"] = 0] = "None"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + })(ts.EndOfLineState || (ts.EndOfLineState = {})); + var EndOfLineState = ts.EndOfLineState; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + })(ts.TokenClass || (ts.TokenClass = {})); + var TokenClass = ts.TokenClass; + // TODO: move these to enums + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind.unknown = ""; + ScriptElementKind.warning = "warning"; + /** predefined type (void) or keyword (class) */ + ScriptElementKind.keyword = "keyword"; + /** top level script node */ + ScriptElementKind.scriptElement = "script"; + /** module foo {} */ + ScriptElementKind.moduleElement = "module"; + /** class X {} */ + ScriptElementKind.classElement = "class"; + /** var x = class X {} */ + ScriptElementKind.localClassElement = "local class"; + /** interface Y {} */ + ScriptElementKind.interfaceElement = "interface"; + /** type T = ... */ + ScriptElementKind.typeElement = "type"; + /** enum E */ + ScriptElementKind.enumElement = "enum"; + // TODO: GH#9983 + ScriptElementKind.enumMemberElement = "const"; + /** + * Inside module and script only + * const v = .. + */ + ScriptElementKind.variableElement = "var"; + /** Inside function */ + ScriptElementKind.localVariableElement = "local var"; + /** + * Inside module and script only + * function f() { } + */ + ScriptElementKind.functionElement = "function"; + /** Inside function */ + ScriptElementKind.localFunctionElement = "local function"; + /** class X { [public|private]* foo() {} } */ + ScriptElementKind.memberFunctionElement = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + ScriptElementKind.memberGetAccessorElement = "getter"; + ScriptElementKind.memberSetAccessorElement = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + ScriptElementKind.memberVariableElement = "property"; + /** class X { constructor() { } } */ + ScriptElementKind.constructorImplementationElement = "constructor"; + /** interface Y { ():number; } */ + ScriptElementKind.callSignatureElement = "call"; + /** interface Y { []:number; } */ + ScriptElementKind.indexSignatureElement = "index"; + /** interface Y { new():Y; } */ + ScriptElementKind.constructSignatureElement = "construct"; + /** function foo(*Y*: string) */ + ScriptElementKind.parameterElement = "parameter"; + ScriptElementKind.typeParameterElement = "type parameter"; + ScriptElementKind.primitiveType = "primitive type"; + ScriptElementKind.label = "label"; + ScriptElementKind.alias = "alias"; + ScriptElementKind.constElement = "const"; + ScriptElementKind.letElement = "let"; + ScriptElementKind.directory = "directory"; + ScriptElementKind.externalModuleName = "external module name"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier.none = ""; + ScriptElementKindModifier.publicMemberModifier = "public"; + ScriptElementKindModifier.privateMemberModifier = "private"; + ScriptElementKindModifier.protectedMemberModifier = "protected"; + ScriptElementKindModifier.exportedModifier = "export"; + ScriptElementKindModifier.ambientModifier = "declare"; + ScriptElementKindModifier.staticModifier = "static"; + ScriptElementKindModifier.abstractModifier = "abstract"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames = (function () { + function ClassificationTypeNames() { + } + return ClassificationTypeNames; + }()); + ClassificationTypeNames.comment = "comment"; + ClassificationTypeNames.identifier = "identifier"; + ClassificationTypeNames.keyword = "keyword"; + ClassificationTypeNames.numericLiteral = "number"; + ClassificationTypeNames.operator = "operator"; + ClassificationTypeNames.stringLiteral = "string"; + ClassificationTypeNames.whiteSpace = "whitespace"; + ClassificationTypeNames.text = "text"; + ClassificationTypeNames.punctuation = "punctuation"; + ClassificationTypeNames.className = "class name"; + ClassificationTypeNames.enumName = "enum name"; + ClassificationTypeNames.interfaceName = "interface name"; + ClassificationTypeNames.moduleName = "module name"; + ClassificationTypeNames.typeParameterName = "type parameter name"; + ClassificationTypeNames.typeAliasName = "type alias name"; + ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; + ts.ClassificationTypeNames = ClassificationTypeNames; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + })(ts.ClassificationType || (ts.ClassificationType = {})); + var ClassificationType = ts.ClassificationType; +})(ts || (ts = {})); +// These utilities are common to multiple language service features. /* @internal */ var ts; (function (ts) { - var OutliningElementsCollector; - (function (OutliningElementsCollector) { - function collectElements(sourceFile) { - var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { - if (hintSpanNode && startElement && endElement) { - var span = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), - hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + ts.scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); + ts.emptyArray = []; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(ts.SemanticMeaning || (ts.SemanticMeaning = {})); + var SemanticMeaning = ts.SemanticMeaning; + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 142 /* Parameter */: + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 253 /* PropertyAssignment */: + case 254 /* ShorthandPropertyAssignment */: + case 255 /* EnumMember */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 252 /* CatchClause */: + return 1 /* Value */; + case 141 /* TypeParameter */: + case 222 /* InterfaceDeclaration */: + case 223 /* TypeAliasDeclaration */: + case 159 /* TypeLiteral */: + return 2 /* Type */; + case 221 /* ClassDeclaration */: + case 224 /* EnumDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 225 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { + return 4 /* Namespace */ | 1 /* Value */; } - } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; } + else { + return 4 /* Namespace */; + } + case 233 /* NamedImports */: + case 234 /* ImportSpecifier */: + case 229 /* ImportEqualsDeclaration */: + case 230 /* ImportDeclaration */: + case 235 /* ExportAssignment */: + case 236 /* ExportDeclaration */: + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + // An external module can be a Value + case 256 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.parent.kind === 235 /* ExportAssignment */) { + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + else if (isInRightSideOfImport(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2 /* Type */; + } + else if (isNamespaceReference(node)) { + return 4 /* Namespace */; + } + else { + return 1 /* Value */; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + ts.Debug.assert(node.kind === 69 /* Identifier */); + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (node.parent.kind === 139 /* QualifiedName */ && + node.parent.right === node && + node.parent.parent.kind === 229 /* ImportEqualsDeclaration */) { + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + return 4 /* Namespace */; + } + function isInRightSideOfImport(node) { + while (node.parent.kind === 139 /* QualifiedName */) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 139 /* QualifiedName */) { + while (root.parent && root.parent.kind === 139 /* QualifiedName */) { + root = root.parent; } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var currentComment = comments_2[_i]; - // For single line comments, combine consecutive ones (2 or more) into - // a single span from the start of the first till the end of the last - if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; + isLastClause = root.right === node; + } + return root.parent.kind === 155 /* TypeReference */ && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 172 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 172 /* PropertyAccessExpression */) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 194 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 251 /* HeritageClause */) { + var decl = root.parent.parent.parent; + return (decl.kind === 221 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 222 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + return node.parent.kind === 155 /* TypeReference */ || + (node.parent.kind === 194 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || + node.kind === 165 /* ThisType */; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 174 /* CallExpression */); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 175 /* NewExpression */); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node, kind) { + var target = climbPastPropertyAccess(node); + return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 214 /* LabeledStatement */ && referenceNode.label.text === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function isJumpStatementTarget(node) { + return node.kind === 69 /* Identifier */ && + (node.parent.kind === 210 /* BreakStatement */ || node.parent.kind === 209 /* ContinueStatement */) && + node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 69 /* Identifier */ && + node.parent.kind === 214 /* LabeledStatement */ && + node.parent.label === node; + } + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 225 /* ModuleDeclaration */ && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 69 /* Identifier */ && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { + switch (node.parent.kind) { + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 253 /* PropertyAssignment */: + case 255 /* EnumMember */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 225 /* ModuleDeclaration */: + return node.parent.name === node; + case 173 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 140 /* ComputedPropertyName */: + return true; + } + } + return false; + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + /** Returns true if the position is within a comment */ + function isInsideComment(sourceFile, token, position) { + // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment + return position <= token.getStart(sourceFile) && + (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || + isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); + function isInsideCommentRange(comments) { + return ts.forEach(comments, function (comment) { + // either we are 1. completely inside the comment, or 2. at the end of the comment + if (comment.pos < position && position < comment.end) { + return true; + } + else if (position === comment.end) { + var text = sourceFile.text; + var width = comment.end - comment.pos; + // is single line comment or just /* + if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { + return true; + } + else { + // is unterminated multi-line comment + return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && + text.charCodeAt(comment.end - 2) === 42 /* asterisk */); + } + } + return false; + }); + } + } + ts.isInsideComment = isInsideComment; + function getContainerNode(node) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 256 /* SourceFile */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 224 /* EnumDeclaration */: + case 225 /* ModuleDeclaration */: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + case 225 /* ModuleDeclaration */: + return ts.ScriptElementKind.moduleElement; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + return ts.ScriptElementKind.classElement; + case 222 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; + case 223 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; + case 224 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; + case 218 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 169 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + return ts.ScriptElementKind.functionElement; + case 149 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; + case 150 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + return ts.ScriptElementKind.memberFunctionElement; + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + return ts.ScriptElementKind.memberVariableElement; + case 153 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; + case 152 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; + case 151 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; + case 148 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; + case 141 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; + case 255 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; + case 142 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportSpecifier */: + case 231 /* ImportClause */: + case 238 /* ExportSpecifier */: + case 232 /* NamespaceImport */: + return ts.ScriptElementKind.alias; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ts.ScriptElementKind.constElement + : ts.isLet(v) + ? ts.ScriptElementKind.letElement + : ts.ScriptElementKind.variableElement; + } + } + ts.getNodeKind = getNodeKind; + function getStringLiteralTypeForNode(node, typeChecker) { + var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; + var type = typeChecker.getTypeAtLocation(searchNode); + if (type && type.flags & 32 /* StringLiteral */) { + return type; + } + return undefined; + } + ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; + function isThis(node) { + switch (node.kind) { + case 97 /* ThisKeyword */: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case 69 /* Identifier */: + // 'this' as a parameter + return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + default: + return false; + } + } + ts.isThis = isThis; + // Matches the beginning of a triple slash directive + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + function positionBelongsToNode(candidate, position, sourceFile) { + return candidate.end > position || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 224 /* EnumDeclaration */: + case 171 /* ObjectLiteralExpression */: + case 167 /* ObjectBindingPattern */: + case 159 /* TypeLiteral */: + case 199 /* Block */: + case 226 /* ModuleBlock */: + case 227 /* CaseBlock */: + case 233 /* NamedImports */: + case 237 /* NamedExports */: + return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); + case 252 /* CatchClause */: + return isCompletedNode(n.block, sourceFile); + case 175 /* NewExpression */: + if (!n.arguments) { + return true; + } + // fall through + case 174 /* CallExpression */: + case 178 /* ParenthesizedExpression */: + case 164 /* ParenthesizedType */: + return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + case 156 /* FunctionType */: + case 157 /* ConstructorType */: + return isCompletedNode(n.type, sourceFile); + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 152 /* ConstructSignature */: + case 151 /* CallSignature */: + case 180 /* ArrowFunction */: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); + case 225 /* ModuleDeclaration */: + return n.body && isCompletedNode(n.body, sourceFile); + case 203 /* IfStatement */: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 202 /* ExpressionStatement */: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 23 /* SemicolonToken */); + case 170 /* ArrayLiteralExpression */: + case 168 /* ArrayBindingPattern */: + case 173 /* ElementAccessExpression */: + case 140 /* ComputedPropertyName */: + case 161 /* TupleType */: + return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); + case 153 /* IndexSignature */: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + case 249 /* CaseClause */: + case 250 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed + return false; + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + case 205 /* WhileStatement */: + return isCompletedNode(n.statement, sourceFile); + case 204 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); + if (hasWhileKeyword) { + return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + } + return isCompletedNode(n.statement, sourceFile); + case 158 /* TypeQuery */: + return isCompletedNode(n.exprName, sourceFile); + case 182 /* TypeOfExpression */: + case 181 /* DeleteExpression */: + case 183 /* VoidExpression */: + case 190 /* YieldExpression */: + case 191 /* SpreadElementExpression */: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 176 /* TaggedTemplateExpression */: + return isCompletedNode(n.template, sourceFile); + case 189 /* TemplateExpression */: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 197 /* TemplateSpan */: + return ts.nodeIsPresent(n.literal); + case 236 /* ExportDeclaration */: + case 230 /* ImportDeclaration */: + return ts.nodeIsPresent(n.moduleSpecifier); + case 185 /* PrefixUnaryExpression */: + return isCompletedNode(n.operand, sourceFile); + case 187 /* BinaryExpression */: + return isCompletedNode(n.right, sourceFile); + case 188 /* ConditionalExpression */: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + ts.isCompletedNode = isCompletedNode; + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var last = ts.lastOrUndefined(children); + if (last.kind === expectedLastToken) { + return true; + } + else if (last.kind === 23 /* SemicolonToken */ && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOf(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). + var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { + // find syntax list that covers the span of the node + if (c.kind === 286 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + return c; + } + }); + // Either we didn't find an appropriate list, or the list must contain us. + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + /* Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is keyword or identifier)) + */ + function getTouchingWord(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + } + ts.getTouchingWord = getTouchingWord; + /* Gets the token whose text has range [start, end) and position >= start + * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) + */ + function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ + function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); + } + ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); + } + ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + var current = sourceFile; + outer: while (true) { + if (isToken(current)) { + // exit early + return current; + } + if (includeJsDocComment) { + var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); + for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { + var jsDocChild = jsDocChildren_1[_i]; + var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = jsDocChild.getEnd(); + if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { + current = jsDocChild; + continue outer; } - else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, /*autoCollapse*/ false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } } } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); } } - function combineAndAddMultipleSingleLineComments(count, start, end) { - // Only outline spans of two or more consecutive single line comments - if (count > 1) { - var multipleSingleLineComments = { - pos: start, - end: end, - kind: 2 /* SingleLineCommentTrivia */ - }; - addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); + // find the child that contains 'position' + for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { + var child = current.getChildAt(i); + // all jsDocComment nodes were already visited + if (ts.isJSDocNode(child)) { + continue; + } + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } + } } } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180 /* ArrowFunction */; + return current; + } + } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ + function findTokenOnLeftOfPosition(file, position) { + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position); + if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent) { + return find(parent); + function find(n) { + if (isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; } - var depth = 0; - var maxDepth = 20; - function walk(n) { - if (depth > maxDepth) { + var children = n.getChildren(); + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + (child.pos === previousToken.end); + if (shouldDiveInChildNode && nodeHasTokens(child)) { + return find(child); + } + } + return undefined; + } + } + ts.findNextToken = findNextToken; + function findPrecedingToken(position, sourceFile, startNode) { + return find(startNode || sourceFile); + function findRightmostToken(n) { + if (isToken(n) || n.kind === 244 /* JsxText */) { + return n; + } + var children = n.getChildren(); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + return candidate && findRightmostToken(candidate); + } + function find(n) { + if (isToken(n) || n.kind === 244 /* JsxText */) { + return n; + } + var children = n.getChildren(); + for (var i = 0, len = children.length; i < len; i++) { + var child = children[i]; + // condition 'position < child.end' checks if child node end after the position + // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' + // aaaa___bbbb___$__ccc + // after we found child node with end after the position we check if start of the node is after the position. + // if yes - then position is in the trivia and we need to look into the previous child to find the token in question. + // if no - position is in the node itself so we should recurse in it. + // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). + // if this is the case - then we should assume that token in question is located in previous child. + if (position < child.end && (nodeHasTokens(child) || child.kind === 244 /* JsxText */)) { + var start = child.getStart(sourceFile); + var lookInPreviousChild = (start >= position) || + (child.kind === 244 /* JsxText */ && start === child.end); // whitespace only JsxText + if (lookInPreviousChild) { + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + return candidate && findRightmostToken(candidate); + } + else { + // candidate should be in this node + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 256 /* SourceFile */); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' + if (children.length) { + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + return candidate && findRightmostToken(candidate); + } + } + /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + if (nodeHasTokens(children[i])) { + return children[i]; + } + } + } + } + ts.findPrecedingToken = findPrecedingToken; + function isInString(sourceFile, position) { + var previousToken = findPrecedingToken(position, sourceFile); + if (previousToken && previousToken.kind === 9 /* StringLiteral */) { + var start = previousToken.getStart(); + var end = previousToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + function isInComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); + } + ts.isInComment = isInComment; + /** + * returns true if the position is in between the open and close elements of an JSX expression. + */ + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 244 /* JsxText */) { + return true; + } + //
Hello |
+ if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { + return true; + } + //
{ |
or
+ if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { + return true; + } + //
{ + // | + // } < /div> + if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { + return true; + } + //
|
+ if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + /** + * Returns true if the cursor at position in sourceFile is within a comment that additionally + * satisfies predicate, and false otherwise. + */ + function isInCommentHelper(sourceFile, position, predicate) { + var token = getTokenAtPosition(sourceFile, position); + if (token && position <= token.getStart(sourceFile)) { + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + // The end marker of a single-line comment does not include the newline character. + // In the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + return predicate ? + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && + predicate(c); }) : + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + } + return false; + } + ts.isInCommentHelper = isInCommentHelper; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + // First, we have to see if this position actually landed in a comment. + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + return ts.forEach(commentRanges, jsDocPrefix); + function jsDocPrefix(c) { + var text = sourceFile.text; + return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; + } + } + ts.hasDocComment = hasDocComment; + /** + * Get the corresponding JSDocTag node if the position is in a jsDoc comment + */ + function getJsDocTagAtPosition(sourceFile, position) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (isToken(node)) { + switch (node.kind) { + case 102 /* VarKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + // if the current token is var, let or const, skip the VariableDeclarationList + node = node.parent === undefined ? undefined : node.parent.parent; + break; + default: + node = node.parent; + break; + } + } + if (node) { + if (node.jsDocComments) { + for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + if (jsDocComment.tags) { + for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.pos <= position && position <= tag.end) { + return tag; + } + } + } + } + } + } + return undefined; + } + ts.getJsDocTagAtPosition = getJsDocTagAtPosition; + function nodeHasTokens(n) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note, that getWidth() does not take trivia into account. + return n.getWidth() !== 0; + } + function getNodeModifiers(node) { + var flags = ts.getCombinedModifierFlags(node); + var result = []; + if (flags & 8 /* Private */) + result.push(ts.ScriptElementKindModifier.privateMemberModifier); + if (flags & 16 /* Protected */) + result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + if (flags & 4 /* Public */) + result.push(ts.ScriptElementKindModifier.publicMemberModifier); + if (flags & 32 /* Static */) + result.push(ts.ScriptElementKindModifier.staticModifier); + if (flags & 128 /* Abstract */) + result.push(ts.ScriptElementKindModifier.abstractModifier); + if (flags & 1 /* Export */) + result.push(ts.ScriptElementKindModifier.exportedModifier); + if (ts.isInAmbientContext(node)) + result.push(ts.ScriptElementKindModifier.ambientModifier); + return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 155 /* TypeReference */ || node.kind === 174 /* CallExpression */) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 221 /* ClassDeclaration */ || node.kind === 222 /* InterfaceDeclaration */) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 138 /* LastToken */; + } + ts.isToken = isToken; + function isWord(kind) { + return kind === 69 /* Identifier */ || ts.isKeyword(kind); + } + ts.isWord = isWord; + function isPropertyName(kind) { + return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); + } + function isComment(kind) { + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 9 /* StringLiteral */ + || kind === 10 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 15 /* FirstPunctuation */ <= kind && kind <= 68 /* LastPunctuation */; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 170 /* ArrayLiteralExpression */ || + node.kind === 171 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 187 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 208 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function hasTrailingDirectorySeparator(path) { + var lastCharacter = path.charAt(path.length - 1); + return lastCharacter === "/" || lastCharacter === "\\"; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function isInReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isReferenceComment); + function isReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isNonReferenceComment); + function isNonReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return !tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInNonReferenceComment = isInNonReferenceComment; +})(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ +var ts; +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var displayParts; + var lineStart; + var indent; + resetWriter(); + return { + displayParts: function () { return displayParts; }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: function () { }, + reportInaccessibleThisError: function () { } + }; + function writeIndent() { + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + writeIndent(); + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + writeIndent(); + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol), symbol); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3 /* Variable */) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4 /* Property */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768 /* GetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536 /* SetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8 /* EnumMember */) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16 /* Function */) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32 /* Class */) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64 /* Interface */) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384 /* Enum */) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536 /* Module */) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192 /* Method */) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144 /* TypeParameter */) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288 /* TypeAlias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 8388608 /* Alias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind, symbol) { + return { + text: text, + kind: ts.SymbolDisplayPartKind[kind] + }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ + function getNewLineOrDefaultFromHost(host) { + return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + writeDisplayParts(displayPartWriter); + var result = displayPartWriter.displayParts(); + displayPartWriter.clear(); + return result; + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + return mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function getDeclaredName(typeChecker, symbol, location) { + // If this is an export or import specifier it could have been renamed using the 'as' syntax. + // If so we want to search for whatever is under the cursor. + if (isImportOrExportSpecifierName(location)) { + return location.getText(); + } + else if (ts.isStringOrNumericLiteral(location.kind) && + location.parent.kind === 140 /* ComputedPropertyName */) { + return location.text; + } + // Try to get the local symbol if we're dealing with an 'export default' + // since that symbol has the "true" name. + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); + return name; + } + ts.getDeclaredName = getDeclaredName; + function isImportOrExportSpecifierName(location) { + return location.parent && + (location.parent.kind === 234 /* ImportSpecifier */ || location.parent.kind === 238 /* ExportSpecifier */) && + location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && + name.charCodeAt(0) === name.charCodeAt(length - 1) && + (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + return name.substring(1, length - 1); + } + ; + return name; + } + ts.stripQuotes = stripQuotes; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + // First check to see if the script kind was specified by the host. Chances are the host + // may override the default script kind for the file extension. + var scriptKind; + if (host && host.getScriptKind) { + scriptKind = host.getScriptKind(fileName); + } + if (!scriptKind) { + scriptKind = ts.getScriptKindFromFileName(fileName); + } + return ts.ensureScriptKind(fileName, scriptKind); + } + ts.getScriptKind = getScriptKind; + function parseAndReEmitConfigJSONFile(content) { + var options = { + fileName: "config.js", + compilerOptions: { + target: 2 /* ES6 */, + removeComments: true + }, + reportDiagnostics: true + }; + var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; + // Becasue the content was wrapped in "()", the start position of diagnostics needs to be subtract by 1 + // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these + // as well + var trimmedOutput = outputText.trim(); + var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; +})(ts || (ts = {})); +var ts; +(function (ts) { + /// Classifier + function createClassifier() { + var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false); + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = []; + noRegexTable[69 /* Identifier */] = true; + noRegexTable[9 /* StringLiteral */] = true; + noRegexTable[8 /* NumericLiteral */] = true; + noRegexTable[10 /* RegularExpressionLiteral */] = true; + noRegexTable[97 /* ThisKeyword */] = true; + noRegexTable[41 /* PlusPlusToken */] = true; + noRegexTable[42 /* MinusMinusToken */] = true; + noRegexTable[18 /* CloseParenToken */] = true; + noRegexTable[20 /* CloseBracketToken */] = true; + noRegexTable[16 /* CloseBraceToken */] = true; + noRegexTable[99 /* TrueKeyword */] = true; + noRegexTable[84 /* FalseKeyword */] = true; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (ts.isAccessibilityModifier(keyword1)) { + if (keyword2 === 123 /* GetKeyword */ || + keyword2 === 131 /* SetKeyword */ || + keyword2 === 121 /* ConstructorKeyword */ || + keyword2 === 113 /* StaticKeyword */) { + // Allow things like "public get", "public constructor" and "public static". + // These are all legal. + return true; + } + // Any other keyword following "public" is actually an identifier an not a real + // keyword. + return false; + } + // Assume any other keyword combination is legal. This can be refined in the future + // if there are more cases we want the classifier to be better at. + return true; + } + function convertClassifications(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0, n = dense.length; i < n; i += 3) { + var start = dense[i]; + var length_4 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } + } + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; + } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + default: + return ts.TokenClass.Identifier; + } + } + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + 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 getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var offset = 0; + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Empty out the template stack for reuse. + while (templateStack.length > 0) { + templateStack.pop(); + } + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + text = "\"\\\n" + text; + offset = 3; + break; + case 2 /* InSingleQuoteStringLiteral */: + text = "'\\\n" + text; + offset = 3; + break; + case 1 /* InMultiLineCommentTrivia */: + text = "/*\n" + text; + offset = 3; + break; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + text = "`\n" + text; + offset = 2; + break; + case 5 /* InTemplateMiddleOrTail */: + text = "}\n" + text; + offset = 2; + // fallthrough + case 6 /* InTemplateSubstitutionPosition */: + templateStack.push(12 /* TemplateHead */); + break; + } + scanner.setText(text); + var result = { + endOfLineState: 0 /* None */, + spans: [] + }; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { + token = 10 /* RegularExpressionLiteral */; + } + } + else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { + token = 69 /* Identifier */; + } + else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 69 /* Identifier */; + } + else if (lastNonTriviaToken === 69 /* Identifier */ && + token === 25 /* LessThanToken */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + else if (token === 117 /* AnyKeyword */ || + token === 132 /* StringKeyword */ || + token === 130 /* NumberKeyword */ || + token === 120 /* BooleanKeyword */ || + token === 133 /* SymbolKeyword */) { + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 69 /* Identifier */; + } + } + else if (token === 12 /* TemplateHead */) { + templateStack.push(token); + } + else if (token === 15 /* OpenBraceToken */) { + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + templateStack.push(token); + } + } + else if (token === 16 /* CloseBraceToken */) { + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 12 /* TemplateHead */) { + token = scanner.reScanTemplateToken(); + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 14 /* TemplateTail */) { + templateStack.pop(); + } + else { + ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); + } + } + else { + ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); + templateStack.pop(); + } + } + } + lastNonTriviaToken = token; + } + processToken(); + } while (token !== 1 /* EndOfFileToken */); + return result; + function processToken() { + var start = scanner.getTokenPos(); + var end = scanner.getTextPos(); + addResult(start, end, classFromKind(token)); + if (end >= text.length) { + if (token === 9 /* StringLiteral */) { + // Check to see if we finished up on a multiline string literal. + var tokenText = scanner.getTokenText(); + if (scanner.isUnterminated()) { + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if (numBackslashes & 1) { + var quoteChar = tokenText.charCodeAt(0); + result.endOfLineState = quoteChar === 34 /* doubleQuote */ + ? 3 /* InDoubleQuoteStringLiteral */ + : 2 /* InSingleQuoteStringLiteral */; + } + } + } + else if (token === 3 /* MultiLineCommentTrivia */) { + // Check to see if the multiline comment was unclosed. + if (scanner.isUnterminated()) { + result.endOfLineState = 1 /* InMultiLineCommentTrivia */; + } + } + else if (ts.isTemplateLiteralKind(token)) { + if (scanner.isUnterminated()) { + if (token === 14 /* TemplateTail */) { + result.endOfLineState = 5 /* InTemplateMiddleOrTail */; + } + else if (token === 11 /* NoSubstitutionTemplateLiteral */) { + result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + } + else { + ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + } + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { + result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; + } + } + } + function addResult(start, end, classification) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. return; } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); + 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; } - switch (n.kind) { - case 199 /* Block */: - if (!ts.isFunctionBlock(n)) { - var parent_15 = n.parent; - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); - // Check if the block is standalone, or 'attached' to some parent statement. - // If the latter, we want to collapse the block, but consider its hint span - // to be the entire span of the parent. - if (parent_15.kind === 204 /* DoStatement */ || - parent_15.kind === 207 /* ForInStatement */ || - parent_15.kind === 208 /* ForOfStatement */ || - parent_15.kind === 206 /* ForStatement */ || - parent_15.kind === 203 /* IfStatement */ || - parent_15.kind === 205 /* WhileStatement */ || - parent_15.kind === 212 /* WithStatement */ || - parent_15.kind === 252 /* CatchClause */) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + start -= offset; + end -= offset; + var length = end - start; + if (length > 0) { + result.spans.push(start); + result.spans.push(length); + result.spans.push(classification); + } + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 37 /* AsteriskToken */: + case 39 /* SlashToken */: + case 40 /* PercentToken */: + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 43 /* LessThanLessThanToken */: + case 44 /* GreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 25 /* LessThanToken */: + case 27 /* GreaterThanToken */: + case 28 /* LessThanEqualsToken */: + case 29 /* GreaterThanEqualsToken */: + case 91 /* InstanceOfKeyword */: + case 90 /* InKeyword */: + case 116 /* AsKeyword */: + case 30 /* EqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + case 32 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + case 46 /* AmpersandToken */: + case 48 /* CaretToken */: + case 47 /* BarToken */: + case 51 /* AmpersandAmpersandToken */: + case 52 /* BarBarToken */: + case 67 /* BarEqualsToken */: + case 66 /* AmpersandEqualsToken */: + case 68 /* CaretEqualsToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 57 /* PlusEqualsToken */: + case 58 /* MinusEqualsToken */: + case 59 /* AsteriskEqualsToken */: + case 61 /* SlashEqualsToken */: + case 62 /* PercentEqualsToken */: + case 56 /* EqualsToken */: + case 24 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + case 49 /* ExclamationToken */: + case 41 /* PlusPlusToken */: + case 42 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function isKeyword(token) { + return token >= 70 /* FirstKeyword */ && token <= 138 /* LastKeyword */; + } + function classFromKind(token) { + if (isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* StringLiteral */: + return 6 /* stringLiteral */; + case 10 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 69 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + return { + getClassificationsForLine: getClassificationsForLine, + getEncodedLexicalClassifications: getEncodedLexicalClassifications + }; + } + ts.createClassifier = createClassifier; + /* @internal */ + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. + switch (kind) { + case 225 /* ModuleDeclaration */: + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 220 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + /* @internal */ + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var result = []; + processNode(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifySymbol(symbol, meaningAtPosition) { + var flags = symbol.getFlags(); + if ((flags & 788448 /* Classifiable */) === 0 /* None */) { + return; + } + if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (meaningAtPosition & 2 /* Type */) { + if (flags & 64 /* Interface */) { + return 13 /* interfaceName */; + } + else if (flags & 262144 /* TypeParameter */) { + return 15 /* typeParameterName */; + } + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + if (meaningAtPosition & 4 /* Namespace */ || + (meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) { + return 14 /* moduleName */; + } + } + return undefined; + /** + * Returns true if there exists a module that introduces entities on the value side. + */ + function hasValueSideModule(symbol) { + return ts.forEach(symbol.declarations, function (declaration) { + return declaration.kind === 225 /* ModuleDeclaration */ && + ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } + } + function processNode(node) { + // Only walk into nodes that intersect the requested span. + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + var kind = node.kind; + checkForClassificationCancellation(cancellationToken, kind); + if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { + var identifier = node; + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (classifiableNames[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); } - if (parent_15.kind === 216 /* TryStatement */) { - // Could be the try-block, or the finally-block. - var tryStatement = parent_15; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + } + } + } + ts.forEachChild(node, processNode); + } + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function getClassificationTypeName(type) { + switch (type) { + case 1 /* comment */: return ts.ClassificationTypeNames.comment; + case 2 /* identifier */: return ts.ClassificationTypeNames.identifier; + case 3 /* keyword */: return ts.ClassificationTypeNames.keyword; + case 4 /* numericLiteral */: return ts.ClassificationTypeNames.numericLiteral; + case 5 /* operator */: return ts.ClassificationTypeNames.operator; + case 6 /* stringLiteral */: return ts.ClassificationTypeNames.stringLiteral; + case 8 /* whiteSpace */: return ts.ClassificationTypeNames.whiteSpace; + case 9 /* text */: return ts.ClassificationTypeNames.text; + case 10 /* punctuation */: return ts.ClassificationTypeNames.punctuation; + case 11 /* className */: return ts.ClassificationTypeNames.className; + case 12 /* enumName */: return ts.ClassificationTypeNames.enumName; + case 13 /* interfaceName */: return ts.ClassificationTypeNames.interfaceName; + case 14 /* moduleName */: return ts.ClassificationTypeNames.moduleName; + case 15 /* typeParameterName */: return ts.ClassificationTypeNames.typeParameterName; + case 16 /* typeAliasName */: return ts.ClassificationTypeNames.typeAliasName; + case 17 /* parameterName */: return ts.ClassificationTypeNames.parameterName; + case 18 /* docCommentTagName */: return ts.ClassificationTypeNames.docCommentTagName; + case 19 /* jsxOpenTagName */: return ts.ClassificationTypeNames.jsxOpenTagName; + case 20 /* jsxCloseTagName */: return ts.ClassificationTypeNames.jsxCloseTagName; + case 21 /* jsxSelfClosingTagName */: return ts.ClassificationTypeNames.jsxSelfClosingTagName; + case 22 /* jsxAttribute */: return ts.ClassificationTypeNames.jsxAttribute; + case 23 /* jsxText */: return ts.ClassificationTypeNames.jsxText; + case 24 /* jsxAttributeStringLiteralValue */: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + } + } + function convertClassifications(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0, n = dense.length; i < n; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + /* @internal */ + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + /* @internal */ + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + // The moment we get something that isn't trivia, then stop processing. + if (!ts.isTrivia(kind)) { + return start; + } + // Don't bother with newlines/whitespace. + if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { + continue; + } + // Only bother with the trivia if it at least intersects the span of interest. + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + } + if (kind === 7 /* ConflictMarkerTrivia */) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ======== add a comment for the first line, and then lex all + // subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); + pos = tag.tagName.end; + switch (tag.kind) { + case 275 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 278 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + break; + case 277 /* JSDocTypeTag */: + processElement(tag.typeExpression); + break; + case 276 /* JSDocReturnTag */: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.preParameterName) { + pushCommentRange(pos, tag.preParameterName.pos - pos); + pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); + pos = tag.preParameterName.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (tag.postParameterName) { + pushCommentRange(pos, tag.postParameterName.pos - pos); + pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); + pos = tag.postParameterName.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ======= marker is on as a comment. Then just lex + // all further tokens and add them to the result. + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1 /* comment */); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.isJSDocTag(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 243 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 245 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 242 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 246 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; + } + // 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, token) { + if (ts.isKeyword(tokenKind)) { + return 3 /* keyword */; + } + // Special case < and > If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { + // 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 && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10 /* punctuation */; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + if (tokenKind === 56 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (token.parent.kind === 218 /* VariableDeclaration */ || + token.parent.kind === 145 /* PropertyDeclaration */ || + token.parent.kind === 142 /* Parameter */ || + token.parent.kind === 246 /* JsxAttribute */) { + return 5 /* operator */; + } + } + if (token.parent.kind === 187 /* BinaryExpression */ || + token.parent.kind === 185 /* PrefixUnaryExpression */ || + token.parent.kind === 186 /* PostfixUnaryExpression */ || + token.parent.kind === 188 /* ConditionalExpression */) { + return 5 /* operator */; + } + } + return 10 /* punctuation */; + } + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; + } + else if (tokenKind === 9 /* StringLiteral */) { + return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 10 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (tokenKind === 244 /* JsxText */) { + return 23 /* jsxText */; + } + else if (tokenKind === 69 /* Identifier */) { + if (token) { + switch (token.parent.kind) { + case 221 /* ClassDeclaration */: + if (token.parent.name === token) { + return 11 /* className */; + } + return; + case 141 /* TypeParameter */: + if (token.parent.name === token) { + return 15 /* typeParameterName */; + } + return; + case 222 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return 13 /* interfaceName */; + } + return; + case 224 /* EnumDeclaration */: + if (token.parent.name === token) { + return 12 /* enumName */; + } + return; + case 225 /* ModuleDeclaration */: + if (token.parent.name === token) { + return 14 /* moduleName */; + } + return; + case 142 /* Parameter */: + if (token.parent.name === token) { + var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; + return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + } + return; + } + } + return 2 /* identifier */; + } + } + function processElement(element) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; + if (!tryClassifyNode(child)) { + // Recurse into our child nodes. + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Completions; + (function (Completions) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + if (ts.isInReferenceComment(sourceFile, position)) { + return getTripleSlashReferenceCompletion(sourceFile, position); + } + if (ts.isInString(sourceFile, position)) { + return getStringLiteralCompletionEntries(sourceFile, position); + } + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + if (isJsDocTagName) { + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + } + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); + } + else { + if (!symbols || symbols.length === 0) { + if (sourceFile.languageVariant === 1 /* JSX */ && + location.parent && location.parent.kind === 245 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } + } + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); + } + // Add keywords if this is not a member completion list + if (!isMemberCompletion && !isJsDocTagName) { + ts.addRange(entries, keywordCompletions); + } + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { + var entries = []; + var nameTable = ts.getNameTable(sourceFile); + for (var name_46 in nameTable) { + // Skip identifiers produced only from the current location + if (nameTable[name_46] === position) { + continue; + } + if (!uniqueNames[name_46]) { + uniqueNames[name_46] = name_46; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, /*performCharacterChecks*/ true); + if (displayName) { + var entry = { + name: displayName, + kind: ts.ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); + } + } + } + return entries; + } + function createCompletionEntry(symbol, location, performCharacterChecks) { + // Try to get a valid display name for this symbol, if we could not find one, then ignore it. + // We would like to only show things that can be added after a dot, so for instance numeric properties can + // not be accessed with a dot (a.1 <- invalid) + var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, compilerOptions.target, performCharacterChecks, location); + if (!displayName) { + return undefined; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). + return { + name: displayName, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0" + }; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { + var start = ts.timestamp(); + var uniqueNames = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var entry = createCompletionEntry(symbol, location, performCharacterChecks); + if (entry) { + var id = ts.escapeIdentifier(entry.name); + if (!uniqueNames[id]) { + entries.push(entry); + uniqueNames[id] = id; + } + } + } + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniqueNames; + } + function getStringLiteralCompletionEntries(sourceFile, position) { + var node = ts.findPrecedingToken(position, sourceFile); + if (!node || node.kind !== 9 /* StringLiteral */) { + return undefined; + } + if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); + } + else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return getStringLiteralCompletionEntriesFromElementAccess(node.parent); + } + else if (node.parent.kind === 230 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + return getStringLiteralCompletionEntriesFromModuleNames(node); + } + else { + var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); + if (argumentInfo) { + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + } + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return getStringLiteralCompletionEntriesFromContextualType(node); + } + } + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var type = typeChecker.getContextualType(element.parent); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + } + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + var candidates = []; + var entries = []; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); + for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { + var candidate = candidates_3[_i]; + if (candidate.parameters.length > argumentInfo.argumentIndex) { + var parameter = candidate.parameters[argumentInfo.argumentIndex]; + addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); + } + } + if (entries.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + } + return undefined; + } + function getStringLiteralCompletionEntriesFromElementAccess(node) { + var type = typeChecker.getTypeAtLocation(node.expression); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + return undefined; + } + function getStringLiteralCompletionEntriesFromContextualType(node) { + var type = typeChecker.getContextualType(node); + if (type) { + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + } + } + return undefined; + } + function addStringLiteralCompletionsFromType(type, result) { + if (!type) { + return; + } + if (type.flags & 524288 /* Union */) { + ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); + } + else { + if (type.flags & 32 /* StringLiteral */) { + result.push({ + name: type.text, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } + } + } + function getStringLiteralCompletionEntriesFromModuleNames(node) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = node.getSourceFile().path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var entries; + if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { + if (compilerOptions.rootDirs) { + entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ false, span, scriptPath); + } + else { + entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ false, span, scriptPath); + } + } + else { + // Check for node modules + entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries + }; + } + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + // Make all paths absolute/normalized if they are not already + rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + // Determine the path to the directory containing the script relative to the root directory it is contained within + var relativeDirectory; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDirectory = rootDirs_1[_i]; + if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { + relativeDirectory = scriptPath.substr(rootDirectory.length); + break; + } + } + // Now find a path for each potential directory that is to be merged with the one containing the script + return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); + var result = []; + for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { + var baseDirectory = baseDirectories_1[_i]; + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, exclude, result); + } + return result; + } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { + if (result === void 0) { result = []; } + fragment = ts.getDirectoryPath(fragment); + if (!fragment) { + fragment = "./"; + } + else { + fragment = ts.ensureTrailingDirectorySeparator(fragment); + } + var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); + var baseDirectory = ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (tryDirectoryExists(host, baseDirectory)) { + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + var foundFiles = ts.createMap(); + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; + } + var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + if (!foundFiles[foundFileName]) { + foundFiles[foundFileName] = true; + } + } + for (var foundFile in foundFiles) { + result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + } + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { + var directory = directories_2[_a]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + } + } + } + return result; + } + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result; + if (baseUrl) { + var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); + result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span); + if (paths) { + for (var path in paths) { + if (paths.hasOwnProperty(path)) { + if (path === "*") { + if (paths[path]) { + for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { + var pattern = _a[_i]; + for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions); _b < _c.length; _b++) { + var match = _c[_b]; + result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + } + } + } } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); - break; + else if (ts.startsWith(path, fragment)) { + var entry = paths[path] && paths[path].length === 1 && paths[path][0]; + if (entry) { + result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); } } } - // Block was a standalone block. In this case we want to only collapse - // the span of the block, independent of any parent span. - var span = ts.createTextSpanFromBounds(n.getStart(), n.end); - elements.push({ - textSpan: span, - hintSpan: span, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); + } + } + } + else { + result = []; + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions); _d < _e.length; _d++) { + var moduleName = _e[_d]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + return result; + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions) { + if (host.readDirectory) { + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (parsed) { + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); + if (matches) { + var result = []; + // Trim away prefix and suffix + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + continue; + } + var start = completePrefix.length; + var length_5 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_5))); + } + return result; + } + } + } + return undefined; + } + function enumeratePotentialNonRelativeModules(fragment, scriptPath, options) { + // Check If this is a nested module + var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; + // Get modules that the type checker picked up + var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts + if (isNestedModule) { + var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); + nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { + if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { + return moduleName.substr(moduleNameWithSeperator_1.length); + } + return moduleName; + }); + } + if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { + var visibleModule = _a[_i]; + if (!isNestedModule) { + nonRelativeModules.push(visibleModule.moduleName); + } + else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { + var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (nestedFiles) { + for (var _b = 0, nestedFiles_1 = nestedFiles; _b < nestedFiles_1.length; _b++) { + var f = nestedFiles_1[_b]; + f = ts.normalizePath(f); + var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); + nonRelativeModules.push(nestedModule); + } + } + } + } + } + return ts.deduplicate(nonRelativeModules); + } + function getTripleSlashReferenceCompletion(sourceFile, position) { + var token = ts.getTokenAtPosition(sourceFile, position); + if (!token) { + return undefined; + } + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + if (!commentRanges || !commentRanges.length) { + return undefined; + } + var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.substr(range.pos, position - range.pos); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (match) { + var prefix = match[1]; + var kind = match[2]; + var toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var entries_3; + if (kind === "path") { + // Give completions for a relative path + var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); + entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + } + else { + // Give completions based on the typings available + var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; + entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries_3 + }; + } + return undefined; + } + function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + if (result === void 0) { result = []; } + // Check for typings specified in compiler options + if (options.types) { + for (var _i = 0, _a = options.types; _i < _a.length; _i++) { + var moduleName = _a[_i]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + } + else if (host.getDirectories) { + var typeRoots = void 0; + try { + // Wrap in try catch because getEffectiveTypeRoots touches the filesystem + typeRoots = ts.getEffectiveTypeRoots(options, host); + } + catch (e) { } + if (typeRoots) { + for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { + var root = typeRoots_2[_b]; + getCompletionEntriesFromDirectories(host, options, root, span, result); + } + } + } + if (host.getDirectories) { + // Also get all @types typings installed in visible node_modules directories + for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { + var packageJson = _d[_c]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + } + } + return result; + } + function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + if (host.getDirectories && tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { + var typeDirectory = directories_3[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + } + } + } + } + function findPackageJsons(currentDir) { + var paths = []; + var currentConfigPath; + while (true) { + currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); + if (currentConfigPath) { + paths.push(currentConfigPath); + currentDir = ts.getDirectoryPath(currentConfigPath); + var parent_16 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_16) { break; } - // Fallthrough. - case 226 /* ModuleBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + currentDir = parent_16; + } + else { break; } - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 227 /* CaseBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); - break; - } - case 170 /* ArrayLiteralExpression */: - var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); - break; } - depth++; - ts.forEachChild(n, walk); - depth--; + return paths; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + var result = []; + if (host.readFile && host.fileExists) { + for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = tryReadingPackageJson(packageJson); + if (!contents) { + return; + } + var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); + var foundModuleNames = []; + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + addPotentialPackageNames(contents[key], foundModuleNames); + } + for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { + var moduleName = foundModuleNames_1[_c]; + var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); + result.push({ + moduleName: moduleName, + moduleDir: moduleDir + }); + } + } + } + return result; + function tryReadingPackageJson(filePath) { + try { + var fileText = tryReadFile(host, filePath); + return fileText ? JSON.parse(fileText) : undefined; + } + catch (e) { + return undefined; + } + } + function addPotentialPackageNames(dependencies, result) { + if (dependencies) { + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + } + function createCompletionEntryForModule(name, kind, replacementSpan) { + return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + } + // Replace everything after the last directory seperator that appears + function getDirectoryFragmentTextSpan(text, textStart) { + var index = text.lastIndexOf(ts.directorySeparator); + var offset = index !== -1 ? index + 1 : 0; + return { start: textStart + offset, length: text.length - offset }; + } + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; + } + return false; + } + function normalizeAndPreserveTrailingSlash(path) { + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); } - walk(sourceFile); - return elements; } - OutliningElementsCollector.collectElements = collectElements; - })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + // Compute all the completion symbols again. + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_2 = completionData.location; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); + if (symbol) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + return { + name: entryName, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + kind: symbolKind, + displayParts: displayParts, + documentation: documentation + }; + } + } + // Didn't find a symbol with this name. See if we can find a keyword instead. + var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + if (keywordCompletion) { + return { + name: entryName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined + }; + } + return undefined; + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + // Compute all the completion symbols again. + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_3 = completionData.location; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); + } + return undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + function getCompletionData(typeChecker, log, sourceFile, position) { + var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + var isJsDocTagName = false; + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + // Completion not allowed inside comments, bail out if this is the case + var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + if (insideComment) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + isJsDocTagName = true; + } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets + var insideJsDocTagExpression = false; + var tag = ts.getJsDocTagAtPosition(sourceFile, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + isJsDocTagName = true; + } + switch (tag.kind) { + case 277 /* JSDocTypeTag */: + case 275 /* JSDocParameterTag */: + case 276 /* JSDocReturnTag */: + var tagWithExpression = tag; + if (tagWithExpression.typeExpression) { + insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; + } + break; + } + } + if (isJsDocTagName) { + return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + } + if (!insideJsDocTagExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile); + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file + var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. + if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { + var start_2 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. + var node = currentToken; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + // Bail out if this is a known invalid completion location + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent_17 = contextToken.parent, kind = contextToken.kind; + if (kind === 21 /* DotToken */) { + if (parent_17.kind === 172 /* PropertyAccessExpression */) { + node = contextToken.parent.expression; + isRightOfDot = true; + } + else if (parent_17.kind === 139 /* QualifiedName */) { + node = contextToken.parent.left; + isRightOfDot = true; + } + else { + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + if (kind === 25 /* LessThanToken */) { + isRightOfOpenTag = true; + location = contextToken; + } + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 245 /* JsxClosingElement */) { + isStartingCloseTag = true; + location = contextToken; + } + } + } + var semanticStart = ts.timestamp(); + var isMemberCompletion; + var isNewIdentifierLocation; + var symbols = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); + if (tryGetGlobalSymbols()) { + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 8388608 /* Alias */)); })); + } + else { + symbols = tagSymbols; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + function getTypeScriptMemberSymbols() { + // Right of dot member completion list + isMemberCompletion = true; + isNewIdentifierLocation = false; + if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { + var symbol = typeChecker.getSymbolAtLocation(node); + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 8388608 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol && symbol.flags & 1952 /* HasExports */) { + // Extract module or enum members + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + ts.forEach(exportedSymbols, function (symbol) { + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + }); + } + } + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { + if (type) { + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + } + if (isJavaScriptFile && type.flags & 524288 /* Union */) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); + } + } + } + } + function tryGetGlobalSymbols() { + var objectLikeContainer; + var namedImportsOrExports; + var jsxContainer; + if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { + return tryGetObjectLikeCompletionSymbols(objectLikeContainer); + } + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { + // cursor is in an import clause + // try to show exported member for imported module + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); + } + if (jsxContainer = tryGetContainingJsxElement(contextToken)) { + var attrsType = void 0; + if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { + // Cursor is inside a JSX self-closing element or opening element + attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + if (attrsType) { + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); + isMemberCompletion = true; + isNewIdentifierLocation = false; + return true; + } + } + } + // Get all entities in the current scope. + isMemberCompletion = false; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + /// TODO filter meaning based on the current context + var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + return true; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 244 /* JsxText */) { + return true; + } + if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 243 /* JsxOpeningElement */) { + return true; + } + if (contextToken.parent.kind === 245 /* JsxClosingElement */ || contextToken.parent.kind === 242 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 241 /* JsxElement */; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + switch (previousToken.kind) { + case 24 /* CommaToken */: + return containingNodeKind === 174 /* CallExpression */ // func( a, | + || containingNodeKind === 148 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 175 /* NewExpression */ // new C(a, | + || containingNodeKind === 170 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 187 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 156 /* FunctionType */; // var x: (s: string, list| + case 17 /* OpenParenToken */: + return containingNodeKind === 174 /* CallExpression */ // func( | + || containingNodeKind === 148 /* Constructor */ // constructor( | + || containingNodeKind === 175 /* NewExpression */ // new C(a| + || containingNodeKind === 178 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 164 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 19 /* OpenBracketToken */: + return containingNodeKind === 170 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 153 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 140 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 125 /* ModuleKeyword */: // module | + case 126 /* NamespaceKeyword */: + return true; + case 21 /* DotToken */: + return containingNodeKind === 225 /* ModuleDeclaration */; // module A.| + case 15 /* OpenBraceToken */: + return containingNodeKind === 221 /* ClassDeclaration */; // class A{ | + case 56 /* EqualsToken */: + return containingNodeKind === 218 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 187 /* BinaryExpression */; // x = a| + case 12 /* TemplateHead */: + return containingNodeKind === 189 /* TemplateExpression */; // `aa ${| + case 13 /* TemplateMiddle */: + return containingNodeKind === 197 /* TemplateSpan */; // `aa ${10} dd ${| + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return containingNodeKind === 145 /* PropertyDeclaration */; // class A{ public | + } + // Previous token may have been a keyword that was converted to an identifier. + switch (previousToken.getText()) { + case "public": + case "protected": + case "private": + return true; + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 10 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(contextToken.kind)) { + var start_3 = contextToken.getStart(); + var end = contextToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start_3 < position && position < end) { + return true; + } + if (position === end) { + return !!contextToken.isUnterminated + || contextToken.kind === 10 /* RegularExpressionLiteral */; + } + } + return false; + } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + // We're looking up possible property names from contextual/inferred/declared type. + isMemberCompletion = true; + var typeForObject; + var existingMembers; + if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { + // We are completing on contextual types, but may also include properties + // other than those within the declared type. + isNewIdentifierLocation = true; + // If the object literal is being assigned to something of type 'null | { hello: string }', + // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. + typeForObject = typeChecker.getContextualType(objectLikeContainer); + typeForObject = typeForObject && typeForObject.getNonNullableType(); + existingMembers = objectLikeContainer.properties; + } + else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { + // We are *only* completing on properties from the type being destructured. + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (ts.isVariableLike(rootDeclaration)) { + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); + if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + existingMembers = objectLikeContainer.elements; + } + } + else { + ts.Debug.fail("Root declaration is not variable-like."); + } + } + else { + ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); + } + if (!typeForObject) { + return false; + } + var typeMembers = typeChecker.getPropertiesOfType(typeForObject); + if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list + symbols = filterObjectMembersList(typeMembers, existingMembers); + } + return true; + } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 233 /* NamedImports */ ? + 230 /* ImportDeclaration */ : + 236 /* ExportDeclaration */; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); + } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : ts.emptyArray; + return true; + } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15 /* OpenBraceToken */: // const x = { | + case 24 /* CommaToken */: + var parent_18 = contextToken.parent; + if (parent_18 && (parent_18.kind === 171 /* ObjectLiteralExpression */ || parent_18.kind === 167 /* ObjectBindingPattern */)) { + return parent_18; + } + break; + } + } + return undefined; + } + /** + * Returns the containing list of named imports or exports of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15 /* OpenBraceToken */: // import { | + case 24 /* CommaToken */: + switch (contextToken.parent.kind) { + case 233 /* NamedImports */: + case 237 /* NamedExports */: + return contextToken.parent; + } + } + } + return undefined; + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent_19 = contextToken.parent; + switch (contextToken.kind) { + case 26 /* LessThanSlashToken */: + case 39 /* SlashToken */: + case 69 /* Identifier */: + case 246 /* JsxAttribute */: + case 247 /* JsxSpreadAttribute */: + if (parent_19 && (parent_19.kind === 242 /* JsxSelfClosingElement */ || parent_19.kind === 243 /* JsxOpeningElement */)) { + return parent_19; + } + else if (parent_19.kind === 246 /* JsxAttribute */) { + return parent_19.parent; + } + break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 9 /* StringLiteral */: + if (parent_19 && ((parent_19.kind === 246 /* JsxAttribute */) || (parent_19.kind === 247 /* JsxSpreadAttribute */))) { + return parent_19.parent; + } + break; + case 16 /* CloseBraceToken */: + if (parent_19 && + parent_19.kind === 248 /* JsxExpression */ && + parent_19.parent && + (parent_19.parent.kind === 246 /* JsxAttribute */)) { + return parent_19.parent.parent; + } + if (parent_19 && parent_19.kind === 247 /* JsxSpreadAttribute */) { + return parent_19.parent; + } + break; + } + } + return undefined; + } + function isFunction(kind) { + switch (kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 153 /* IndexSignature */: + return true; + } + return false; + } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { + var containingNodeKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 24 /* CommaToken */: + return containingNodeKind === 218 /* VariableDeclaration */ || + containingNodeKind === 219 /* VariableDeclarationList */ || + containingNodeKind === 200 /* VariableStatement */ || + containingNodeKind === 224 /* EnumDeclaration */ || + isFunction(containingNodeKind) || + containingNodeKind === 221 /* ClassDeclaration */ || + containingNodeKind === 192 /* ClassExpression */ || + containingNodeKind === 222 /* InterfaceDeclaration */ || + containingNodeKind === 168 /* ArrayBindingPattern */ || + containingNodeKind === 223 /* TypeAliasDeclaration */; // type Map, K, | + case 21 /* DotToken */: + return containingNodeKind === 168 /* ArrayBindingPattern */; // var [.| + case 54 /* ColonToken */: + return containingNodeKind === 169 /* BindingElement */; // var {x :html| + case 19 /* OpenBracketToken */: + return containingNodeKind === 168 /* ArrayBindingPattern */; // var [x| + case 17 /* OpenParenToken */: + return containingNodeKind === 252 /* CatchClause */ || + isFunction(containingNodeKind); + case 15 /* OpenBraceToken */: + return containingNodeKind === 224 /* EnumDeclaration */ || + containingNodeKind === 222 /* InterfaceDeclaration */ || + containingNodeKind === 159 /* TypeLiteral */; // const x : { | + case 23 /* SemicolonToken */: + return containingNodeKind === 144 /* PropertySignature */ && + contextToken.parent && contextToken.parent.parent && + (contextToken.parent.parent.kind === 222 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 159 /* TypeLiteral */); // const x : { a; | + case 25 /* LessThanToken */: + return containingNodeKind === 221 /* ClassDeclaration */ || + containingNodeKind === 192 /* ClassExpression */ || + containingNodeKind === 222 /* InterfaceDeclaration */ || + containingNodeKind === 223 /* TypeAliasDeclaration */ || + isFunction(containingNodeKind); + case 113 /* StaticKeyword */: + return containingNodeKind === 145 /* PropertyDeclaration */; + case 22 /* DotDotDotToken */: + return containingNodeKind === 142 /* Parameter */ || + (contextToken.parent && contextToken.parent.parent && + contextToken.parent.parent.kind === 168 /* ArrayBindingPattern */); // var [...z| + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return containingNodeKind === 142 /* Parameter */; + case 116 /* AsKeyword */: + return containingNodeKind === 234 /* ImportSpecifier */ || + containingNodeKind === 238 /* ExportSpecifier */ || + containingNodeKind === 232 /* NamespaceImport */; + case 73 /* ClassKeyword */: + case 81 /* EnumKeyword */: + case 107 /* InterfaceKeyword */: + case 87 /* FunctionKeyword */: + case 102 /* VarKeyword */: + case 123 /* GetKeyword */: + case 131 /* SetKeyword */: + case 89 /* ImportKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + case 114 /* YieldKeyword */: + case 134 /* TypeKeyword */: + return true; + } + // Previous token may have been a keyword that was converted to an identifier. + switch (contextToken.getText()) { + case "abstract": + case "async": + case "class": + case "const": + case "declare": + case "enum": + case "function": + case "interface": + case "let": + case "private": + case "protected": + case "public": + case "static": + case "var": + case "yield": + return true; + } + return false; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8 /* NumericLiteral */) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @param exportsOfModule The list of symbols which a module exposes. + * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. + * + * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports + * do not occur at the current position and have not otherwise been typed. + */ + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var existingImportsOrExports = ts.createMap(); + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_47 = element.propertyName || element.name; + existingImportsOrExports[name_47.text] = true; + } + if (!ts.someProperties(existingImportsOrExports)) { + return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + } + return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (!existingMembers || existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 253 /* PropertyAssignment */ && + m.kind !== 254 /* ShorthandPropertyAssignment */ && + m.kind !== 169 /* BindingElement */ && + m.kind !== 147 /* MethodDeclaration */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (m.getStart() <= position && position <= m.getEnd()) { + continue; + } + var existingName = void 0; + if (m.kind === 169 /* BindingElement */ && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 69 /* Identifier */) { + existingName = m.propertyName.text; + } + } + else { + // TODO(jfreeman): Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + existingName = m.name.text; + } + existingMemberNames[existingName] = true; + } + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); + } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (attr.getStart() <= position && position <= attr.getEnd()) { + continue; + } + if (attr.kind === 246 /* JsxAttribute */) { + seenNames[attr.name.text] = true; + } + } + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); + } + } + /** + * Get the name to be display in completion from a given symbol. + * + * @return undefined if the name is of external module otherwise a name with striped of any quote + */ + function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { + var displayName = ts.getDeclaredName(typeChecker, symbol, location); + if (displayName) { + var firstCharCode = displayName.charCodeAt(0); + // First check of the displayName is not external module; if it is an external module, it is not valid entry + if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + return undefined; + } + } + return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + } + /** + * Get a displayName from a given for completion list, performing any necessary quotes stripping + * and checking whether the name is valid identifier name. + */ + function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + if (!name) { + return undefined; + } + name = ts.stripQuotes(name); + if (!name) { + return undefined; + } + // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an + // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. + // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. + // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. + if (performCharacterChecks) { + if (!ts.isIdentifierText(name, target)) { + return undefined; + } + } + return name; + } + // A cache of completion entries for keywords, these do not change between sessions + var keywordCompletions = []; + for (var i = 70 /* FirstKeyword */; i <= 138 /* LastKeyword */; i++) { + keywordCompletions.push({ + name: ts.tokenToString(i), + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + sortText: "0" + }); + } + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches /// = 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { + break; + } + } + } + } + var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); + } + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + case 204 /* DoStatement */: + case 205 /* WhileStatement */: + return getLoopBreakContinueOccurrences(owner); + case 213 /* SwitchStatement */: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); + var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); + } + }); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getTryCatchFinallyOccurrences(tryStatement) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getThrowOccurrences(throwStatement) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + }); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getReturnOccurrences(returnStatement) { + var func = ts.getContainingFunction(returnStatement); + // If we didn't find a containing function with a block body, bail out. + if (!(func && hasKind(func.body, 199 /* Block */))) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(func.body, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + }); + // Include 'throw' statements that do not occur within a try block. + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getIfElseOccurrences(ifStatement) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (hasKind(ifStatement.parent, 203 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (ifStatement) { + var children = ifStatement.getChildren(); + pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { + break; + } + } + if (!hasKind(ifStatement.elseStatement, 203 /* IfStatement */)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombindElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombindElseAndIf = false; + break; + } + } + if (shouldCombindElseAndIf) { + result.push({ + fileName: fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: ts.HighlightSpanKind.reference + }); + i++; // skip the next keyword + continue; + } + } + // Ordinary case: just highlight the keyword. + result.push(getHighlightSpanForNode(keywords[i])); + } + return result; + } + } + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ + function isLabeledBy(node, labelName) { + for (var owner = node.parent; owner.kind === 214 /* LabeledStatement */; owner = owner.parent) { + if (owner.label.text === labelName) { + return true; + } + } + return false; + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function getKeyForCompilationSettings(settings) { + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); + } + function getBucketForCompilationSettings(key, createIfMissing) { + var bucket = buckets[key]; + if (!bucket && createIfMissing) { + buckets[key] = bucket = ts.createFileMap(); + } + return bucket; + } + function reportStats() { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets[name]; + var sourceFiles = []; + entries.forEachValue(function (key, entry) { + sourceFiles.push({ + name: key, + refCount: entry.languageServiceRefCount, + references: entry.owners.slice(0) + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + var entry = bucket.get(path); + if (!entry) { + ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0, + owners: [] + }; + bucket.set(path, entry); + } + else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + } + } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); + ts.Debug.assert(bucket !== undefined); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.remove(path); + } + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistry = createDocumentRegistry; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + function findReferencedSymbols(typeChecker, cancellationToken, sourceFiles, sourceFile, position, findInStrings, findInComments) { + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 8 /* NumericLiteral */: + if (!ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + break; + } + // Fallthrough + case 69 /* Identifier */: + case 97 /* ThisKeyword */: + // case SyntaxKind.SuperKeyword: TODO:GH#9268 + case 121 /* ConstructorKeyword */: + case 9 /* StringLiteral */: + return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, /*implementations*/ false); + } + return undefined; + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, implementations) { + if (!implementations) { + // Labels + if (ts.isLabelName(node)) { + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. + return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; + } + else { + // it is a label definition and not a target, search within the parent labeledStatement + return getLabelReferencesInNode(node.parent, node); + } + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles); + } + if (node.kind === 95 /* SuperKeyword */) { + return getReferencesForSuperKeyword(node); + } + } + // `getSymbolAtLocation` normally returns the symbol of the class when given the constructor keyword, + // so we have to specify that we want the constructor symbol. + var symbol = typeChecker.getSymbolAtLocation(node); + if (!implementations && !symbol && node.kind === 9 /* StringLiteral */) { + return getReferencesForStringLiteral(node, sourceFiles); + } + // Could not find a symbol e.g. unknown identifier + if (!symbol) { + // Can't have references to something that we have no symbol for. + return undefined; + } + var declarations = symbol.declarations; + // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!declarations || !declarations.length) { + return undefined; + } + var result; + // Compute the meaning from the location and the symbol it references + var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), declarations); + // Get the text to search for. + // Note: if this is an external module symbol, the name doesn't include quotes. + var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + // Maps from a symbol ID to the ReferencedSymbol entry in 'result'. + var symbolToIndex = []; + if (scope) { + result = []; + getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + else { + var internedName = getInternedName(symbol, node, declarations); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + cancellationToken.throwIfCancellationRequested(); + var nameTable = ts.getNameTable(sourceFile); + if (nameTable[internedName] !== undefined) { + result = result || []; + getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + } + } + return result; + function getDefinition(symbol) { + var info = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, node.getSourceFile(), ts.getContainerNode(node), node); + var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) { + return undefined; + } + return { + containerKind: "", + containerName: "", + name: name, + kind: info.symbolKind, + fileName: declarations[0].getSourceFile().fileName, + textSpan: ts.createTextSpan(declarations[0].getStart(), 0), + displayParts: info.displayParts + }; + } + function getAliasSymbolForPropertyNameSymbol(symbol, location) { + if (symbol.flags & 8388608 /* Alias */) { + // Default import get alias + var defaultImport = ts.getDeclarationOfKind(symbol, 231 /* ImportClause */); + if (defaultImport) { + return typeChecker.getAliasedSymbol(symbol); + } + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 /* ImportSpecifier */ || + declaration.kind === 238 /* ExportSpecifier */) ? declaration : undefined; }); + if (importOrExportSpecifier && + // export { a } + (!importOrExportSpecifier.propertyName || + // export {a as class } where a is location + importOrExportSpecifier.propertyName === location)) { + // If Import specifier -> get alias + // else Export specifier -> get local target + return importOrExportSpecifier.kind === 234 /* ImportSpecifier */ ? + typeChecker.getAliasedSymbol(symbol) : + typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); + } + } + return undefined; + } + function followAliasIfNecessary(symbol, location) { + return getAliasSymbolForPropertyNameSymbol(symbol, location) || symbol; + } + function getPropertySymbolOfDestructuringAssignment(location) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && + typeChecker.getPropertySymbolOfDestructuringAssignment(location); + } + function isObjectBindingPatternElementWithoutPropertyName(symbol) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + return bindingElement && + bindingElement.parent.kind === 167 /* ObjectBindingPattern */ && + !bindingElement.propertyName; + } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + return undefined; + } + function getInternedName(symbol, location, declarations) { + // If this is an export or import specifier it could have been renamed using the 'as' syntax. + // If so we want to search for whatever under the cursor. + if (ts.isImportOrExportSpecifierName(location)) { + return location.getText(); + } + // Try to get the local symbol if we're dealing with an 'export default' + // since that symbol has the "true" name. + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + symbol = localExportDefaultSymbol || symbol; + return ts.stripQuotes(symbol.name); + } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ + function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. + var valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { + return valueDeclaration; + } + // If this is private property or method, the scope is the containing class + if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8 /* Private */) ? d : undefined; }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); + } + } + // If the symbol is an import we would like to find it if we are looking for what it imports. + // So consider it visible outside its declaration scope. + if (symbol.flags & 8388608 /* Alias */) { + return undefined; + } + // If symbol is of object binding pattern element without property name we would want to + // look for property too and that could be anywhere + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + return undefined; + } + // if this symbol is visible from its parent container, e.g. exported, then bail out + // if symbol correspond to the union property - bail out + if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { + return undefined; + } + var scope; + var declarations = symbol.getDeclarations(); + if (declarations) { + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var container = ts.getContainerNode(declaration); + if (!container) { + return undefined; + } + if (scope && scope !== container) { + // Different declarations have different containers, bail out + return undefined; + } + if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file + return undefined; + } + // The search scope is the container node + scope = container; + } + } + return scope; + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, start); + while (position >= 0) { + cancellationToken.throwIfCancellationRequested(); + // If we are past the end, stop looking + if (position > end) + break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { + // Found a real match. Keep searching. + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var references = []; + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.getWidth() !== labelName.length) { + return; + } + // Only pick labels that are either the target label, or have a target that is the target label + if (node === targetLabel || + (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = { + containerKind: "", + containerName: "", + fileName: targetLabel.getSourceFile().fileName, + kind: ts.ScriptElementKind.label, + name: labelName, + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), + displayParts: [ts.displayPart(labelName, ts.SymbolDisplayPartKind.text)] + }; + return [{ definition: definition, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + if (node) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for + switch (node.kind) { + case 69 /* Identifier */: + return node.getWidth() === searchSymbolName.length; + case 9 /* StringLiteral */: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isNameOfExternalModuleImportOrDeclaration(node)) { + // For string literals we have two additional chars for the quotes + return node.getWidth() === searchSymbolName.length + 2; + } + break; + case 8 /* NumericLiteral */: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + return node.getWidth() === searchSymbolName.length; + } + break; + } + } + return false; + } + /** Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ + function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { + var sourceFile = container.getSourceFile(); + var start = findInComments ? container.getFullStart() : container.getStart(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, start, container.getEnd()); + var parents = getParentSymbolsOfPropertyAccess(); + var inheritsFromCache = ts.createMap(); + if (possiblePositions.length) { + // Build the set of symbols to search for, initially it has only the current symbol + var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, searchText)) { + // This wasn't the start of a token. Check to see if it might be a + // match in a comment or string if that's what the caller is asking + // for. + if (!implementations && ((findInStrings && ts.isInString(sourceFile, position)) || + (findInComments && ts.isInNonReferenceComment(sourceFile, position)))) { + // In the case where we're looking inside comments/strings, we don't have + // an actual definition. So just use 'undefined' here. Features like + // 'Rename' won't care (as they ignore the definitions), and features like + // 'FindReferences' will just filter out these results. + result.push({ + definition: undefined, + references: [{ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpan(position, searchText.length), + isWriteAccess: false, + isDefinition: false + }] + }); + } + return; + } + if (!(ts.getMeaningFromLocation(referenceLocation) & searchMeaning)) { + return; + } + var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation); + if (referenceSymbol) { + var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, + /*searchLocationIsConstructor*/ searchLocation.kind === 121 /* ConstructorKeyword */, parents, inheritsFromCache); + if (relatedSymbol) { + addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); + } + else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { + addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); + } + else if (searchLocation.kind === 121 /* ConstructorKeyword */) { + findAdditionalConstructorReferences(referenceSymbol, referenceLocation); + } + } + }); + } + return; + /* If we are just looking for implementations and this is a property access expression, we need to get the + * symbol of the local type of the symbol the property is being accessed on. This is because our search + * symbol may have a different parent symbol if the local type's symbol does not declare the property + * being accessed (i.e. it is declared in some parent class or interface) + */ + function getParentSymbolsOfPropertyAccess() { + if (implementations) { + var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(searchLocation); + if (propertyAccessExpression) { + var localParentType = typeChecker.getTypeAtLocation(propertyAccessExpression.expression); + if (localParentType) { + if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== searchSymbol.parent) { + return [localParentType.symbol]; + } + else if (localParentType.flags & 1572864 /* UnionOrIntersection */) { + return getSymbolsForClassAndInterfaceComponents(localParentType); + } + } + } + } + } + function getPropertyAccessExpressionFromRightHandSide(node) { + return ts.isRightSideOfPropertyAccess(node) && node.parent; + } + /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ + function findAdditionalConstructorReferences(referenceSymbol, referenceLocation) { + ts.Debug.assert(ts.isClassLike(searchSymbol.valueDeclaration)); + var referenceClass = referenceLocation.parent; + if (referenceSymbol === searchSymbol && ts.isClassLike(referenceClass)) { + ts.Debug.assert(referenceClass.name === referenceLocation); + // This is the class declaration containing the constructor. + addReferences(findOwnConstructorCalls(searchSymbol)); + } + else { + // If this class appears in `extends C`, then the extending class' "super" calls are references. + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending && ts.isClassLike(classExtending) && followAliasIfNecessary(referenceSymbol, referenceLocation) === searchSymbol) { + addReferences(superConstructorAccesses(classExtending)); + } + } + } + function addReferences(references) { + if (references.length) { + var referencedSymbol = getReferencedSymbol(searchSymbol); + ts.addRange(referencedSymbol.references, ts.map(references, getReferenceEntryFromNode)); + } + } + /** `classSymbol` is the class where the constructor was defined. + * Reference the constructor and all calls to `new this()`. + */ + function findOwnConstructorCalls(classSymbol) { + var result = []; + for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148 /* Constructor */); + var ctrKeyword = decl.getChildAt(0); + ts.Debug.assert(ctrKeyword.kind === 121 /* ConstructorKeyword */); + result.push(ctrKeyword); + } + ts.forEachProperty(classSymbol.exports, function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 147 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 97 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + result.push(thisKeyword); + } + }); + } + } + }); + return result; + } + /** Find references to `super` in the constructor of an extending class. */ + function superConstructorAccesses(cls) { + var symbol = cls.symbol; + var ctr = symbol.members["__constructor"]; + if (!ctr) { + return []; + } + var result = []; + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148 /* Constructor */); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 95 /* SuperKeyword */, function (node) { + if (ts.isCallExpressionTarget(node)) { + result.push(node); + } + }); + } + } + ; + return result; + } + function getReferencedSymbol(symbol) { + var symbolId = ts.getSymbolId(symbol); + var index = symbolToIndex[symbolId]; + if (index === undefined) { + index = result.length; + symbolToIndex[symbolId] = index; + result.push({ + definition: getDefinition(symbol), + references: [] + }); + } + return result[index]; + } + function addReferenceToRelatedSymbol(node, relatedSymbol) { + var references = getReferencedSymbol(relatedSymbol).references; + if (implementations) { + getImplementationReferenceEntryForNode(node, references); + } + else { + references.push(getReferenceEntryFromNode(node)); + } + } + } + function getImplementationReferenceEntryForNode(refNode, result) { + // Check if we found a function/propertyAssignment/method with an implementation or initializer + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + result.push(getReferenceEntryFromNode(refNode.parent)); + } + else if (refNode.kind === 69 /* Identifier */) { + if (refNode.parent.kind === 254 /* ShorthandPropertyAssignment */) { + // Go ahead and dereference the shorthand assignment by going to its definition + getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); + } + // Check if the node is within an extends or implements clause + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + result.push(getReferenceEntryFromNode(containingClass)); + return; + } + // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface + var containingTypeReference = getContainingTypeReference(refNode); + if (containingTypeReference) { + var parent_21 = containingTypeReference.parent; + if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + } + else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { + if (parent_21.body.kind === 199 /* Block */) { + ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { + maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); + } + }); + } + else if (isImplementationExpression(parent_21.body)) { + maybeAdd(getReferenceEntryFromNode(parent_21.body)); + } + } + else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + } + } + } + // Type nodes can contain multiple references to the same type. For example: + // let x: Foo & (Foo & Bar) = ... + // Because we are returning the implementation locations and not the identifier locations, + // duplicate entries would be returned here as each of the type references is part of + // the same implementation. For that reason, check before we add a new entry + function maybeAdd(a) { + if (!ts.forEach(result, function (b) { return a.fileName === b.fileName && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; })) { + result.push(a); + } + } + } + function getSymbolsForClassAndInterfaceComponents(type, result) { + if (result === void 0) { result = []; } + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var componentType = _a[_i]; + if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { + result.push(componentType.symbol); + } + if (componentType.getFlags() & 1572864 /* UnionOrIntersection */) { + getSymbolsForClassAndInterfaceComponents(componentType, result); + } + } + return result; + } + function getContainingTypeReference(node) { + var topLevelTypeReference = undefined; + while (node) { + if (ts.isTypeNode(node)) { + topLevelTypeReference = node; + } + node = node.parent; + } + return topLevelTypeReference; + } + function getContainingClassIfInHeritageClause(node) { + if (node && node.parent) { + if (node.kind === 194 /* ExpressionWithTypeArguments */ + && node.parent.kind === 251 /* HeritageClause */ + && ts.isClassLike(node.parent.parent)) { + return node.parent.parent; + } + else if (node.kind === 69 /* Identifier */ || node.kind === 172 /* PropertyAccessExpression */) { + return getContainingClassIfInHeritageClause(node.parent); + } + } + return undefined; + } + /** + * Returns true if this is an expression that can be considered an implementation + */ + function isImplementationExpression(node) { + // Unwrap parentheses + if (node.kind === 178 /* ParenthesizedExpression */) { + return isImplementationExpression(node.expression); + } + return node.kind === 180 /* ArrowFunction */ || + node.kind === 179 /* FunctionExpression */ || + node.kind === 171 /* ObjectLiteralExpression */ || + node.kind === 192 /* ClassExpression */ || + node.kind === 170 /* ArrayLiteralExpression */; + } + /** + * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol + * is an interface, determines if some ancestor of the child symbol extends or inherits from it. + * Also takes in a cache of previous results which makes this slightly more efficient and is + * necessary to avoid potential loops like so: + * class A extends B { } + * class B extends A { } + * + * We traverse the AST rather than using the type checker because users are typically only interested + * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling + * implementations of types that share a common ancestor with the type whose implementation we are + * searching for need to be filtered out of the results. The type checker doesn't let us make the + * distinction between structurally compatible implementations and explicit implementations, so we + * must use the AST. + * + * @param child A class or interface Symbol + * @param parent Another class or interface Symbol + * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results + */ + function explicitlyInheritsFrom(child, parent, cachedResults) { + var parentIsInterface = parent.getFlags() & 64 /* Interface */; + return searchHierarchy(child); + function searchHierarchy(symbol) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + if (key in cachedResults) { + return cachedResults[key]; + } + // Set the key so that we don't infinitely recurse + cachedResults[key] = false; + var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + if (parentIsInterface) { + var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); + if (interfaceReferences) { + for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { + var typeReference = interfaceReferences_1[_i]; + if (searchTypeReference(typeReference)) { + return true; + } + } + } + } + return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + } + else if (declaration.kind === 222 /* InterfaceDeclaration */) { + if (parentIsInterface) { + return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); + } + } + return false; + }); + cachedResults[key] = inherits; + return inherits; + } + function searchTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type && type.symbol) { + return searchHierarchy(type.symbol); + } + } + return false; + } + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); + if (!searchSpaceNode) { + return undefined; + } + // Whether 'super' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + default: + return undefined; + } + var references = []; + var sourceFile = searchSpaceNode.getSourceFile(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.kind !== 95 /* SuperKeyword */) { + return; + } + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + if (container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = getDefinition(searchSpaceNode.symbol); + return [{ definition: definition, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + // fall through + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + case 256 /* SourceFile */: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + // Fall through + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. + default: + return undefined; + } + var references = []; + var possiblePositions; + if (searchSpaceNode.kind === 256 /* SourceFile */) { + ts.forEach(sourceFiles, function (sourceFile) { + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); + }); + } + else { + var sourceFile = searchSpaceNode.getSourceFile(); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); + } + var thisOrSuperSymbol = typeChecker.getSymbolAtLocation(thisOrSuperKeyword); + var displayParts = thisOrSuperSymbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, thisOrSuperSymbol, thisOrSuperKeyword.getSourceFile(), ts.getContainerNode(thisOrSuperKeyword), thisOrSuperKeyword).displayParts; + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: "this", + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: displayParts + }, + references: references + }]; + function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || !ts.isThis(node)) { + return; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 179 /* FunctionExpression */: + case 220 /* FunctionDeclaration */: + if (searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 192 /* ClassExpression */: + case 221 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 256 /* SourceFile */: + if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + result.push(getReferenceEntryFromNode(node)); + } + break; + } + }); + } + } + function getReferencesForStringLiteral(node, sourceFiles) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (!type) { + // nothing to do here. moving on + return undefined; + } + var references = []; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); + getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); + } + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: type.text, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: [ts.displayPart(ts.getTextOfNode(node), ts.SymbolDisplayPartKind.stringLiteral)] + }, + references: references + }]; + function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { + for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { + var position = possiblePositions_1[_i]; + cancellationToken.throwIfCancellationRequested(); + var node_2 = ts.getTouchingWord(sourceFile, position); + if (!node_2 || node_2.kind !== 9 /* StringLiteral */) { + return; + } + var type_1 = ts.getStringLiteralTypeForNode(node_2, typeChecker); + if (type_1 === searchType) { + references.push(getReferenceEntryFromNode(node_2)); + } + } + } + } + function populateSearchSymbolSet(symbol, location) { + // The search set contains at least the current symbol + var result = [symbol]; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var containingObjectLiteralElement = getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254 /* ShorthandPropertyAssignment */) { + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); + if (propertySymbol) { + result.push(propertySymbol); + } + } + // If the symbol is an alias, add what it aliases to the list + // import {a} from "mod"; + // export {a} + // If the symbol is an alias to default declaration, add what it aliases to the list + // declare "mod" { export default class B { } } + // import B from "mod"; + //// For export specifiers, the exported name can be referring to a local symbol, e.g.: + //// import {a} from "mod"; + //// export {a as somethingElse} + //// We want the *local* declaration of 'a' as declared in the import, + //// *not* as declared within "mod" (or farther) + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); + if (aliasSymbol) { + result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + if (containingObjectLiteralElement) { + ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); + }); + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * const name = "Foo"; + * const obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); + if (shorthandValueSymbol) { + result.push(shorthandValueSymbol); + } + } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 /* Parameter */ && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } + // If this is symbol of binding element without propertyName declaration in Object binding pattern + // Include the property in the search + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); + if (bindingElementPropertySymbol) { + result.push(bindingElementPropertySymbol); + } + // If this is a union property, add all the symbols from all its source symbols in all unioned types. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list + ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + if (rootSymbol !== symbol) { + result.push(rootSymbol); + } + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap()); + } + }); + return result; + } + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited + // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. + // For example: + // interface C extends C { + // /*findRef*/propName: string; + // } + // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, + // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, + // the function will add any found symbol of the property-name, then its sub-routine will call + // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already + // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. + if (symbol.name in previousIterationSymbolsCache) { + return; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); + } + else if (declaration.kind === 222 /* InterfaceDeclaration */) { + ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); + } + }); + } + return; + function getPropertySymbolFromTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type) { + var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); + if (propertySymbol) { + result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); + } + // Visit the typeReference as well to see if it directly or indirectly use that property + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); + } + } + } + } + function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation, searchLocationIsConstructor, parents, cache) { + if (ts.contains(searchSymbols, referenceSymbol)) { + // If we are searching for constructor uses, they must be 'new' expressions. + return (!searchLocationIsConstructor || ts.isNewExpressionTarget(referenceLocation)) && referenceSymbol; + } + // If the reference symbol is an alias, check if what it is aliasing is one of the search + // symbols but by looking up for related symbol of this alias so it can handle multiple level of indirectness. + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); + if (aliasSymbol) { + return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation, searchLocationIsConstructor, parents, cache); + } + // If the reference location is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this symbol to + // compare to our searchSymbol + var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); + if (containingObjectLiteralElement) { + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + }); + if (contextualSymbol) { + return contextualSymbol; + } + // If the reference location is the name of property from object literal destructuring pattern + // Get the property symbol from the object literal's type and look if thats the search symbol + // In below eg. get 'property' from type of elems iterating type + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); + if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { + return propertySymbol; + } + } + // If the reference location is the binding element and doesn't have property name + // then include the binding element in the related symbols + // let { a } : { a }; + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); + if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { + return bindingElementPropertySymbol; + } + // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) + // Or a union property, use its underlying unioned symbols + return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { + // if it is in the list, then we are done + if (searchSymbols.indexOf(rootSymbol) >= 0) { + return rootSymbol; + } + // Finally, try all properties with the same name in any type the containing type extended or implemented, and + // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the + // parent symbol + if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + // Parents will only be defined if implementations is true + if (parents) { + if (!ts.forEach(parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, cache); })) { + return undefined; + } + } + var result_3 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, /*previousIterationSymbolsCache*/ ts.createMap()); + return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + } + return undefined; + }); + } + function getNameFromObjectLiteralElement(node) { + if (node.name.kind === 140 /* ComputedPropertyName */) { + var nameExpression = node.name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } + return undefined; + } + return node.name.text; + } + function getPropertySymbolsFromContextualType(node) { + var objectLiteral = node.parent; + var contextualType = typeChecker.getContextualType(objectLiteral); + var name = getNameFromObjectLiteralElement(node); + if (name && contextualType) { + var result_4 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_4.push(symbol_2); + } + if (contextualType.flags & 524288 /* Union */) { + ts.forEach(contextualType.types, function (t) { + var symbol = t.getProperty(name); + if (symbol) { + result_4.push(symbol); + } + }); + } + return result_4; + } + return undefined; + } + /** Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ + function getIntersectingMeaningFromDeclarations(meaning, declarations) { + if (declarations) { + var lastIterationMeaning = void 0; + do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning + lastIterationMeaning = meaning; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + } + FindAllReferences.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function convertReferences(referenceSymbols) { + if (!referenceSymbols) { + return undefined; + } + var referenceEntries = []; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; + ts.addRange(referenceEntries, referenceSymbol.references); + } + return referenceEntries; + } + FindAllReferences.convertReferences = convertReferences; + function isImplementation(node) { + if (!node) { + return false; + } + else if (ts.isVariableLike(node)) { + if (node.initializer) { + return true; + } + else if (node.kind === 218 /* VariableDeclaration */) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); + } + } + else if (ts.isFunctionLike(node)) { + return !!node.body || ts.hasModifier(node, 2 /* Ambient */); + } + else { + switch (node.kind) { + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 224 /* EnumDeclaration */: + case 225 /* ModuleDeclaration */: + return true; + } + } + return false; + } + function getParentStatementOfVariableDeclaration(node) { + if (node.parent && node.parent.parent && node.parent.parent.kind === 200 /* VariableStatement */) { + ts.Debug.assert(node.parent.kind === 219 /* VariableDeclarationList */); + return node.parent.parent; + } + } + function getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result) { + var refSymbol = typeChecker.getSymbolAtLocation(node); + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) { + result.push(getReferenceEntryFromNode(declaration)); + } + } + } + } + FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function getReferenceEntryFromNode(node) { + var start = node.getStart(); + var end = node.getEnd(); + if (node.kind === 9 /* StringLiteral */) { + start += 1; + end -= 1; + } + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(start, end), + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) + }; + } + FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ + function isWriteAccess(node) { + if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { + return true; + } + var parent = node.parent; + if (parent) { + if (parent.kind === 186 /* PostfixUnaryExpression */ || parent.kind === 185 /* PrefixUnaryExpression */) { + return true; + } + else if (parent.kind === 187 /* BinaryExpression */ && parent.left === node) { + var operator = parent.operatorToken.kind; + return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; + } + } + return false; + } + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + /** + * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } + */ + function getContainingObjectLiteralElement(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (node.parent.kind === 140 /* ComputedPropertyName */) { + return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; + } + // intential fall through + case 69 /* Identifier */: + return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function isObjectLiteralPropertyDeclaration(node) { + switch (node.kind) { + case 253 /* PropertyAssignment */: + case 254 /* ShorthandPropertyAssignment */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return true; + } + return false; + } + /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */ + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + function isNameOfExternalModuleImportOrDeclaration(node) { + if (node.kind === 9 /* StringLiteral */) { + return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); + } + return false; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + /// Triple slash reference comments + var comment = findReferenceInPosition(sourceFile.referencedFiles, position); + if (comment) { + var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); + if (referenceFile) { + return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; + } + return undefined; + } + // Type reference directives + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + if (referenceFile && referenceFile.resolvedFileName) { + return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + } + return undefined; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + // Labels + if (ts.isJumpStatementTarget(node)) { + var labelName = node.text; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfo(label, ts.ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; + } + var typeChecker = program.getTypeChecker(); + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + if (calledDeclaration) { + return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; + } + var symbol = typeChecker.getSymbolAtLocation(node); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return undefined; + } + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol.flags & 8388608 /* Alias */) { + var declaration = symbol.declarations[0]; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from a named import. + // + if (node.kind === 69 /* Identifier */ && + (node.parent === declaration || + (declaration.kind === 234 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 233 /* NamedImports */))) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + } + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + if (!shorthandSymbol) { + return []; + } + var shorthandDeclarations = shorthandSymbol.getDeclarations(); + var shorthandSymbolKind_1 = ts.SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /// Goto type + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; + } + if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_5 = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + } + }); + return result_5; + } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(typeChecker, type.symbol, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionFromSymbol(typeChecker, symbol, node) { + var result = []; + var declarations = symbol.getDeclarations(); + var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + // Just add all the declarations. + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + // 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 (ts.isNewExpressionTarget(location) || location.kind === 121 /* ConstructorKeyword */) { + if (symbol.flags & 32 /* Class */) { + // Find the first class-like declaration and try to get the construct signature. + for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isClassLike(declaration)) { + return tryAddSignature(declaration.members, + /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); + } + } + ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 148 /* Constructor */) || + (!selectConstructors && (d.kind === 220 /* FunctionDeclaration */ || d.kind === 147 /* MethodDeclaration */ || d.kind === 146 /* MethodSignature */))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } + function createDefinitionInfo(node, symbolKind, symbolName, containerName) { + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function getSymbolInfo(typeChecker, symbol, node) { + return { + symbolName: typeChecker.symbolToString(symbol), + symbolKind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node), + containerName: symbol.parent ? typeChecker.symbolToString(symbol.parent, node) : "" + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + var _a = getSymbolInfo(typeChecker, decl.symbol, decl), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + return createDefinitionInfo(decl, symbolKind, symbolName, containerName); + } + function findReferenceInPosition(refs, pos) { + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + if (ref.pos <= pos && pos < ref.end) { + return ref; + } + } + return undefined; + } + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: ts.ScriptElementKind.scriptElement, + name: name, + containerName: undefined, + containerKind: undefined + }; + } + /** Returns a CallLikeExpression where `node` is the target being invoked. */ + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + return callLike && typeChecker.getResolvedSignature(callLike).declaration; + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToImplementation; + (function (GoToImplementation) { + function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { + // If invoked directly on a shorthand property assignment, then return + // the declaration of the symbol being assigned (not the symbol being assigned to). + if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + var result = []; + ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); + return result.length > 0 ? result : undefined; + } + else if (node.kind === 95 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + // References to and accesses on the super keyword only have one possible implementation, so no + // need to "Find all References" + var symbol = typeChecker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)]; + } + else { + // Perform "Find all References" and retrieve only those that are implementations + var referencedSymbols = ts.FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, /*findInStrings*/ false, /*findInComments*/ false, /*implementations*/ true); + var result = ts.flatMap(referencedSymbols, function (symbol) { + return ts.map(symbol.references, function (_a) { + var textSpan = _a.textSpan, fileName = _a.fileName; + return ({ textSpan: textSpan, fileName: fileName }); + }); + }); + return result && result.length > 0 ? result : undefined; + } + } + GoToImplementation.getImplementationAtPosition = getImplementationAtPosition; + })(GoToImplementation = ts.GoToImplementation || (ts.GoToImplementation = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "augments", + "author", + "argument", + "borrows", + "class", + "constant", + "constructor", + "constructs", + "default", + "deprecated", + "description", + "event", + "example", + "extends", + "field", + "fileOverview", + "function", + "ignore", + "inner", + "lends", + "link", + "memberOf", + "name", + "namespace", + "param", + "private", + "property", + "public", + "requires", + "returns", + "see", + "since", + "static", + "throws", + "type", + "typedef", + "property", + "prop", + "version" + ]; + var jsDocCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + // Only collect doc comments from duplicate declarations once: + // In case of a union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. const a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + var comments = ts.getJSDocComments(declaration, /*checkParentVariableStatement*/ true); + if (!comments) { + return; + } + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var comment = comments_3[_i]; + if (comment) { + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (ts.indexOf(array, array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getAllJsDocCompletionEntries() { + return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getAllJsDocCompletionEntries = getAllJsDocCompletionEntries; + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + // Check if in a context where we don't want to perform any insertion + if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + return undefined; + } + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenStart = tokenAtPos.getStart(); + if (!tokenAtPos || tokenStart < position) { + return undefined; + } + // TODO: add support for: + // - enums/enum members + // - interfaces + // - property declarations + // - potentially property assignments + var commentOwner; + findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 220 /* FunctionDeclaration */: + case 147 /* MethodDeclaration */: + case 148 /* Constructor */: + case 221 /* ClassDeclaration */: + case 200 /* VariableStatement */: + break findOwner; + case 256 /* SourceFile */: + return undefined; + case 225 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + if (commentOwner.parent.kind === 225 /* ModuleDeclaration */) { + return undefined; + } + break findOwner; + } + } + if (!commentOwner || commentOwner.getStart() < position) { + return undefined; + } + var parameters = getParametersForJsDocOwningNode(commentOwner); + var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); + var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; + var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var docParams = ""; + for (var i = 0, numParams = parameters.length; i < numParams; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 69 /* Identifier */ ? + currentName.text : + "param" + i; + docParams += indentationStr + " * @param " + paramName + newLine; + } + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. + var preamble = "/**" + newLine + + indentationStr + " * "; + var result = preamble + newLine + + docParams + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getParametersForJsDocOwningNode(commentOwner) { + if (ts.isFunctionLike(commentOwner)) { + return commentOwner.parameters; + } + if (commentOwner.kind === 200 /* VariableStatement */) { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + if (varDeclarations.length === 1 && varDeclarations[0].initializer) { + return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + } + } + return ts.emptyArray; + } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 178 /* ParenthesizedExpression */) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + return rightHandSide.parameters; + case 192 /* ClassExpression */: + for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148 /* Constructor */) { + return member.parameters; + } + } + break; + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + // A map of loose file names to library names + // that we are confident require typings + var safeList; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations + * @param typingOptions are used to customize the typing inference process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // Only infer typings for .js and .jsx files + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = ts.createMap(result.config); + } + var filesToWatch = []; + // Directories to search for package.json, bower.json and other typing information + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + // Add the cached typing locations for inferred typings that are already installed + for (var name_48 in packageNameToTypingLocation) { + if (name_48 in inferredTypings && !inferredTypings[name_48]) { + inferredTypings[name_48] = packageNameToTypingLocation[name_48]; + } + } + // Remove typings that the user has added to the exclude list + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + /** + * Merge a given list of typingNames to the inferredTypings map + */ + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); + } + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + /** + * Infer typing names from node_module folder + * @param nodeModulesPath is the path to the "node_modules" folder + */ + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - ts.forEach(program.getSourceFiles(), function (sourceFile) { + ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_49 in nameToDeclarations) { + var declarations = nameToDeclarations[name_49]; if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_49); if (!matches) { continue; } - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -46257,14 +66643,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_49); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -46290,8 +66676,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; if (!match.isCaseSensitive) { return false; } @@ -46366,8 +66752,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -46546,9 +66932,9 @@ var ts; case 169 /* BindingElement */: case 218 /* VariableDeclaration */: var decl = node; - var name_37 = decl.name; - if (ts.isBindingPattern(name_37)) { - addChildrenRecursively(name_37); + var name_50 = decl.name; + if (ts.isBindingPattern(name_50)) { + addChildrenRecursively(name_50); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -46595,23 +66981,19 @@ var ts; addLeafNode(node); break; default: - if (node.jsDocComments) { - for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { - var jsDocComment = _j[_h]; - for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { - var tag = _l[_k]; - if (tag.kind === 279 /* JSDocTypedefTag */) { - addLeafNode(tag); - } + ts.forEach(node.jsDocComments, function (jsDocComment) { + ts.forEach(jsDocComment.tags, function (tag) { + if (tag.kind === 279 /* JSDocTypedefTag */) { + addLeafNode(tag); } - } - } + }); + }); ts.forEachChild(node, addChildrenRecursively); } } /** Merge declarations of the same kind. */ function mergeChildren(children) { - var nameToItems = {}; + var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); @@ -46619,7 +67001,7 @@ var ts; // Anonymous items are never merged. return true; } - var itemsWithSameName = ts.getProperty(nameToItems, name); + var itemsWithSameName = nameToItems[name]; if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -46761,7 +67143,7 @@ var ts; case 179 /* FunctionExpression */: case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: - if (node.flags & 512 /* Default */) { + if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } return getFunctionOrClassName(node); @@ -46827,6 +67209,7 @@ var ts; case 147 /* MethodDeclaration */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: + case 218 /* VariableDeclaration */: return hasSomeImportantChild(item); case 180 /* ArrowFunction */: case 220 /* FunctionDeclaration */: @@ -46862,7 +67245,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -46873,7 +67256,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -46893,49 +67276,6 @@ var ts; return spans; } } - // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. - function nodeKind(node) { - switch (node.kind) { - case 256 /* SourceFile */: - return ts.ScriptElementKind.moduleElement; - case 255 /* EnumMember */: - return ts.ScriptElementKind.memberVariableElement; - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - var variableDeclarationNode = void 0; - var name_38; - if (node.kind === 169 /* BindingElement */) { - name_38 = node.name; - variableDeclarationNode = node; - // binding elements are added only for variable declarations - // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(!!variableDeclarationNode); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_38 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return ts.ScriptElementKind.constElement; - } - else if (ts.isLet(variableDeclarationNode)) { - return ts.ScriptElementKind.letElement; - } - else { - return ts.ScriptElementKind.variableElement; - } - case 180 /* ArrowFunction */: - return ts.ScriptElementKind.functionElement; - case 279 /* JSDocTypedefTag */: - return ts.ScriptElementKind.typeElement; - default: - return ts.getNodeKind(node); - } - } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. if (ts.isAmbientModule(moduleDeclaration)) { @@ -46979,7 +67319,7 @@ var ts; else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } - else if (node.flags & 512 /* Default */) { + else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } else { @@ -46993,6 +67333,168 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile) { + var elements = []; + var collapseText = "..."; + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + if (hintSpanNode && startElement && endElement) { + var span_12 = { + textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_12); + } + } + function addOutliningSpanComments(commentSpan, autoCollapse) { + if (commentSpan) { + var span_13 = { + textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_13); + } + } + function addOutliningForLeadingCommentsForNode(n) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (comments) { + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var isFirstSingleLineComment = true; + var singleLineCommentCount = 0; + for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { + var currentComment = comments_4[_i]; + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { + if (isFirstSingleLineComment) { + firstSingleLineCommentStart = currentComment.pos; + } + isFirstSingleLineComment = false; + lastSingleLineCommentEnd = currentComment.end; + singleLineCommentCount++; + } + else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) { + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + addOutliningSpanComments(currentComment, /*autoCollapse*/ false); + singleLineCommentCount = 0; + lastSingleLineCommentEnd = -1; + isFirstSingleLineComment = true; + } + } + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + } + } + function combineAndAddMultipleSingleLineComments(count, start, end) { + // Only outline spans of two or more consecutive single line comments + if (count > 1) { + var multipleSingleLineComments = { + pos: start, + end: end, + kind: 2 /* SingleLineCommentTrivia */ + }; + addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); + } + } + function autoCollapse(node) { + return ts.isFunctionBlock(node) && node.parent.kind !== 180 /* ArrowFunction */; + } + var depth = 0; + var maxDepth = 20; + function walk(n) { + if (depth > maxDepth) { + return; + } + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n); + } + switch (n.kind) { + case 199 /* Block */: + if (!ts.isFunctionBlock(n)) { + var parent_22 = n.parent; + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + if (parent_22.kind === 204 /* DoStatement */ || + parent_22.kind === 207 /* ForInStatement */ || + parent_22.kind === 208 /* ForOfStatement */ || + parent_22.kind === 206 /* ForStatement */ || + parent_22.kind === 203 /* IfStatement */ || + parent_22.kind === 205 /* WhileStatement */ || + parent_22.kind === 212 /* WithStatement */ || + parent_22.kind === 252 /* CatchClause */) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + if (parent_22.kind === 216 /* TryStatement */) { + // Could be the try-block, or the finally-block. + var tryStatement = parent_22; + if (tryStatement.tryBlock === n) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + else if (tryStatement.finallyBlock === n) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + if (finallyKeyword) { + addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + break; + } + } + } + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + var span_14 = ts.createTextSpanFromBounds(n.getStart(), n.end); + elements.push({ + textSpan: span_14, + hintSpan: span_14, + bannerText: collapseText, + autoCollapse: autoCollapse(n) + }); + break; + } + // Fallthrough. + case 226 /* ModuleBlock */: { + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 224 /* EnumDeclaration */: + case 171 /* ObjectLiteralExpression */: + case 227 /* CaseBlock */: { + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 170 /* ArrayLiteralExpression */: + var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); + var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + break; + } + depth++; + ts.forEachChild(n, walk); + depth--; + } + walk(sourceFile); + return elements; + } + OutliningElementsCollector.collectElements = collectElements; + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. (function (PatternMatchKind) { @@ -47015,7 +67517,7 @@ var ts; // we see the name of a module that is used everywhere, or the name of an overload). As // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. - var stringToWordSpans = {}; + var stringToWordSpans = ts.createMap(); pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -47071,7 +67573,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -47087,7 +67589,7 @@ var ts; else { // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive // manner. If it does, return that there was a prefix match. - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -47102,10 +67604,10 @@ var ts; // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span = wordSpans_1[_i]; - if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + var span_15 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_15, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + /*isCaseSensitive:*/ partStartsWith(candidate, span_15, chunk.text, /*ignoreCase:*/ false)); } } } @@ -47353,14 +67855,6 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function startsWith(string, search) { - for (var i = 0, n = search.length; i < n; i++) { - if (string.charCodeAt(i) !== search.charCodeAt(i)) { - return false; - } - } - return true; - } // Assumes 'value' is already lowercase. function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { @@ -47558,6 +68052,434 @@ var ts; return transition; } })(ts || (ts = {})); +var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var referencedFiles = []; + var typeReferenceDirectives = []; + var importedFiles = []; + var ambientExternalModules; + var isNoDefaultLib = false; + var braceNesting = 0; + // assume that text represent an external module if it contains at least one top level import/export + // ambient modules that are found inside external modules are interpreted as module augmentations + var externalModule = false; + function nextToken() { + var token = ts.scanner.scan(); + if (token === 15 /* OpenBraceToken */) { + braceNesting++; + } + else if (token === 16 /* CloseBraceToken */) { + braceNesting--; + } + return token; + } + function processTripleSlashDirectives() { + var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); + ts.forEach(commentRanges, function (commentRange) { + var comment = sourceText.substring(commentRange.pos, commentRange.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); + if (referencePathMatchResult) { + isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var fileReference = referencePathMatchResult.fileReference; + if (fileReference) { + var collection = referencePathMatchResult.isTypeReferenceDirective + ? typeReferenceDirectives + : referencedFiles; + collection.push(fileReference); + } + } + }); + } + function getFileReference() { + var file = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { + fileName: file, + pos: pos, + end: pos + file.length + }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 122 /* DeclareKeyword */) { + // declare module "mod" + token = nextToken(); + if (token === 125 /* ModuleKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + var token = ts.scanner.getToken(); + if (token === 89 /* ImportKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 24 /* CommaToken */) { + // consume comma and keep going + token = nextToken(); + } + else { + // unknown syntax + return true; + } + } + if (token === 15 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 16 /* CloseBraceToken */) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = nextToken(); + if (token === 116 /* AsKeyword */) { + token = nextToken(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 82 /* ExportKeyword */) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 15 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 16 /* CloseBraceToken */) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 89 /* ImportKeyword */) { + token = nextToken(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 129 /* RequireKeyword */) { + token = nextToken(); + if (token === 17 /* OpenParenToken */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 69 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 17 /* OpenParenToken */) { + return true; + } + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = nextToken(); + if (token === 24 /* CommaToken */) { + token = nextToken(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 19 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = nextToken(); + var i = 0; + // scan until ']' or EOF + while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 9 /* StringLiteral */) { + recordModuleName(); + i++; + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + // (for JavaScript files) require("mod") + while (true) { + if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { + break; + } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + processTripleSlashDirectives(); + if (externalModule) { + // for external modules module all nested ambient modules are augmentations + if (ambientExternalModules) { + // move all detected ambient modules to imported files since they need to be resolved + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + } + else { + // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + if (node) { + if (node.kind === 69 /* Identifier */ || + node.kind === 9 /* StringLiteral */ || + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + ts.isThis(node)) { + var symbol = typeChecker.getSymbolAtLocation(node); + // Only allow a symbol to be renamed if it actually has at least one declaration. + if (symbol) { + var declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + // Disallow rename for elements that are defined in the standard TypeScript library. + if (ts.forEach(declarations, isDefinedInLibraryFile)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + if (kind) { + return { + canRename: true, + kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + else if (node.kind === 9 /* StringLiteral */) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (type) { + if (isDefinedInLibraryFile(node)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + else { + var displayName = ts.stripQuotes(type.text); + return { + canRename: true, + kind: ts.ScriptElementKind.variableElement, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: displayName, + kindModifiers: ts.ScriptElementKindModifier.none, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + } + } + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); + function getRenameInfoError(localizedErrorMessage) { + return { + canRename: false, + localizedErrorMessage: localizedErrorMessage, + displayName: undefined, + fullDisplayName: undefined, + kind: undefined, + kindModifiers: undefined, + triggerSpan: undefined + }; + } + function isDefinedInLibraryFile(declaration) { + if (defaultLibFileName) { + var sourceFile_1 = declaration.getSourceFile(); + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_1.fileName)); + if (canonicalName === canonicalDefaultLibName) { + return true; + } + } + return false; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 9 /* StringLiteral */) { + // Exclude the quotes + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + } + Rename.getRenameInfo = getRenameInfo; + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); /// /* @internal */ var ts; @@ -47751,10 +68673,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = ts.getProperty(nameToDeclarations, name.text); + var declarations = nameToDeclarations[name.text]; if (declarations) { - for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { - var declaration = declarations_8[_b]; + for (var _b = 0, declarations_10 = declarations; _b < declarations_10.length; _b++) { + var declaration = declarations_10[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -48106,1084 +69028,637 @@ var ts; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); -// These utilities are common to multiple language service features. /* @internal */ var ts; (function (ts) { - function getLineStartPositionForPosition(position, sourceFile) { - var lineStarts = sourceFile.getLineStarts(); - var line = sourceFile.getLineAndCharacterOfPosition(position).line; - return lineStarts[line]; - } - ts.getLineStartPositionForPosition = getLineStartPositionForPosition; - function rangeContainsRange(r1, r2) { - return startEndContainsRange(r1.pos, r1.end, r2); - } - ts.rangeContainsRange = rangeContainsRange; - function startEndContainsRange(start, end, range) { - return start <= range.pos && end >= range.end; - } - ts.startEndContainsRange = startEndContainsRange; - function rangeContainsStartEnd(range, start, end) { - return range.pos <= start && range.end >= end; - } - ts.rangeContainsStartEnd = rangeContainsStartEnd; - function rangeOverlapsWithStartEnd(r1, start, end) { - return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); - } - ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; - function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { - var start = Math.max(start1, start2); - var end = Math.min(end1, end2); - return start < end; - } - ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; - function positionBelongsToNode(candidate, position, sourceFile) { - return candidate.end > position || !isCompletedNode(candidate, sourceFile); - } - ts.positionBelongsToNode = positionBelongsToNode; - function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { - return false; - } - switch (n.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 167 /* ObjectBindingPattern */: - case 159 /* TypeLiteral */: - case 199 /* Block */: - case 226 /* ModuleBlock */: - case 227 /* CaseBlock */: - case 233 /* NamedImports */: - case 237 /* NamedExports */: - return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 252 /* CatchClause */: - return isCompletedNode(n.block, sourceFile); - case 175 /* NewExpression */: - if (!n.arguments) { - return true; - } - // fall through - case 174 /* CallExpression */: - case 178 /* ParenthesizedExpression */: - case 164 /* ParenthesizedType */: - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - return isCompletedNode(n.type, sourceFile); - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 180 /* ArrowFunction */: - if (n.body) { - return isCompletedNode(n.body, sourceFile); - } - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - // Even though type parameters can be unclosed, we can get away with - // having at least a closing paren. - return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 225 /* ModuleDeclaration */: - return n.body && isCompletedNode(n.body, sourceFile); - case 203 /* IfStatement */: - if (n.elseStatement) { - return isCompletedNode(n.elseStatement, sourceFile); - } - return isCompletedNode(n.thenStatement, sourceFile); - case 202 /* ExpressionStatement */: - return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23 /* SemicolonToken */); - case 170 /* ArrayLiteralExpression */: - case 168 /* ArrayBindingPattern */: - case 173 /* ElementAccessExpression */: - case 140 /* ComputedPropertyName */: - case 161 /* TupleType */: - return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); - case 153 /* IndexSignature */: - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: - // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed - return false; - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: - return isCompletedNode(n.statement, sourceFile); - case 204 /* DoStatement */: - // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); - case 158 /* TypeQuery */: - return isCompletedNode(n.exprName, sourceFile); - case 182 /* TypeOfExpression */: - case 181 /* DeleteExpression */: - case 183 /* VoidExpression */: - case 190 /* YieldExpression */: - case 191 /* SpreadElementExpression */: - var unaryWordExpression = n; - return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176 /* TaggedTemplateExpression */: - return isCompletedNode(n.template, sourceFile); - case 189 /* TemplateExpression */: - var lastSpan = ts.lastOrUndefined(n.templateSpans); - return isCompletedNode(lastSpan, sourceFile); - case 197 /* TemplateSpan */: - return ts.nodeIsPresent(n.literal); - case 236 /* ExportDeclaration */: - case 230 /* ImportDeclaration */: - return ts.nodeIsPresent(n.moduleSpecifier); - case 185 /* PrefixUnaryExpression */: - return isCompletedNode(n.operand, sourceFile); - case 187 /* BinaryExpression */: - return isCompletedNode(n.right, sourceFile); - case 188 /* ConditionalExpression */: - return isCompletedNode(n.whenFalse, sourceFile); - default: - return true; - } - } - ts.isCompletedNode = isCompletedNode; - /* - * Checks if node ends with 'expectedLastToken'. - * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. - */ - function nodeEndsWith(n, expectedLastToken, sourceFile) { - var children = n.getChildren(sourceFile); - if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { - return true; - } - else if (last.kind === 23 /* SemicolonToken */ && children.length !== 1) { - return children[children.length - 2].kind === expectedLastToken; + var SymbolDisplay; + (function (SymbolDisplay) { + // TODO(drosen): use contextual SemanticMeaning. + function getSymbolKind(typeChecker, symbol, location) { + var flags = symbol.getFlags(); + if (flags & 32 /* Class */) + return ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */) ? + ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + if (flags & 384 /* Enum */) + return ts.ScriptElementKind.enumElement; + if (flags & 524288 /* TypeAlias */) + return ts.ScriptElementKind.typeElement; + if (flags & 64 /* Interface */) + return ts.ScriptElementKind.interfaceElement; + if (flags & 262144 /* TypeParameter */) + return ts.ScriptElementKind.typeParameterElement; + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location); + if (result === ts.ScriptElementKind.unknown) { + if (flags & 262144 /* TypeParameter */) + return ts.ScriptElementKind.typeParameterElement; + if (flags & 8 /* EnumMember */) + return ts.ScriptElementKind.variableElement; + if (flags & 8388608 /* Alias */) + return ts.ScriptElementKind.alias; + if (flags & 1536 /* Module */) + return ts.ScriptElementKind.moduleElement; } + return result; } - return false; - } - function findListItemInfo(node) { - var list = findContainingList(node); - // It is possible at this point for syntaxList to be undefined, either if - // node.parent had no list child, or if none of its list children contained - // the span of node. If this happens, return undefined. The caller should - // handle this case. - if (!list) { - return undefined; - } - var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); - return { - listItemIndex: listItemIndex, - list: list - }; - } - ts.findListItemInfo = findListItemInfo; - function hasChildOfKind(n, kind, sourceFile) { - return !!findChildOfKind(n, kind, sourceFile); - } - ts.hasChildOfKind = hasChildOfKind; - function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); - } - ts.findChildOfKind = findChildOfKind; - function findContainingList(node) { - // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will - // be parented by the container of the SyntaxList, not the SyntaxList itself. - // In order to find the list item index, we first need to locate SyntaxList itself and then search - // for the position of the relevant node (or comma). - var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - // find syntax list that covers the span of the node - if (c.kind === 282 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { - return c; + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location) { + if (typeChecker.isUndefinedSymbol(symbol)) { + return ts.ScriptElementKind.variableElement; } - }); - // Either we didn't find an appropriate list, or the list must contain us. - ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); - return syntaxList; - } - ts.findContainingList = findContainingList; - /* Gets the token whose text has range [start, end) and - * position >= start and (position < end or (position === end && token is keyword or identifier)) - */ - function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); - } - ts.getTouchingWord = getTouchingWord; - /* Gets the token whose text has range [start, end) and position >= start - * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) - */ - function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); - } - ts.getTouchingPropertyName = getTouchingPropertyName; - /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); - } - ts.getTouchingToken = getTouchingToken; - /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); - } - ts.getTokenAtPosition = getTokenAtPosition; - /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - var current = sourceFile; - outer: while (true) { - if (isToken(current)) { - // exit early - return current; + if (typeChecker.isArgumentsSymbol(symbol)) { + return ts.ScriptElementKind.localVariableElement; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; + if (location.kind === 97 /* ThisKeyword */ && ts.isExpression(location)) { + return ts.ScriptElementKind.parameterElement; + } + if (flags & 3 /* Variable */) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return ts.ScriptElementKind.parameterElement; + } + else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return ts.ScriptElementKind.letElement; + } + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + if (flags & 32768 /* GetAccessor */) + return ts.ScriptElementKind.memberGetAccessorElement; + if (flags & 65536 /* SetAccessor */) + return ts.ScriptElementKind.memberSetAccessorElement; + if (flags & 8192 /* Method */) + return ts.ScriptElementKind.memberFunctionElement; + if (flags & 16384 /* Constructor */) + return ts.ScriptElementKind.constructorImplementationElement; + if (flags & 4 /* Property */) { + if (flags & 268435456 /* SyntheticProperty */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return ts.ScriptElementKind.memberVariableElement; } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; + ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); + }); + if (!unionPropertyKind) { + // If this was union of all methods, + // make sure it has call signatures before we can label it as method + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return ts.ScriptElementKind.memberFunctionElement; + } + return ts.ScriptElementKind.memberVariableElement; + } + return unionPropertyKind; + } + return ts.ScriptElementKind.memberVariableElement; + } + return ts.ScriptElementKind.unknown; + } + function getSymbolModifiers(symbol) { + return symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : ts.ScriptElementKindModifier.none; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var symbolFlags = symbol.flags; + var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); + var hasAddedSymbolInfo; + var isThisExpression = location.kind === 97 /* ThisKeyword */ && ts.isExpression(location); + var type; + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { + symbolKind = ts.ScriptElementKind.memberVariableElement; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (type) { + if (location.parent && location.parent.kind === 172 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpression = void 0; + if (location.kind === 174 /* CallExpression */ || location.kind === 175 /* NewExpression */) { + callExpression = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpression = location.parent; + } + if (callExpression) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); + if (!signature && candidateSignatures.length) { + // Use the first candidate: + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpression.kind === 175 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 8388608 /* Alias */) { + symbolKind = ts.ScriptElementKind.alias; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case ts.ScriptElementKind.memberVariableElement: + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.parameterElement: + case ts.ScriptElementKind.localVariableElement: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + if (!(type.flags & 2097152 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + } + addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || + (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 148 /* Constructor */)) { + // get the signature from the declaration and write it + var functionDeclaration = location.parent; + var allSignatures = functionDeclaration.kind === 148 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration.kind === 148 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + if (ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushTypePart(ts.ScriptElementKind.localClassElement); + } + else { + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(73 /* ClassKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(107 /* InterfaceKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if (symbolFlags & 524288 /* TypeAlias */) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); + } + if (symbolFlags & 384 /* Enum */) { + addNewLineIfDisplayPartsExist(); + if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + displayParts.push(ts.keywordPart(74 /* ConstKeyword */)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(81 /* EnumKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536 /* Module */) { + addNewLineIfDisplayPartsExist(); + var declaration = ts.getDeclarationOfKind(symbol, 225 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(90 /* InKeyword */)); + displayParts.push(ts.spacePart()); + if (symbol.parent) { + // Class/Interface type parameter + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + // Method/function type parameter + var declaration = ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 152 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 151 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8 /* EnumMember */) { + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 255 /* EnumMember */) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + } + } + } + if (symbolFlags & 8388608 /* Alias */) { + addNewLineIfDisplayPartsExist(); + if (symbol.declarations[0].kind === 228 /* NamespaceExportDeclaration */) { + displayParts.push(ts.keywordPart(82 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(126 /* NamespaceKeyword */)); + } + else { + displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 229 /* ImportEqualsDeclaration */) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== ts.ScriptElementKind.unknown) { + if (type) { + if (isThisExpression) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(97 /* ThisKeyword */)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + // For properties, variables and local vars: show the type + if (symbolKind === ts.ScriptElementKind.memberVariableElement || + symbolFlags & 3 /* Variable */ || + symbolKind === ts.ScriptElementKind.localVariableElement || + isThisExpression) { + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.spacePart()); + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === ts.ScriptElementKind.memberFunctionElement) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(); + if (documentation.length === 0 && symbol.flags & 4 /* Property */) { + // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` + // there documentation comments might be attached to the right hand side symbol of their declarations. + // The pattern of such special property access is that the parent symbol is the symbol of the file. + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256 /* SourceFile */; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 187 /* BinaryExpression */) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; } } } } } - // find the child that contains 'position' - for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { - var child = current.getChildAt(i); - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { - continue; - } - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + function addNewLineIfDisplayPartsExist() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); } } - return current; - } - } - /** - * The token on the left of the position is the token that strictly includes the position - * or sits to the left of the cursor if it is on a boundary. For example - * - * fo|o -> will return foo - * foo |bar -> will return foo - * - */ - function findTokenOnLeftOfPosition(file, position) { - // Ideally, getTokenAtPosition should return a token. However, it is currently - // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position); - if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { - return tokenAtPosition; - } - return findPrecedingToken(position, file); - } - ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { - return find(parent); - function find(n) { - if (isToken(n) && n.pos === previousToken.end) { - // this is token that starts at the end of previous token - return it - return n; + function addFullSymbolName(symbol, enclosingDeclaration) { + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + ts.addRange(displayParts, fullSymbolDisplayParts); } - var children = n.getChildren(); - for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { - var child = children_1[_i]; - var shouldDiveInChildNode = - // previous token is enclosed somewhere in the child - (child.pos <= previousToken.pos && child.end > previousToken.end) || - // previous token ends exactly at the beginning of child - (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { - return find(child); + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + addNewLineIfDisplayPartsExist(); + if (symbolKind) { + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); } } - return undefined; - } - } - ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { - return find(startNode || sourceFile); - function findRightmostToken(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { - return n; - } - var children = n.getChildren(); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); - return candidate && findRightmostToken(candidate); - } - function find(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { - return n; - } - var children = n.getChildren(); - for (var i = 0, len = children.length; i < len; i++) { - var child = children[i]; - // condition 'position < child.end' checks if child node end after the position - // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' - // aaaa___bbbb___$__ccc - // after we found child node with end after the position we check if start of the node is after the position. - // if yes - then position is in the trivia and we need to look into the previous child to find the token in question. - // if no - position is in the node itself so we should recurse in it. - // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). - // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 244 /* JsxText */)) { - var start = child.getStart(sourceFile); - var lookInPreviousChild = (start >= position) || - (child.kind === 244 /* JsxText */ && start === child.end); // whitespace only JsxText - if (lookInPreviousChild) { - // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); - return candidate && findRightmostToken(candidate); - } - else { - // candidate should be in this node - return find(child); - } + function pushTypePart(symbolKind) { + switch (symbolKind) { + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.functionElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.constructorImplementationElement: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + return; } } - ts.Debug.assert(startNode !== undefined || n.kind === 256 /* SourceFile */); - // Here we know that none of child token nodes embrace the position, - // the only known case is when position is at the end of the file. - // Try to find the rightmost token in the file without filtering. - // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); - return candidate && findRightmostToken(candidate); - } - } - /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { - for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { - return children[i]; + function addSignatureDisplayParts(signature, allSignatures, flags) { + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(35 /* PlusToken */)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); } + documentation = signature.getDocumentationComment(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); } } - } - ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 /* StringLiteral */ || previousToken.kind === 166 /* StringLiteralType */)) { - var start = previousToken.getStart(); - var end = previousToken.getEnd(); - // To be "in" one of these literals, the position has to be: - // 1. entirely within the token text. - // 2. at the end position of an unterminated token. - // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start < position && position < end) { - return true; + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; // This is exported symbol } - if (position === end) { - return !!previousToken.isUnterminated; - } - } - return false; - } - ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; - /** - * returns true if the position is in between the open and close elements of an JSX expression. - */ - function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - if (!token) { - return false; - } - if (token.kind === 244 /* JsxText */) { - return true; - } - //
Hello |
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { - return true; - } - //
{ |
or
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { - return true; - } - //
{ - // | - // } < /div> - if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { - return true; - } - //
|
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { - return true; - } - return false; - } - ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; - function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); - } - ts.isInTemplateString = isInTemplateString; - /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. - */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - // The end marker of a single-line comment does not include the newline character. - // In the following case, we are inside a comment (^ denotes the cursor position): - // - // // asdf ^\n - // - // But for multi-line comments, we don't want to be inside the comment in the following case: - // - // /* asdf */^ - // - // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); - } - return false; - } - ts.isInCommentHelper = isInCommentHelper; - function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - // First, we have to see if this position actually landed in a comment. - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return ts.forEach(commentRanges, jsDocPrefix); - function jsDocPrefix(c) { - var text = sourceFile.text; - return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; - } - } - ts.hasDocComment = hasDocComment; - /** - * Get the corresponding JSDocTag node if the position is in a jsDoc comment - */ - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (isToken(node)) { - switch (node.kind) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - // if the current token is var, let or const, skip the VariableDeclarationList - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } + return ts.forEach(symbol.declarations, function (declaration) { + // Function expressions are local + if (declaration.kind === 179 /* FunctionExpression */) { + return true; } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; - function nodeHasTokens(n) { - // If we have a token or node that has a non-zero width, it must have tokens. - // Note, that getWidth() does not take trivia into account. - return n.getWidth() !== 0; - } - function getNodeModifiers(node) { - var flags = ts.getCombinedNodeFlags(node); - var result = []; - if (flags & 8 /* Private */) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 16 /* Protected */) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 4 /* Public */) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 32 /* Static */) - result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 128 /* Abstract */) - result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1 /* Export */) - result.push(ts.ScriptElementKindModifier.exportedModifier); - if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; - } - ts.getNodeModifiers = getNodeModifiers; - function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 /* TypeReference */ || node.kind === 174 /* CallExpression */) { - return node.typeArguments; - } - if (ts.isFunctionLike(node) || node.kind === 221 /* ClassDeclaration */ || node.kind === 222 /* InterfaceDeclaration */) { - return node.typeParameters; - } - return undefined; - } - ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; - function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 138 /* LastToken */; - } - ts.isToken = isToken; - function isWord(kind) { - return kind === 69 /* Identifier */ || ts.isKeyword(kind); - } - ts.isWord = isWord; - function isPropertyName(kind) { - return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); - } - function isComment(kind) { - return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; - } - ts.isComment = isComment; - function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 /* StringLiteral */ - || kind === 166 /* StringLiteralType */ - || kind === 10 /* RegularExpressionLiteral */ - || ts.isTemplateLiteralKind(kind)) { - return true; - } - return false; - } - ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; - function isPunctuation(kind) { - return 15 /* FirstPunctuation */ <= kind && kind <= 68 /* LastPunctuation */; - } - ts.isPunctuation = isPunctuation; - function isInsideTemplateLiteral(node, position) { - return ts.isTemplateLiteralKind(node.kind) - && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); - } - ts.isInsideTemplateLiteral = isInsideTemplateLiteral; - function isAccessibilityModifier(kind) { - switch (kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return true; - } - return false; - } - ts.isAccessibilityModifier = isAccessibilityModifier; - function compareDataObjects(dst, src) { - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { + if (declaration.kind !== 218 /* VariableDeclaration */ && declaration.kind !== 220 /* FunctionDeclaration */) { return false; } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; + // If the parent is not sourceFile or module block it is local variable + for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { + // Reached source file or module block + if (parent_23.kind === 256 /* SourceFile */ || parent_23.kind === 226 /* ModuleBlock */) { + return false; + } } - } + // parent is in function block + return true; + }); } - return true; - } - ts.compareDataObjects = compareDataObjects; - function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 /* ArrayLiteralExpression */ || - node.kind === 171 /* ObjectLiteralExpression */) { - // [a,b,c] from: - // [a, b, c] = someExpression; - if (node.parent.kind === 187 /* BinaryExpression */ && - node.parent.left === node && - node.parent.operatorToken.kind === 56 /* EqualsToken */) { - return true; - } - // [a, b, c] from: - // for([a, b, c] of expression) - if (node.parent.kind === 208 /* ForOfStatement */ && - node.parent.initializer === node) { - return true; - } - // [a, b, c] of - // [x, [a, b, c] ] = someExpression - // or - // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { - return true; - } - } - return false; - } - ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); })(ts || (ts = {})); -// Display-part writer helpers -/* @internal */ var ts; (function (ts) { - function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; - } - ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; - var displayPartWriter = getDisplayPartWriter(); - function getDisplayPartWriter() { - var displayParts; - var lineStart; - var indent; - resetWriter(); - return { - displayParts: function () { return displayParts; }, - writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, - writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, - writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, - writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, - writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, - writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, - writeSymbol: writeSymbol, - writeLine: writeLine, - increaseIndent: function () { indent++; }, - decreaseIndent: function () { indent--; }, - clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } - }; - function writeIndent() { - if (lineStart) { - var indentString = ts.getIndentString(indent); - if (indentString) { - displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); - } - lineStart = false; - } - } - function writeKind(text, kind) { - writeIndent(); - displayParts.push(displayPart(text, kind)); - } - function writeSymbol(text, symbol) { - writeIndent(); - displayParts.push(symbolPart(text, symbol)); - } - function writeLine() { - displayParts.push(lineBreakPart()); - lineStart = true; - } - function resetWriter() { - displayParts = []; - lineStart = true; - indent = 0; - } - } - function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); - function displayPartKind(symbol) { - var flags = symbol.flags; - if (flags & 3 /* Variable */) { - return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; - } - else if (flags & 4 /* Property */) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 32768 /* GetAccessor */) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 65536 /* SetAccessor */) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 8 /* EnumMember */) { - return ts.SymbolDisplayPartKind.enumMemberName; - } - else if (flags & 16 /* Function */) { - return ts.SymbolDisplayPartKind.functionName; - } - else if (flags & 32 /* Class */) { - return ts.SymbolDisplayPartKind.className; - } - else if (flags & 64 /* Interface */) { - return ts.SymbolDisplayPartKind.interfaceName; - } - else if (flags & 384 /* Enum */) { - return ts.SymbolDisplayPartKind.enumName; - } - else if (flags & 1536 /* Module */) { - return ts.SymbolDisplayPartKind.moduleName; - } - else if (flags & 8192 /* Method */) { - return ts.SymbolDisplayPartKind.methodName; - } - else if (flags & 262144 /* TypeParameter */) { - return ts.SymbolDisplayPartKind.typeParameterName; - } - else if (flags & 524288 /* TypeAlias */) { - return ts.SymbolDisplayPartKind.aliasName; - } - else if (flags & 8388608 /* Alias */) { - return ts.SymbolDisplayPartKind.aliasName; - } - return ts.SymbolDisplayPartKind.text; - } - } - ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] - }; - } - ts.displayPart = displayPart; - function spacePart() { - return displayPart(" ", ts.SymbolDisplayPartKind.space); - } - ts.spacePart = spacePart; - function keywordPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); - } - ts.keywordPart = keywordPart; - function punctuationPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); - } - ts.punctuationPart = punctuationPart; - function operatorPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); - } - ts.operatorPart = operatorPart; - function textOrKeywordPart(text) { - var kind = ts.stringToToken(text); - return kind === undefined - ? textPart(text) - : keywordPart(kind); - } - ts.textOrKeywordPart = textOrKeywordPart; - function textPart(text) { - return displayPart(text, ts.SymbolDisplayPartKind.text); - } - ts.textPart = textPart; - var carriageReturnLineFeed = "\r\n"; - /** - * The default is CRLF. + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; - } - ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; - function lineBreakPart() { - return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); - } - ts.lineBreakPart = lineBreakPart; - function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; - } - ts.mapToDisplayParts = mapToDisplayParts; - function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - }); - } - ts.typeToDisplayParts = typeToDisplayParts; - function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { - return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); - }); - } - ts.symbolToDisplayParts = symbolToDisplayParts; - function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); - }); - } - ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location)) { - return location.getText(); + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; + // Filename can be non-ts file. + options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + // if jsx is specified then treat file as .tsx + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140 /* ComputedPropertyName */) { - return location.text; + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); - return name; + var newLine = ts.getNewLineCharacter(options); + // Output + var outputText; + var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files + var compilerHost = { + getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text, writeByteOrderMark) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + sourceMapText = text; + } + else { + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } + }; + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } + // Emit + program.emit(); + ts.Debug.assert(outputText !== undefined, "Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } - ts.getDeclaredName = getDeclaredName; - function isImportOrExportSpecifierName(location) { - return location.parent && - (location.parent.kind === 234 /* ImportSpecifier */ || location.parent.kind === 238 /* ExportSpecifier */) && - location.parent.propertyName === location; - } - ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; - /** - * Strip off existed single quotes or double quotes from a given string - * - * @return non-quoted string + ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. */ - function stripQuotes(name) { - var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { - return name.substring(1, length - 1); - } - ; - return name; + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; } - ts.stripQuotes = stripQuotes; - function scriptKindIs(fileName, host) { - var scriptKinds = []; - for (var _i = 2; _i < arguments.length; _i++) { - scriptKinds[_i - 2] = arguments[_i]; + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ + function fixupCompilerOptions(options, diagnostics) { + // Lazily create this value to fix module loading errors. + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.clone(options); + var _loop_2 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + // Value should be a key of opt.type + if (typeof value === "string") { + // If value is not a string, this will fail + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { + // Supplied value isn't a valid enum value. + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + }; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_2(opt); } - var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return options; } - ts.scriptKindIs = scriptKindIs; - function getScriptKind(fileName, host) { - // First check to see if the script kind was specified by the host. Chances are the host - // may override the default script kind for the file extension. - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind || scriptKind === 0 /* Unknown */) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); - } - ts.getScriptKind = getScriptKind; -})(ts || (ts = {})); -// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. -// See LICENSE.txt in the project root for complete license information. -/// -/* @internal */ -var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - // A map of loose file names to library names - // that we are confident require typings - var safeList; - /** - * @param host is the object providing I/O related operations. - * @param fileNames are the file names that belong to the same project - * @param projectRootPath is the path to the project root directory - * @param safeListPath is the path used to retrieve the safe list - * @param packageNameToTypingLocation is the map of package names to their cached typing locations - * @param typingOptions are used to customize the typing inference process - * @param compilerOptions are used as a source for typing inference - */ - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - // A typing name to typing file path mapping - var inferredTypings = {}; - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - if (result.config) { - safeList = result.config; - } - else { - safeList = {}; - } - ; - } - var filesToWatch = []; - // Directories to search for package.json, bower.json and other typing information - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - // Add the cached typing locations for inferred typings that are already installed - for (var name_39 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { - inferredTypings[name_39] = packageNameToTypingLocation[name_39]; - } - } - // Remove typings that the user has added to the exclude list - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - /** - * Merge a given list of typingNames to the inferredTypings map - */ - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { - inferredTypings[typing] = undefined; - } - } - } - /** - * Get the typing info from common package manager json files like package.json or bower.json - */ - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); - } - } - } - /** - * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" - * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred - * to the 'angular-route' typing name. - * @param fileNames are the names for source files in the project - */ - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - /** - * Infer typing names from node_module folder - * @param nodeModulesPath is the path to the "node_modules" folder - */ - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - // Todo: add support for ModuleResolutionHost too - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; - var normalizedFileName = ts.normalizePath(fileName); - if (ts.getBaseFileName(normalizedFileName) !== "package.json") { - continue; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - // npm 3's package.json contains a "_requiredBy" field - // we should include all the top level module names for npm 2, and only module names whose - // "_requiredBy" field starts with "#" or equals "/" for npm 3. - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used - // to download d.ts files from DefinitelyTyped - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /// /// @@ -49205,6 +69680,7 @@ var ts; ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); function getFormattingScanner(sourceFile, startPos, endPos) { ts.Debug.assert(scanner === undefined); @@ -49296,6 +69772,9 @@ var ts; } return false; } + function shouldRescanJsxText(node) { + return node && node.kind === 244 /* JsxText */; + } function shouldRescanSlashToken(container) { return container.kind === 10 /* RegularExpressionLiteral */; } @@ -49326,7 +69805,9 @@ var ts; ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ - : 0 /* Scan */; + : shouldRescanJsxText(n) + ? 5 /* RescanJsxText */ + : 0 /* Scan */; if (lastTokenInfo && expectedScanAction === lastScanAction) { // readTokenInfo was called before with the same expected scan action. // No need to re-scan text, return existing 'lastTokenInfo' @@ -49361,6 +69842,10 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4 /* RescanJsxIdentifier */; } + else if (expectedScanAction === 5 /* RescanJsxText */) { + currentToken = scanner.reScanJsxToken(); + lastScanAction = 5 /* RescanJsxText */; + } else { lastScanAction = 0 /* Scan */; } @@ -49664,9 +70149,9 @@ var ts; } return true; }; - RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); + RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -49716,6 +70201,8 @@ var ts; // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); // Insert new line after { and before } in multi-line contexts. this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); @@ -49750,7 +70237,7 @@ var ts; this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} @@ -49781,7 +70268,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); // Remove spaces in empty interface literals. e.g.: x: {} this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); // decorators @@ -49797,6 +70283,12 @@ var ts; this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + // jsx opening element + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39 /* SlashToken */, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, @@ -49811,7 +70303,7 @@ var ts; this.SpaceAfterPostdecrementWhenFollowedBySubtract, this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, this.NoSpaceAfterCloseBrace, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, @@ -49824,6 +70316,8 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, + this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, + this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, // TypeScript-specific rules this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, @@ -49837,7 +70331,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket, this.NoSpaceBeforeCloseAngularBracket, this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, @@ -49857,8 +70350,8 @@ var ts; /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); // Insert space before and after binary operators this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -49895,19 +70388,22 @@ var ts; this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); + // No space after type assertion + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_40 in o) { - if (o[name_40] === rule) { - return name_40; + for (var name_51 in o) { + if (o[name_51] === rule) { + return name_51; } } throw new Error("Unknown rule"); @@ -50110,12 +70606,21 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244 /* JsxText */; }; - Rules.isNonJsxElementContext = function (context) { + Rules.IsNonJsxElementContext = function (context) { return context.contextNode.kind !== 241 /* JsxElement */; }; - Rules.isJsxExpressionContext = function (context) { + Rules.IsJsxExpressionContext = function (context) { return context.contextNode.kind === 248 /* JsxExpression */; }; + Rules.IsNextTokenParentJsxAttribute = function (context) { + return context.nextTokenParent.kind === 246 /* JsxAttribute */; + }; + Rules.IsJsxAttributeContext = function (context) { + return context.contextNode.kind === 246 /* JsxAttribute */; + }; + Rules.IsJsxSelfClosingElementContext = function (context) { + return context.contextNode.kind === 242 /* JsxSelfClosingElement */; + }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -50126,7 +70631,7 @@ var ts; !Rules.NodeIsInDecoratorContext(context.nextTokenParent); }; Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isExpression(node)) { + while (ts.isPartOfExpression(node)) { node = node.parent; } return node.kind === 143 /* Decorator */; @@ -50439,21 +70944,21 @@ var ts; TokenRange.prototype.toString = function () { return this.tokenAccess.toString(); }; - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 138 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 138 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 130 /* NumberKeyword */, 132 /* StringKeyword */, 120 /* BooleanKeyword */, 133 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); return TokenRange; }()); + TokenRange.Any = TokenRange.AllTokens(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 138 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 138 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 130 /* NumberKeyword */, 132 /* StringKeyword */, 120 /* BooleanKeyword */, 133 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -50538,6 +71043,18 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true + // so if the option is undefined, we should treat it as true as well + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + rules.push(this.globalRules.SpaceAfterOpenBrace); + rules.push(this.globalRules.SpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } + else { + rules.push(this.globalRules.NoSpaceAfterOpenBrace); + rules.push(this.globalRules.NoSpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); @@ -50575,6 +71092,12 @@ var ts; rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } + if (options.InsertSpaceAfterTypeAssertion) { + rules.push(this.globalRules.SpaceAfterTypeAssertion); + } + else { + rules.push(this.globalRules.NoSpaceAfterTypeAssertion); + } rules = rules.concat(this.globalRules.LowPriorityCommonRules); return rules; }; @@ -50918,8 +71441,9 @@ var ts; case 147 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; - } - // fall-through + } /* + fall-through + */ case 145 /* PropertyDeclaration */: case 142 /* Parameter */: return node.name.kind; @@ -51673,7 +72197,7 @@ var ts; // actual indentation is used for statements\declarations if one of cases below is true: // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line - var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && (parent.kind === 256 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; @@ -51951,101 +72475,49 @@ var ts; })(ts || (ts = {})); /// /// +/// +/// /// -/// +/// +/// +/// +/// +/// +/// +/// +/// +/// /// /// +/// /// +/// +/// /// -/// -/// +/// +/// /// /// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; - var ScriptSnapshot; - (function (ScriptSnapshot) { - var StringScriptSnapshot = (function () { - function StringScriptSnapshot(text) { - this.text = text; - } - StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringScriptSnapshot.prototype.getLength = function () { - return this.text.length; - }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { - // Text-based snapshots do not support incremental parsing. Return undefined - // to signal that to the caller. - return undefined; - }; - return StringScriptSnapshot; - }()); - function fromString(text) { - return new StringScriptSnapshot(text); - } - ScriptSnapshot.fromString = fromString; - })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var emptyArray = []; - var jsDocTagNames = [ - "augments", - "author", - "argument", - "borrows", - "class", - "constant", - "constructor", - "constructs", - "default", - "deprecated", - "description", - "event", - "example", - "extends", - "field", - "fileOverview", - "function", - "ignore", - "inner", - "lends", - "link", - "memberOf", - "name", - "namespace", - "param", - "private", - "property", - "public", - "requires", - "returns", - "see", - "since", - "static", - "throws", - "type", - "typedef", - "property", - "prop", - "version" - ]; - var jsDocCompletionEntries; - function createNode(kind, pos, end, flags, parent) { - var node = new NodeObject(kind, pos, end); - node.flags = flags; + function createNode(kind, pos, end, parent) { + var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : + kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + new TokenObject(kind, pos, end); node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { - this.kind = kind; this.pos = pos; this.end = end; this.flags = 0 /* None */; + this.transformFlags = undefined; + this.excludeTransformFlags = undefined; this.parent = undefined; + this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -52072,22 +72544,25 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { - scanner.setTextPos(pos); + ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); - var textPos = scanner.getTextPos(); + var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, 0, this)); + nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); + var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -52107,16 +72582,19 @@ var ts; var _this = this; var children; if (this.kind >= 139 /* FirstNode */) { - scanner.setText((sourceFile || this.getSourceFile()).text); + ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 281 /* LastJSDocTagNode */; + var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 285 /* LastJSDocTagNode */; var processNode = function (node) { - if (pos_3 < node.pos) { + var isJSDocTagNode = ts.isJSDocTag(node); + if (!isJSDocTagNode && pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - pos_3 = node.end; + if (!isJSDocTagNode) { + pos_3 = node.end; + } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -52132,13 +72610,17 @@ var ts; processNode(jsDocComment); } } + // For syntactic classifications, all trivia are classcified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { this.addSyntheticNodes(children, pos_3, this.end); } - scanner.setText(undefined); + ts.scanner.setText(undefined); } - this._children = children || emptyArray; + this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -52173,6 +72655,58 @@ var ts; }; return NodeObject; }()); + var TokenOrIdentifierObject = (function () { + function TokenOrIdentifierObject(pos, end) { + // Set properties in same order as NodeObject + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + return ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + return undefined; + }; + return TokenOrIdentifierObject; + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -52189,301 +72723,28 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4 /* Property */)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4 /* Property */)); } return this.documentationComment; }; return SymbolObject; }()); - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { - var documentationComment = []; - var docComments = getJsDocCommentsSeparatedByNewLines(); - ts.forEach(docComments, function (docComment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(docComment); - }); - return documentationComment; - function getJsDocCommentsSeparatedByNewLines() { - var paramTag = "@param"; - var jsDocCommentParts = []; - ts.forEach(declarations, function (declaration, indexOfDeclaration) { - // Make sure we are collecting doc comment from declaration once, - // In case of union property there might be same declaration multiple times - // which only varies in type parameter - // Eg. const a: Array | Array; a.length - // The property length will have two declarations of property length coming - // from Array - Array and Array - if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); - // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments - if (canUseParsedParamTagComments && declaration.kind === 142 /* Parameter */) { - if ((declaration.parent.kind === 179 /* FunctionExpression */ || declaration.parent.kind === 180 /* ArrowFunction */) && - declaration.parent.parent.kind === 218 /* VariableDeclaration */) { - addCommentParts(declaration.parent.parent.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body && declaration.body.kind === 225 /* ModuleDeclaration */) { - return; - } - if ((declaration.kind === 179 /* FunctionExpression */ || declaration.kind === 180 /* ArrowFunction */) && - declaration.parent.kind === 218 /* VariableDeclaration */) { - addCommentParts(declaration.parent.parent, sourceFileOfDeclaration, getCleanedJsDocComment); - } - // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 225 /* ModuleDeclaration */ && declaration.parent.kind === 225 /* ModuleDeclaration */) { - declaration = declaration.parent; - } - addCommentParts(declaration.kind === 218 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration, getCleanedJsDocComment); - if (declaration.kind === 218 /* VariableDeclaration */) { - var init = declaration.initializer; - if (init && (init.kind === 179 /* FunctionExpression */ || init.kind === 180 /* ArrowFunction */)) { - // Get the cleaned js doc comment text from the initializer - addCommentParts(init, sourceFileOfDeclaration, getCleanedJsDocComment); - } - } - } - }); - return jsDocCommentParts; - function addCommentParts(commented, sourceFileOfDeclaration, getCommentPart) { - var ranges = getJsDocCommentTextRange(commented, sourceFileOfDeclaration); - // Get the cleaned js doc comment text from the declaration - ts.forEach(ranges, function (jsDocCommentTextRange) { - var cleanedComment = getCommentPart(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); - if (cleanedComment) { - ts.addRange(jsDocCommentParts, cleanedComment); - } - }); - } - function getJsDocCommentTextRange(node, sourceFile) { - return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { - return { - pos: jsDocComment.pos + "/*".length, - end: jsDocComment.end - "*/".length // Trim off comment end indicator - }; - }); - } - function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { - if (maxSpacesToRemove !== undefined) { - end = Math.min(end, pos + maxSpacesToRemove); - } - for (; pos < end; pos++) { - var ch = sourceFile.text.charCodeAt(pos); - if (!ts.isWhiteSpaceSingleLine(ch)) { - return pos; - } - } - return end; - } - function consumeLineBreaks(pos, end, sourceFile) { - while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function isName(pos, end, sourceFile, name) { - return pos + name.length < end && - sourceFile.text.substr(pos, name.length) === name && - ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)); - } - function isParamTag(pos, end, sourceFile) { - // If it is @param tag - return isName(pos, end, sourceFile, paramTag); - } - function pushDocCommentLineText(docComments, text, blankLineCount) { - // Add the empty lines in between texts - while (blankLineCount) { - blankLineCount--; - docComments.push(ts.textPart("")); - } - docComments.push(ts.textPart(text)); - } - function getCleanedJsDocComment(pos, end, sourceFile) { - var spacesToRemoveAfterAsterisk; - var docComments = []; - var blankLineCount = 0; - var isInParamTag = false; - while (pos < end) { - var docCommentTextOfLine = ""; - // First consume leading white space - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); - // If the comment starts with '*' consume the spaces on this line - if (pos < end && sourceFile.text.charCodeAt(pos) === 42 /* asterisk */) { - var lineStartPos = pos + 1; - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); - // Set the spaces to remove after asterisk as margin if not already set - if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - spacesToRemoveAfterAsterisk = pos - lineStartPos; - } - } - else if (spacesToRemoveAfterAsterisk === undefined) { - spacesToRemoveAfterAsterisk = 0; - } - // Analyze text on this line - while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - var ch = sourceFile.text.charAt(pos); - if (ch === "@") { - // If it is @param tag - if (isParamTag(pos, end, sourceFile)) { - isInParamTag = true; - pos += paramTag.length; - continue; - } - else { - isInParamTag = false; - } - } - // Add the ch to doc text if we arent in param tag - if (!isInParamTag) { - docCommentTextOfLine += ch; - } - // Scan next character - pos++; - } - // Continue with next line - pos = consumeLineBreaks(pos, end, sourceFile); - if (docCommentTextOfLine) { - pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); - blankLineCount = 0; - } - else if (!isInParamTag && docComments.length) { - // This is blank line when there is text already parsed - blankLineCount++; - } - } - return docComments; - } - function getCleanedParamJsDocComment(pos, end, sourceFile) { - var paramHelpStringMargin; - var paramDocComments = []; - while (pos < end) { - if (isParamTag(pos, end, sourceFile)) { - var blankLineCount = 0; - var recordedParamTag = false; - // Consume leading spaces - pos = consumeWhiteSpaces(pos + paramTag.length); - if (pos >= end) { - break; - } - // Ignore type expression - if (sourceFile.text.charCodeAt(pos) === 123 /* openBrace */) { - pos++; - for (var curlies = 1; pos < end; pos++) { - var charCode = sourceFile.text.charCodeAt(pos); - // { character means we need to find another } to match the found one - if (charCode === 123 /* openBrace */) { - curlies++; - continue; - } - // } char - if (charCode === 125 /* closeBrace */) { - curlies--; - if (curlies === 0) { - // We do not have any more } to match the type expression is ignored completely - pos++; - break; - } - else { - // there are more { to be matched with } - continue; - } - } - // Found start of another tag - if (charCode === 64 /* at */) { - break; - } - } - // Consume white spaces - pos = consumeWhiteSpaces(pos); - if (pos >= end) { - break; - } - } - // Parameter name - if (isName(pos, end, sourceFile, name)) { - // Found the parameter we are looking for consume white spaces - pos = consumeWhiteSpaces(pos + name.length); - if (pos >= end) { - break; - } - var paramHelpString = ""; - var firstLineParamHelpStringPos = pos; - while (pos < end) { - var ch = sourceFile.text.charCodeAt(pos); - // at line break, set this comment line text and go to next line - if (ts.isLineBreak(ch)) { - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - paramHelpString = ""; - blankLineCount = 0; - recordedParamTag = true; - } - else if (recordedParamTag) { - blankLineCount++; - } - // Get the pos after cleaning start of the line - setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); - continue; - } - // Done scanning param help string - next tag found - if (ch === 64 /* at */) { - break; - } - paramHelpString += sourceFile.text.charAt(pos); - // Go to next character - pos++; - } - // If there is param help text, add it top the doc comments - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - } - paramHelpStringMargin = undefined; - } - // If this is the start of another tag, continue with the loop in search of param tag with symbol name - if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { - continue; - } - } - // Next character - pos++; - } - return paramDocComments; - function consumeWhiteSpaces(pos) { - while (pos < end && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { - // Get the pos after consuming line breaks - pos = consumeLineBreaks(pos, end, sourceFile); - if (pos >= end) { - return; - } - if (paramHelpStringMargin === undefined) { - paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; - } - // Now consume white spaces max - var startOfLinePos = pos; - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); - if (pos >= end) { - return; - } - var consumedSpaces = pos - startOfLinePos; - if (consumedSpaces < paramHelpStringMargin) { - var ch = sourceFile.text.charCodeAt(pos); - if (ch === 42 /* asterisk */) { - // Consume more spaces after asterisk - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); - } - } - } - } + var TokenObject = (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + _super.call(this, pos, end); + this.kind = kind; } - } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(kind, pos, end) { + _super.call(this, pos, end); + } + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 69 /* Identifier */; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -52517,7 +72778,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (1024 /* Class */ | 2048 /* Interface */) + return this.flags & (32768 /* Class */ | 65536 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; @@ -52544,7 +72805,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? getJsDocCommentsFromDeclarations([this.declaration], + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], /*name*/ undefined, /*canUseParsedParamTagComments*/ false) : []; } @@ -52576,24 +72837,23 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { var name = getDeclarationName(declaration); if (name) { - var declarations = getDeclarations(name); - declarations.push(declaration); + ts.multiMapAdd(result, name, declaration); } } function getDeclarations(name) { - return ts.getProperty(result, name) || (result[name] = []); + return result[name] || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_2 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_2 !== undefined) { - return result_2; + var result_6 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_6 !== undefined) { + return result_6; } if (declaration.name.kind === 140 /* ComputedPropertyName */) { var expr = declaration.name.expression; @@ -52660,7 +72920,7 @@ var ts; break; case 142 /* Parameter */: // Only consider parameter properties - if (!(node.flags & 92 /* ParameterPropertyModifier */)) { + if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // fall through @@ -52714,207 +72974,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); - var TextChange = (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; - var HighlightSpanKind; - (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; - })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); - (function (IndentStyle) { - IndentStyle[IndentStyle["None"] = 0] = "None"; - IndentStyle[IndentStyle["Block"] = 1] = "Block"; - IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; - (function (SymbolDisplayPartKind) { - SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; - SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; - SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; - SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; - SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; - SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; - SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; - (function (OutputFileType) { - OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; - OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; - OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; - })(ts.OutputFileType || (ts.OutputFileType = {})); - var OutputFileType = ts.OutputFileType; - (function (EndOfLineState) { - EndOfLineState[EndOfLineState["None"] = 0] = "None"; - EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; - EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; - EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; - EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; - EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; - EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; - })(ts.EndOfLineState || (ts.EndOfLineState = {})); - var EndOfLineState = ts.EndOfLineState; - (function (TokenClass) { - TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; - TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; - TokenClass[TokenClass["Operator"] = 2] = "Operator"; - TokenClass[TokenClass["Comment"] = 3] = "Comment"; - TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; - TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; - TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; - // TODO: move these to enums - var ScriptElementKind; - (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; - /** predefined type (void) or keyword (class) */ - ScriptElementKind.keyword = "keyword"; - /** top level script node */ - ScriptElementKind.scriptElement = "script"; - /** module foo {} */ - ScriptElementKind.moduleElement = "module"; - /** class X {} */ - ScriptElementKind.classElement = "class"; - /** var x = class X {} */ - ScriptElementKind.localClassElement = "local class"; - /** interface Y {} */ - ScriptElementKind.interfaceElement = "interface"; - /** type T = ... */ - ScriptElementKind.typeElement = "type"; - /** enum E */ - ScriptElementKind.enumElement = "enum"; - /** - * Inside module and script only - * const v = .. - */ - ScriptElementKind.variableElement = "var"; - /** Inside function */ - ScriptElementKind.localVariableElement = "local var"; - /** - * Inside module and script only - * function f() { } - */ - ScriptElementKind.functionElement = "function"; - /** Inside function */ - ScriptElementKind.localFunctionElement = "local function"; - /** class X { [public|private]* foo() {} } */ - ScriptElementKind.memberFunctionElement = "method"; - /** class X { [public|private]* [get|set] foo:number; } */ - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; - /** - * class X { [public|private]* foo:number; } - * interface Y { foo:number; } - */ - ScriptElementKind.memberVariableElement = "property"; - /** class X { constructor() { } } */ - ScriptElementKind.constructorImplementationElement = "constructor"; - /** interface Y { ():number; } */ - ScriptElementKind.callSignatureElement = "call"; - /** interface Y { []:number; } */ - ScriptElementKind.indexSignatureElement = "index"; - /** interface Y { new():Y; } */ - ScriptElementKind.constructSignatureElement = "construct"; - /** function foo(*Y*: string) */ - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); - var ScriptElementKindModifier; - (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; - })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - return ClassificationTypeNames; - }()); - ts.ClassificationTypeNames = ClassificationTypeNames; - (function (ClassificationType) { - ClassificationType[ClassificationType["comment"] = 1] = "comment"; - ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; - ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; - ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; - ClassificationType[ClassificationType["operator"] = 5] = "operator"; - ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; - ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; - ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; - ClassificationType[ClassificationType["text"] = 9] = "text"; - ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; - ClassificationType[ClassificationType["className"] = 11] = "className"; - ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; - ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; - ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; - ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; - ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; - ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; - ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; - ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; - ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; - ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; - ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; - ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; - ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; - })(ts.ClassificationType || (ts.ClassificationType = {})); - var ClassificationType = ts.ClassificationType; + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; } + }; + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -52922,29 +72992,6 @@ var ts; return ""; } ts.displayPartsToString = displayPartsToString; - function isLocalVariableOrFunction(symbol) { - if (symbol.parent) { - return false; // This is exported symbol - } - return ts.forEach(symbol.declarations, function (declaration) { - // Function expressions are local - if (declaration.kind === 179 /* FunctionExpression */) { - return true; - } - if (declaration.kind !== 218 /* VariableDeclaration */ && declaration.kind !== 220 /* FunctionDeclaration */) { - return false; - } - // If the parent is not sourceFile or module block it is local variable - for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { - // Reached source file or module block - if (parent_16.kind === 256 /* SourceFile */ || parent_16.kind === 226 /* ModuleBlock */) { - return false; - } - } - // parent is in function block - return true; - }); - } function getDefaultCompilerOptions() { // Always default to "ScriptTarget.ES5" for the language service return { @@ -52953,7 +73000,7 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about scrip Should be refreshed + // Cache host information about script should be refreshed // at each language service public entry point, since we don't know when // set of scripts handled by the host changes. var HostCache = (function () { @@ -53060,126 +73107,6 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptionsStringToEnum; - /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ - function fixupCompilerOptions(options, diagnostics) { - // Lazily create this value to fix module loading errors. - commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { - return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); - }); - options = ts.clone(options); - var _loop_3 = function(opt) { - if (!ts.hasProperty(options, opt.name)) { - return "continue"; - } - var value = options[opt.name]; - // Value should be a key of opt.type - if (typeof value === "string") { - // If value is not a string, this will fail - options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); - } - else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { - // Supplied value isn't a valid enum value. - diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); - } - } - }; - for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { - var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_3(opt); - } - return options; - } - /* - * This function will compile source text from 'input' argument using specified compiler options. - * If not options are provided - it will use a set of default compiler options. - * Extra compiler options that will unconditionally be used by this function are: - * - isolatedModules = true - * - allowNonTsExtensions = true - * - noLib = true - * - noResolve = true - */ - function transpileModule(input, transpileOptions) { - var diagnostics = []; - var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : getDefaultCompilerOptions(); - options.isolatedModules = true; - // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. - options.suppressOutputPathCheck = true; - // Filename can be non-ts file. - options.allowNonTsExtensions = true; - // We are not returning a sourceFile for lib file when asked by the program, - // so pass --noLib to avoid reporting a file not found error. - options.noLib = true; - // Clear out other settings that would not be used in transpiling this module - options.lib = undefined; - options.types = undefined; - options.noEmit = undefined; - options.noEmitOnError = undefined; - options.paths = undefined; - options.rootDirs = undefined; - options.declaration = undefined; - options.declarationDir = undefined; - options.out = undefined; - options.outFile = undefined; - // We are not doing a full typecheck, we are not resolving the whole context, - // so pass --noResolve to avoid reporting missing file errors. - options.noResolve = true; - // if jsx is specified then treat file as .tsx - var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); - if (transpileOptions.moduleName) { - sourceFile.moduleName = transpileOptions.moduleName; - } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; - var newLine = ts.getNewLineCharacter(options); - // Output - var outputText; - var sourceMapText; - // Create a compilerHost object to allow the compiler to read and write files - var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { - if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); - sourceMapText = text; - } - else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); - outputText = text; - } - }, - getDefaultLibFileName: function () { return "lib.d.ts"; }, - useCaseSensitiveFileNames: function () { return false; }, - getCanonicalFileName: function (fileName) { return fileName; }, - getCurrentDirectory: function () { return ""; }, - getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } - }; - var program = ts.createProgram([inputFileName], options, compilerHost); - if (transpileOptions.reportDiagnostics) { - ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); - ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); - } - // Emit - program.emit(); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); - return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; - } - ts.transpileModule = transpileModule; - /* - * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. - */ - function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { - var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); - // addRange correctly handles cases when wither 'from' or 'to' argument is missing - ts.addRange(diagnostics, output.diagnostics); - return output.outputText; - } - ts.transpile = transpile; function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); @@ -53238,681 +73165,6 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have - // for those settings. - var buckets = {}; - var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = ts.lookUp(buckets, key); - if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(); - } - return bucket; - } - function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { - var entries = ts.lookUp(buckets, name); - var sourceFiles = []; - entries.forEachValue(function (key, entry) { - sourceFiles.push({ - name: key, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) - }); - }); - sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); - return { - bucket: name, - sourceFiles: sourceFiles - }; - }); - return JSON.stringify(bucketInfoArray, undefined, 2); - } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); - } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); - } - function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); - var entry = bucket.get(path); - if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); - // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); - entry = { - sourceFile: sourceFile, - languageServiceRefCount: 0, - owners: [] - }; - bucket.set(path, entry); - } - else { - // We have an entry for this file. However, it may be for a different version of - // the script snapshot. If so, update it appropriately. Otherwise, we can just - // return it as is. - if (entry.sourceFile.version !== version) { - entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); - } - } - // If we're acquiring, then this is the first time this LS is asking for this document. - // Increase our ref count so we know there's another LS using the document. If we're - // not acquiring, then that means the LS is 'updating' the file instead, and that means - // it has already acquired the document previously. As such, we do not need to increase - // the ref count. - if (acquiring) { - entry.languageServiceRefCount++; - } - return entry.sourceFile; - } - function releaseDocument(fileName, compilationSettings) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); - } - function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(path); - entry.languageServiceRefCount--; - ts.Debug.assert(entry.languageServiceRefCount >= 0); - if (entry.languageServiceRefCount === 0) { - bucket.remove(path); - } - } - return { - acquireDocument: acquireDocument, - acquireDocumentWithKey: acquireDocumentWithKey, - updateDocument: updateDocument, - updateDocumentWithKey: updateDocumentWithKey, - releaseDocument: releaseDocument, - releaseDocumentWithKey: releaseDocumentWithKey, - reportStats: reportStats, - getKeyForCompilationSettings: getKeyForCompilationSettings - }; - } - ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { - if (readImportFiles === void 0) { readImportFiles = true; } - if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; - var importedFiles = []; - var ambientExternalModules; - var isNoDefaultLib = false; - var braceNesting = 0; - // assume that text represent an external module if it contains at least one top level import/export - // ambient modules that are found inside external modules are interpreted as module augmentations - var externalModule = false; - function nextToken() { - var token = scanner.scan(); - if (token === 15 /* OpenBraceToken */) { - braceNesting++; - } - else if (token === 16 /* CloseBraceToken */) { - braceNesting--; - } - return token; - } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } - function getFileReference() { - var file = scanner.getTokenValue(); - var pos = scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; - } - function recordAmbientExternalModule() { - if (!ambientExternalModules) { - ambientExternalModules = []; - } - ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); - } - function recordModuleName() { - importedFiles.push(getFileReference()); - markAsExternalModuleIfTopLevel(); - } - function markAsExternalModuleIfTopLevel() { - if (braceNesting === 0) { - externalModule = true; - } - } - /** - * Returns true if at least one token was consumed from the stream - */ - function tryConsumeDeclare() { - var token = scanner.getToken(); - if (token === 122 /* DeclareKeyword */) { - // declare module "mod" - token = nextToken(); - if (token === 125 /* ModuleKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - recordAmbientExternalModule(); - } - } - return true; - } - return false; - } - /** - * Returns true if at least one token was consumed from the stream - */ - function tryConsumeImport() { - var token = scanner.getToken(); - if (token === 89 /* ImportKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import "mod"; - recordModuleName(); - return true; - } - else { - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import d from "mod"; - recordModuleName(); - return true; - } - } - else if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { - return true; - } - } - else if (token === 24 /* CommaToken */) { - // consume comma and keep going - token = nextToken(); - } - else { - // unknown syntax - return true; - } - } - if (token === 15 /* OpenBraceToken */) { - token = nextToken(); - // consume "{ a as B, c, d as D}" clauses - // make sure that it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { - token = nextToken(); - } - if (token === 16 /* CloseBraceToken */) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import {a as A} from "mod"; - // import d, {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = nextToken(); - if (token === 116 /* AsKeyword */) { - token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import * as NS from "mod" - // import d, * as NS from "mod" - recordModuleName(); - } - } - } - } - } - } - return true; - } - return false; - } - function tryConsumeExport() { - var token = scanner.getToken(); - if (token === 82 /* ExportKeyword */) { - markAsExternalModuleIfTopLevel(); - token = nextToken(); - if (token === 15 /* OpenBraceToken */) { - token = nextToken(); - // consume "{ a as B, c, d as D}" clauses - // make sure it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { - token = nextToken(); - } - if (token === 16 /* CloseBraceToken */) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // export {a as A} from "mod"; - // export {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // export * from "mod" - recordModuleName(); - } - } - } - else if (token === 89 /* ImportKeyword */) { - token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = nextToken(); - if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { - return true; - } - } - } - } - return true; - } - return false; - } - function tryConsumeRequireCall(skipCurrentToken) { - var token = skipCurrentToken ? nextToken() : scanner.getToken(); - if (token === 129 /* RequireKeyword */) { - token = nextToken(); - if (token === 17 /* OpenParenToken */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // require("mod"); - recordModuleName(); - } - } - return true; - } - return false; - } - function tryConsumeDefine() { - var token = scanner.getToken(); - if (token === 69 /* Identifier */ && scanner.getTokenValue() === "define") { - token = nextToken(); - if (token !== 17 /* OpenParenToken */) { - return true; - } - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // looks like define ("modname", ... - skip string literal and comma - token = nextToken(); - if (token === 24 /* CommaToken */) { - token = nextToken(); - } - else { - // unexpected token - return true; - } - } - // should be start of dependency list - if (token !== 19 /* OpenBracketToken */) { - return true; - } - // skip open bracket - token = nextToken(); - var i = 0; - // scan until ']' or EOF - while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { - // record string literals as module names - if (token === 9 /* StringLiteral */) { - recordModuleName(); - i++; - } - token = nextToken(); - } - return true; - } - return false; - } - function processImports() { - scanner.setText(sourceText); - nextToken(); - // Look for: - // import "mod"; - // import d from "mod" - // import {a as A } from "mod"; - // import * as NS from "mod" - // import d, {a, b as B} from "mod" - // import i = require("mod"); - // - // export * from "mod" - // export {a as b} from "mod" - // export import i = require("mod") - // (for JavaScript files) require("mod") - while (true) { - if (scanner.getToken() === 1 /* EndOfFileToken */) { - break; - } - // check if at least one of alternative have moved scanner forward - if (tryConsumeDeclare() || - tryConsumeImport() || - tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { - continue; - } - else { - nextToken(); - } - } - scanner.setText(undefined); - } - if (readImportFiles) { - processImports(); - } - processTripleSlashDirectives(); - if (externalModule) { - // for external modules module all nested ambient modules are augmentations - if (ambientExternalModules) { - // move all detected ambient modules to imported files since they need to be resolved - for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { - var decl = ambientExternalModules_1[_i]; - importedFiles.push(decl.ref); - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; - } - else { - // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 - var ambientModuleNames = void 0; - if (ambientExternalModules) { - for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { - var decl = ambientExternalModules_2[_a]; - if (decl.depth === 0) { - if (!ambientModuleNames) { - ambientModuleNames = []; - } - ambientModuleNames.push(decl.ref.fileName); - } - else { - importedFiles.push(decl.ref); - } - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; - } - } - ts.preProcessFile = preProcessFile; - /// Helpers - function getTargetLabel(referenceNode, labelName) { - while (referenceNode) { - if (referenceNode.kind === 214 /* LabeledStatement */ && referenceNode.label.text === labelName) { - return referenceNode.label; - } - referenceNode = referenceNode.parent; - } - return undefined; - } - function isJumpStatementTarget(node) { - return node.kind === 69 /* Identifier */ && - (node.parent.kind === 210 /* BreakStatement */ || node.parent.kind === 209 /* ContinueStatement */) && - node.parent.label === node; - } - function isLabelOfLabeledStatement(node) { - return node.kind === 69 /* Identifier */ && - node.parent.kind === 214 /* LabeledStatement */ && - node.parent.label === node; - } - /** - * Whether or not a 'node' is preceded by a label of the given string. - * Note: 'node' cannot be a SourceFile. - */ - function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214 /* LabeledStatement */; owner = owner.parent) { - if (owner.label.text === labelName) { - return true; - } - } - return false; - } - function isLabelName(node) { - return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); - } - function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node; - } - function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node; - } - function isCallExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; - } - function isNewExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 175 /* NewExpression */ && node.parent.expression === node; - } - function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 /* ModuleDeclaration */ && node.parent.name === node; - } - function isNameOfFunctionDeclaration(node) { - return node.kind === 69 /* Identifier */ && - ts.isFunctionLike(node.parent) && node.parent.name === node; - } - function isObjectLiteralPropertyDeclaration(node) { - switch (node.kind) { - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return true; - } - return false; - } - /** - * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } - */ - function getContainingObjectLiteralElement(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - if (node.parent.kind === 140 /* ComputedPropertyName */) { - return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; - } - // intential fall through - case 69 /* Identifier */: - return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; - } - return undefined; - } - function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { - switch (node.parent.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 225 /* ModuleDeclaration */: - return node.parent.name === node; - case 173 /* ElementAccessExpression */: - return node.parent.argumentExpression === node; - case 140 /* ComputedPropertyName */: - return true; - } - } - return false; - } - function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9 /* StringLiteral */) { - return isNameOfModuleDeclaration(node) || - (ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node); - } - return false; - } - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - var SemanticMeaning; - (function (SemanticMeaning) { - SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; - SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; - SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; - SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; - SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; - })(SemanticMeaning || (SemanticMeaning = {})); - var BreakContinueSearchType; - (function (BreakContinueSearchType) { - BreakContinueSearchType[BreakContinueSearchType["None"] = 0] = "None"; - BreakContinueSearchType[BreakContinueSearchType["Unlabeled"] = 1] = "Unlabeled"; - BreakContinueSearchType[BreakContinueSearchType["Labeled"] = 2] = "Labeled"; - BreakContinueSearchType[BreakContinueSearchType["All"] = 3] = "All"; - })(BreakContinueSearchType || (BreakContinueSearchType = {})); - // A cache of completion entries for keywords, these do not change between sessions - var keywordCompletions = []; - for (var i = 70 /* FirstKeyword */; i <= 138 /* LastKeyword */; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - sortText: "0" - }); - } - /* @internal */ function getContainerNode(node) { - while (true) { - node = node.parent; - if (!node) { - return undefined; - } - switch (node.kind) { - case 256 /* SourceFile */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: - return node; - } - } - } - ts.getContainerNode = getContainerNode; - /* @internal */ function getNodeKind(node) { - switch (node.kind) { - case 225 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - return ScriptElementKind.classElement; - case 222 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 223 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 224 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 218 /* VariableDeclaration */: - return ts.isConst(node) - ? ScriptElementKind.constElement - : ts.isLet(node) - ? ScriptElementKind.letElement - : ScriptElementKind.variableElement; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - return ScriptElementKind.functionElement; - case 149 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return ScriptElementKind.memberFunctionElement; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return ScriptElementKind.memberVariableElement; - case 153 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; - case 152 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; - case 151 /* CallSignature */: return ScriptElementKind.callSignatureElement; - case 148 /* Constructor */: return ScriptElementKind.constructorImplementationElement; - case 141 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 255 /* EnumMember */: return ScriptElementKind.variableElement; - case 142 /* Parameter */: return (node.flags & 92 /* ParameterPropertyModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 231 /* ImportClause */: - case 238 /* ExportSpecifier */: - case 232 /* NamespaceImport */: - return ScriptElementKind.alias; - } - return ScriptElementKind.unknown; - } - ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { function CancellationTokenObject(cancellationToken) { this.cancellationToken = cancellationToken; @@ -53928,7 +73180,7 @@ var ts; return CancellationTokenObject; }()); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; @@ -53985,14 +73237,16 @@ var ts; // incremental parsing. var oldSettings = program && program.getCompilerOptions(); var newSettings = hostCache.compilationSettings(); - var changesInCompilationSettingsAffectSyntax = oldSettings && + var shouldCreateNewSourceFiles = oldSettings && (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.baseUrl !== newSettings.baseUrl || + !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -54006,7 +73260,6 @@ var ts; getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return hostCache.getOrCreateEntry(fileName) !== undefined; }, readFile: function (fileName) { @@ -54041,7 +73294,7 @@ var ts; var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } } @@ -54069,7 +73322,7 @@ var ts; // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. - if (!changesInCompilationSettingsAffectSyntax) { + if (!shouldCreateNewSourceFiles) { // Check if the old program had this file already var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { @@ -54172,1455 +73425,17 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module otherwise a name with striped of any quote - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { - // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) - return undefined; - } - } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { - return undefined; - } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks) { - if (!ts.isIdentifier(name, target)) { - return undefined; - } - } - return name; - } - function getCompletionData(fileName, position) { - var typeChecker = program.getTypeChecker(); - var sourceFile = getValidSourceFile(fileName); - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - var isJsDocTagName = false; - var start = new Date().getTime(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); - // Completion not allowed inside comments, bail out if this is the case - var insideComment = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); - if (insideComment) { - // The current position is next to the '@' sign, when no tag name being provided yet. - // Provide a full list of tag names - if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { - isJsDocTagName = true; - } - // Completion should work inside certain JsDoc tags. For example: - // /** @type {number | string} */ - // Completion should work in the brackets - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); - if (tag) { - if (tag.tagName.pos <= position && position <= tag.tagName.end) { - isJsDocTagName = true; - } - switch (tag.kind) { - case 277 /* JSDocTypeTag */: - case 275 /* JSDocParameterTag */: - case 276 /* JSDocReturnTag */: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; - } - } - if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; - } - if (!insideJsDocTagExpression) { - // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal - // comment or the plain text part of a jsDoc comment, so no completion should be available - log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); - return undefined; - } - } - start = new Date().getTime(); - var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); - // The decision to provide completion depends on the contextToken, which is determined through the previousToken. - // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file - var contextToken = previousToken; - // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| - // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_5 = new Date().getTime(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); - } - // Find the node where completion is requested on. - // Also determine whether we are trying to complete with members of that node - // or attributes of a JSX tag. - var node = currentToken; - var isRightOfDot = false; - var isRightOfOpenTag = false; - var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); - if (contextToken) { - // Bail out if this is a known invalid completion location - if (isCompletionListBlocker(contextToken)) { - log("Returning an empty list because completion was requested in an invalid position."); - return undefined; - } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21 /* DotToken */) { - if (parent_17.kind === 172 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent_17.kind === 139 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; - } - } - else if (sourceFile.languageVariant === 1 /* JSX */) { - if (kind === 25 /* LessThanToken */) { - isRightOfOpenTag = true; - location = contextToken; - } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 245 /* JsxClosingElement */) { - isStartingCloseTag = true; - location = contextToken; - } - } - } - var semanticStart = new Date().getTime(); - var isMemberCompletion; - var isNewIdentifierLocation; - var symbols = []; - if (isRightOfDot) { - getTypeScriptMemberSymbols(); - } - else if (isRightOfOpenTag) { - var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); - if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 8388608 /* Alias */)); })); - } - else { - symbols = tagSymbols; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else if (isStartingCloseTag) { - var tagName = contextToken.parent.parent.openingElement.tagName; - var tagSymbol = typeChecker.getSymbolAtLocation(tagName); - if (!typeChecker.isUnknownSymbol(tagSymbol)) { - symbols = [tagSymbol]; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else { - // For JavaScript or TypeScript, if we're not after a dot, then just try to get the - // global symbols in scope. These results should be valid for either language as - // the set of symbols that can be referenced from this location. - if (!tryGetGlobalSymbols()) { - return undefined; - } - } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; - function getTypeScriptMemberSymbols() { - // Right of dot member completion list - isMemberCompletion = true; - isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { - var symbol = typeChecker.getSymbolAtLocation(node); - // This is an alias, follow what it aliases - if (symbol && symbol.flags & 8388608 /* Alias */) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952 /* HasExports */) { - // Extract module or enum members - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - }); - } - } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); - } - function addTypeProperties(type) { - if (type) { - // Filter private properties - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - } - if (isJavaScriptFile && type.flags & 16384 /* Union */) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } - } - } - } - function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - return tryGetObjectLikeCompletionSymbols(objectLikeContainer); - } - if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { - // cursor is in an import clause - // try to show exported member for imported module - return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); - } - if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType = void 0; - if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { - // Cursor is inside a JSX self-closing element or opening element - attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); - if (attrsType) { - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); - isMemberCompletion = true; - isNewIdentifierLocation = false; - return true; - } - } - } - // Get all entities in the current scope. - isMemberCompletion = false; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); - if (previousToken !== contextToken) { - ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); - } - // We need to find the node that will give us an appropriate scope to begin - // aggregating completion candidates. This is achieved in 'getScopeNode' - // by finding the first node that encompasses a position, accounting for whether a node - // is "complete" to decide whether a position belongs to the node. - // - // However, at the end of an identifier, we are interested in the scope of the identifier - // itself, but fall outside of the identifier. For instance: - // - // xyz => x$ - // - // the cursor is outside of both the 'x' and the arrow function 'xyz => x', - // so 'xyz' is not returned in our results. - // - // We define 'adjustedPosition' so that we may appropriately account for - // being at the end of an identifier. The intention is that if requesting completion - // at the end of an identifier, it should be effectively equivalent to requesting completion - // anywhere inside/at the beginning of the identifier. So in the previous case, the - // 'adjustedPosition' will work as if requesting completion in the following: - // - // xyz => $x - // - // If previousToken !== contextToken, then - // - 'contextToken' was adjusted to the token prior to 'previousToken' - // because we were at the end of an identifier. - // - 'previousToken' is defined. - var adjustedPosition = previousToken !== contextToken ? - previousToken.getStart() : - position; - var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - /// TODO filter meaning based on the current context - var symbolMeanings = 793056 /* Type */ | 107455 /* Value */ | 1536 /* Namespace */ | 8388608 /* Alias */; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); - return true; - } - /** - * Finds the first node that "embraces" the position, so that one may - * accurately aggregate locals from the closest containing scope. - */ - function getScopeNode(initialToken, position, sourceFile) { - var scope = initialToken; - while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { - scope = scope.parent; - } - return scope; - } - function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); - var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || - isSolelyIdentifierDefinitionLocation(contextToken) || - isDotOfNumericLiteral(contextToken) || - isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); - return result; - } - function isInJsxText(contextToken) { - if (contextToken.kind === 244 /* JsxText */) { - return true; - } - if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 243 /* JsxOpeningElement */) { - return true; - } - if (contextToken.parent.kind === 245 /* JsxClosingElement */ || contextToken.parent.kind === 242 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241 /* JsxElement */; - } - } - return false; - } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 174 /* CallExpression */ // func( a, | - || containingNodeKind === 148 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 175 /* NewExpression */ // new C(a, | - || containingNodeKind === 170 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 187 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 156 /* FunctionType */; // var x: (s: string, list| - case 17 /* OpenParenToken */: - return containingNodeKind === 174 /* CallExpression */ // func( | - || containingNodeKind === 148 /* Constructor */ // constructor( | - || containingNodeKind === 175 /* NewExpression */ // new C(a| - || containingNodeKind === 178 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 164 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 19 /* OpenBracketToken */: - return containingNodeKind === 170 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 153 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 140 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 125 /* ModuleKeyword */: // module | - case 126 /* NamespaceKeyword */: - return true; - case 21 /* DotToken */: - return containingNodeKind === 225 /* ModuleDeclaration */; // module A.| - case 15 /* OpenBraceToken */: - return containingNodeKind === 221 /* ClassDeclaration */; // class A{ | - case 56 /* EqualsToken */: - return containingNodeKind === 218 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 187 /* BinaryExpression */; // x = a| - case 12 /* TemplateHead */: - return containingNodeKind === 189 /* TemplateExpression */; // `aa ${| - case 13 /* TemplateMiddle */: - return containingNodeKind === 197 /* TemplateSpan */; // `aa ${10} dd ${| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; // class A{ public | - } - // Previous token may have been a keyword that was converted to an identifier. - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": - return true; - } - } - return false; - } - function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { - if (contextToken.kind === 9 /* StringLiteral */ - || contextToken.kind === 166 /* StringLiteralType */ - || contextToken.kind === 10 /* RegularExpressionLiteral */ - || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_6 = contextToken.getStart(); - var end = contextToken.getEnd(); - // To be "in" one of these literals, the position has to be: - // 1. entirely within the token text. - // 2. at the end position of an unterminated token. - // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_6 < position && position < end) { - return true; - } - if (position === end) { - return !!contextToken.isUnterminated - || contextToken.kind === 10 /* RegularExpressionLiteral */; - } - } - return false; - } - /** - * Aggregates relevant symbols for completion in object literals and object binding patterns. - * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. - */ - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { - // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - var typeForObject; - var existingMembers; - if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { - // We are completing on contextual types, but may also include properties - // other than those within the declared type. - isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - existingMembers = objectLikeContainer.properties; - } - else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { - // We are *only* completing on properties from the type being destructured. - isNewIdentifierLocation = false; - var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - // We don't want to complete using the type acquired by the shape - // of the binding pattern; we are only interested in types acquired - // through type declaration or inference. - // Also proceed if rootDeclaration is parameter and if its containing function expression\arrow function is contextually typed - - // type of parameter will flow in from the contextual type of the function - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } - } - if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - existingMembers = objectLikeContainer.elements; - } - } - else { - ts.Debug.fail("Root declaration is not variable-like."); - } - } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); - if (typeMembers && typeMembers.length > 0) { - // Add filtered items to the completion list - symbols = filterObjectMembersList(typeMembers, existingMembers); - } - return true; - } - /** - * Aggregates relevant symbols for completion in import clauses and export clauses - * whose declarations have a module specifier; for instance, symbols will be aggregated for - * - * import { | } from "moduleName"; - * export { a as foo, | } from "moduleName"; - * - * but not for - * - * export { | }; - * - * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. - */ - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 /* NamedImports */ ? - 230 /* ImportDeclaration */ : - 236 /* ExportDeclaration */; - var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); - var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; - if (!moduleSpecifier) { - return false; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - var exports; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); - if (moduleSpecifierSymbol) { - exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); - } - symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; - return true; - } - /** - * Returns the immediate owning object literal or binding pattern of a context token, - * on the condition that one exists and that the context implies completion should be given. - */ - function tryGetObjectLikeCompletionContainer(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // const x = { | - case 24 /* CommaToken */: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 /* ObjectLiteralExpression */ || parent_18.kind === 167 /* ObjectBindingPattern */)) { - return parent_18; - } - break; - } - } - return undefined; - } - /** - * Returns the containing list of named imports or exports of a context token, - * on the condition that one exists and that the context implies completion should be given. - */ - function tryGetNamedImportsOrExportsForCompletion(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // import { | - case 24 /* CommaToken */: - switch (contextToken.parent.kind) { - case 233 /* NamedImports */: - case 237 /* NamedExports */: - return contextToken.parent; - } - } - } - return undefined; - } - function tryGetContainingJsxElement(contextToken) { - if (contextToken) { - var parent_19 = contextToken.parent; - switch (contextToken.kind) { - case 26 /* LessThanSlashToken */: - case 39 /* SlashToken */: - case 69 /* Identifier */: - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: - if (parent_19 && (parent_19.kind === 242 /* JsxSelfClosingElement */ || parent_19.kind === 243 /* JsxOpeningElement */)) { - return parent_19; - } - else if (parent_19.kind === 246 /* JsxAttribute */) { - return parent_19.parent; - } - break; - // The context token is the closing } or " of an attribute, which means - // its parent is a JsxExpression, whose parent is a JsxAttribute, - // whose parent is a JsxOpeningLikeElement - case 9 /* StringLiteral */: - if (parent_19 && ((parent_19.kind === 246 /* JsxAttribute */) || (parent_19.kind === 247 /* JsxSpreadAttribute */))) { - return parent_19.parent; - } - break; - case 16 /* CloseBraceToken */: - if (parent_19 && - parent_19.kind === 248 /* JsxExpression */ && - parent_19.parent && - (parent_19.parent.kind === 246 /* JsxAttribute */)) { - return parent_19.parent.parent; - } - if (parent_19 && parent_19.kind === 247 /* JsxSpreadAttribute */) { - return parent_19.parent; - } - break; - } - } - return undefined; - } - function isFunction(kind) { - switch (kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - return true; - } - return false; - } - /** - * @returns true if we are certain that the currently edited location must define a new location; false otherwise. - */ - function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; - switch (contextToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 218 /* VariableDeclaration */ || - containingNodeKind === 219 /* VariableDeclarationList */ || - containingNodeKind === 200 /* VariableStatement */ || - containingNodeKind === 224 /* EnumDeclaration */ || - isFunction(containingNodeKind) || - containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 168 /* ArrayBindingPattern */ || - containingNodeKind === 223 /* TypeAliasDeclaration */; // type Map, K, | - case 21 /* DotToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [.| - case 54 /* ColonToken */: - return containingNodeKind === 169 /* BindingElement */; // var {x :html| - case 19 /* OpenBracketToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [x| - case 17 /* OpenParenToken */: - return containingNodeKind === 252 /* CatchClause */ || - isFunction(containingNodeKind); - case 15 /* OpenBraceToken */: - return containingNodeKind === 224 /* EnumDeclaration */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 159 /* TypeLiteral */; // const x : { | - case 23 /* SemicolonToken */: - return containingNodeKind === 144 /* PropertySignature */ && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 159 /* TypeLiteral */); // const x : { a; | - case 25 /* LessThanToken */: - return containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 223 /* TypeAliasDeclaration */ || - isFunction(containingNodeKind); - case 113 /* StaticKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; - case 22 /* DotDotDotToken */: - return containingNodeKind === 142 /* Parameter */ || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168 /* ArrayBindingPattern */); // var [...z| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 142 /* Parameter */; - case 116 /* AsKeyword */: - return containingNodeKind === 234 /* ImportSpecifier */ || - containingNodeKind === 238 /* ExportSpecifier */ || - containingNodeKind === 232 /* NamespaceImport */; - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: - case 107 /* InterfaceKeyword */: - case 87 /* FunctionKeyword */: - case 102 /* VarKeyword */: - case 123 /* GetKeyword */: - case 131 /* SetKeyword */: - case 89 /* ImportKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - case 114 /* YieldKeyword */: - case 134 /* TypeKeyword */: - return true; - } - // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": - return true; - } - return false; - } - function isDotOfNumericLiteral(contextToken) { - if (contextToken.kind === 8 /* NumericLiteral */) { - var text = contextToken.getFullText(); - return text.charAt(text.length - 1) === "."; - } - return false; - } - /** - * Filters out completion suggestions for named imports or exports. - * - * @param exportsOfModule The list of symbols which a module exposes. - * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. - * - * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports - * do not occur at the current position and have not otherwise been typed. - */ - function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; - for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { - var element = namedImportsOrExports_1[_i]; - // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { - continue; - } - var name_41 = element.propertyName || element.name; - existingImportsOrExports[name_41.text] = true; - } - if (ts.isEmpty(existingImportsOrExports)) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); - } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !ts.lookUp(existingImportsOrExports, e.name); }); - } - /** - * Filters out completion suggestions for named imports or exports. - * - * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations - * do not occur at the current position and have not otherwise been typed. - */ - function filterObjectMembersList(contextualMemberSymbols, existingMembers) { - if (!existingMembers || existingMembers.length === 0) { - return contextualMemberSymbols; - } - var existingMemberNames = {}; - for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { - var m = existingMembers_1[_i]; - // Ignore omitted expressions for missing members - if (m.kind !== 253 /* PropertyAssignment */ && - m.kind !== 254 /* ShorthandPropertyAssignment */ && - m.kind !== 169 /* BindingElement */ && - m.kind !== 147 /* MethodDeclaration */) { - continue; - } - // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { - continue; - } - var existingName = void 0; - if (m.kind === 169 /* BindingElement */ && m.propertyName) { - // include only identifiers in completion list - if (m.propertyName.kind === 69 /* Identifier */) { - existingName = m.propertyName.text; - } - } - else { - // TODO(jfreeman): Account for computed property name - // NOTE: if one only performs this step when m.name is an identifier, - // things like '__proto__' are not filtered out. - existingName = m.name.text; - } - existingMemberNames[existingName] = true; - } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); - } - /** - * Filters out completion suggestions from 'symbols' according to existing JSX attributes. - * - * @returns Symbols to be suggested in a JSX element, barring those whose attributes - * do not occur at the current position and have not otherwise been typed. - */ - function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; - for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { - var attr = attributes_1[_i]; - // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { - continue; - } - if (attr.kind === 246 /* JsxAttribute */) { - seenNames[attr.name.text] = true; - } - } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); - } - } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position); - } - var completionData = getCompletionData(fileName, position); - if (!completionData) { - return undefined; - } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; - if (isJsDocTagName) { - // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; - } - var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); - } - else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 /* JSX */ && - location.parent && location.parent.kind === 245 /* JsxClosingElement */) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
completion list at "1" will contain "div" with type any - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0" - }); - } - else { - return undefined; - } - } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); - } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !isJsDocTagName) { - ts.addRange(entries, keywordCompletions); - } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { - var entries = []; - var target = program.getCompilerOptions().target; - var nameTable = getNameTable(sourceFile); - for (var name_42 in nameTable) { - // Skip identifiers produced only from the current location - if (nameTable[name_42] === position) { - continue; - } - if (!uniqueNames[name_42]) { - uniqueNames[name_42] = name_42; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, /*performCharacterChecks*/ true); - if (displayName) { - var entry = { - name: displayName, - kind: ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } - } - } - return entries; - } - function getAllJsDocCompletionEntries() { - return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { - return { - name: tagName, - kind: ScriptElementKind.keyword, - kindModifiers: "", - sortText: "0" - }; - })); - } - function createCompletionEntry(symbol, location, performCharacterChecks) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, performCharacterChecks, location); - if (!displayName) { - return undefined; - } - // TODO(drosen): Right now we just permit *all* semantic meanings when calling - // 'getSymbolKind' which is permissible given that it is backwards compatible; but - // really we should consider passing the meaning for the node so that we don't report - // that a suggestion for a value is an interface. We COULD also just do what - // 'getSymbolModifiers' does, which is to use the first declaration. - // Use a 'sortText' of 0' so that all symbol completion entries come before any other - // entries (like JavaScript identifier entries). - return { - name: displayName, - kind: getSymbolKind(symbol, location), - kindModifiers: getSymbolModifiers(symbol), - sortText: "0" - }; - } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; - if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks); - if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(uniqueNames, id)) { - entries.push(entry); - uniqueNames[id] = id; - } - } - } - } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return uniqueNames; - } - function getStringLiteralCompletionEntries(sourceFile, position) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9 /* StringLiteral */) { - return undefined; - } - var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - return getStringLiteralCompletionEntriesFromElementAccess(node.parent); - } - else { - // Otherwise, get the completions from the contextual type if one exists - return getStringLiteralCompletionEntriesFromContextualType(node); - } - } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { - var typeChecker = program.getTypeChecker(); - var candidates = []; - var entries = []; - typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); - for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { - var candidate = candidates_3[_i]; - if (candidate.parameters.length > argumentInfo.argumentIndex) { - var parameter = candidate.parameters[argumentInfo.argumentIndex]; - addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); - } - } - if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; - } - return undefined; - } - function getStringLiteralCompletionEntriesFromElementAccess(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getTypeAtLocation(node.expression); - var entries = []; - if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); - if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; - } - } - return undefined; - } - function getStringLiteralCompletionEntriesFromContextualType(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getContextualType(node); - if (type) { - var entries_2 = []; - addStringLiteralCompletionsFromType(type, entries_2); - if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; - } - } - return undefined; - } - function addStringLiteralCompletionsFromType(type, result) { - if (!type) { - return; - } - if (type.flags & 16384 /* Union */) { - ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); - } - else { - if (type.flags & 256 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ScriptElementKindModifier.none, - kind: ScriptElementKind.variableElement, - sortText: "0" - }); - } - } - } + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); - // Compute all the completion symbols again. - var completionData = getCompletionData(fileName, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - // Find the symbol with the matching entry name. - var target_2 = program.getCompilerOptions().target; - // We don't need to perform character checks here because we're only comparing the - // name against 'entryName' (which is known to be good), not building a new - // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); - if (symbol) { - var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; - return { - name: entryName, - kindModifiers: getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation - }; - } - } - // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - displayParts: [ts.displayPart(entryName, SymbolDisplayPartKind.keyword)], - documentation: undefined - }; - } - return undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } - // TODO(drosen): use contextual SemanticMeaning. - function getSymbolKind(symbol, location) { - var flags = symbol.getFlags(); - if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */) ? - ScriptElementKind.localClassElement : ScriptElementKind.classElement; - if (flags & 384 /* Enum */) - return ScriptElementKind.enumElement; - if (flags & 524288 /* TypeAlias */) - return ScriptElementKind.typeElement; - if (flags & 64 /* Interface */) - return ScriptElementKind.interfaceElement; - if (flags & 262144 /* TypeParameter */) - return ScriptElementKind.typeParameterElement; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location); - if (result === ScriptElementKind.unknown) { - if (flags & 262144 /* TypeParameter */) - return ScriptElementKind.typeParameterElement; - if (flags & 8 /* EnumMember */) - return ScriptElementKind.variableElement; - if (flags & 8388608 /* Alias */) - return ScriptElementKind.alias; - if (flags & 1536 /* Module */) - return ScriptElementKind.moduleElement; - } - return result; - } - function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location) { - var typeChecker = program.getTypeChecker(); - if (typeChecker.isUndefinedSymbol(symbol)) { - return ScriptElementKind.variableElement; - } - if (typeChecker.isArgumentsSymbol(symbol)) { - return ScriptElementKind.localVariableElement; - } - if (location.kind === 97 /* ThisKeyword */ && ts.isExpression(location)) { - return ScriptElementKind.parameterElement; - } - if (flags & 3 /* Variable */) { - if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ScriptElementKind.parameterElement; - } - else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ScriptElementKind.constElement; - } - else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ScriptElementKind.letElement; - } - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement; - } - if (flags & 16 /* Function */) - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localFunctionElement : ScriptElementKind.functionElement; - if (flags & 32768 /* GetAccessor */) - return ScriptElementKind.memberGetAccessorElement; - if (flags & 65536 /* SetAccessor */) - return ScriptElementKind.memberSetAccessorElement; - if (flags & 8192 /* Method */) - return ScriptElementKind.memberFunctionElement; - if (flags & 16384 /* Constructor */) - return ScriptElementKind.constructorImplementationElement; - if (flags & 4 /* Property */) { - if (flags & 268435456 /* SyntheticProperty */) { - // If union property is result of union of non method (property/accessors/variables), it is labeled as property - var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - var rootSymbolFlags = rootSymbol.getFlags(); - if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { - return ScriptElementKind.memberVariableElement; - } - ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); - }); - if (!unionPropertyKind) { - // If this was union of all methods, - // make sure it has call signatures before we can label it as method - var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (typeOfUnionProperty.getCallSignatures().length) { - return ScriptElementKind.memberFunctionElement; - } - return ScriptElementKind.memberVariableElement; - } - return unionPropertyKind; - } - return ScriptElementKind.memberVariableElement; - } - return ScriptElementKind.unknown; - } - function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 - ? ts.getNodeModifiers(symbol.declarations[0]) - : ScriptElementKindModifier.none; - } - // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { - if (semanticMeaning === void 0) { semanticMeaning = getMeaningFromLocation(location); } - var typeChecker = program.getTypeChecker(); - var displayParts = []; - var documentation; - var symbolFlags = symbol.flags; - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, location); - var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 /* ThisKeyword */ && ts.isExpression(location); - var type; - // Class at constructor site need to be shown as constructor apart from property,method, vars - if (symbolKind !== ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { - // If it is accessor they are allowed only if location is at name of the accessor - if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { - symbolKind = ScriptElementKind.memberVariableElement; - } - var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (type) { - if (location.parent && location.parent.kind === 172 /* PropertyAccessExpression */) { - var right = location.parent.name; - // Either the location is on the right of a property access, or on the left and the right is missing - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; - } - } - // try get the call/construct signature from the type if it matches - var callExpression = void 0; - if (location.kind === 174 /* CallExpression */ || location.kind === 175 /* NewExpression */) { - callExpression = location; - } - else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { - callExpression = location.parent; - } - if (callExpression) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); - if (!signature && candidateSignatures.length) { - // Use the first candidate: - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpression.kind === 175 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - // Get the first signature if there is one -- allSignatures may contain - // either the original signature or its target, so check for either - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { - // Constructor - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else if (symbolFlags & 8388608 /* Alias */) { - symbolKind = ScriptElementKind.alias; - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case ScriptElementKind.memberVariableElement: - case ScriptElementKind.variableElement: - case ScriptElementKind.constElement: - case ScriptElementKind.letElement: - case ScriptElementKind.parameterElement: - case ScriptElementKind.localVariableElement: - // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 65536 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); - } - addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); - break; - default: - // Just signature - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; - } - } - else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 148 /* Constructor */)) { - // get the signature from the declaration and write it - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); - } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 148 /* Constructor */) { - // show (constructor) Type(...) signature - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 /* CallSignature */ && - !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; - } - } - } - if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */)) { - // Special case for class expressions because we would like to indicate that - // the class name is local to the class body (similar to function expression) - // (local class) class - pushTypePart(ScriptElementKind.localClassElement); - } - else { - // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(73 /* ClassKeyword */)); - } - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107 /* InterfaceKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); - } - if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); - if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74 /* ConstKeyword */)); - displayParts.push(ts.spacePart()); - } - displayParts.push(ts.keywordPart(81 /* EnumKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90 /* InKeyword */)); - displayParts.push(ts.spacePart()); - if (symbol.parent) { - // Class/Interface type parameter - addFullSymbolName(symbol.parent, enclosingDeclaration); - writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); - } - else { - // Method/function type parameter - var declaration = ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; - if (declaration) { - if (ts.isFunctionLikeKind(declaration.kind)) { - var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - else if (declaration.kind !== 151 /* CallSignature */ && declaration.name) { - addFullSymbolName(declaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); - } - else { - // Type alias type parameter - // For example - // type list = T[]; // Both T will go through same code path - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); - } - } - } - } - if (symbolFlags & 8 /* EnumMember */) { - addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 255 /* EnumMember */) { - var constantValue = typeChecker.getConstantValue(declaration); - if (constantValue !== undefined) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral)); - } - } - } - if (symbolFlags & 8388608 /* Alias */) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229 /* ImportEqualsDeclaration */) { - var importEqualsDeclaration = declaration; - if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - } - else { - var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); - if (internalAliasSymbol) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(internalAliasSymbol, enclosingDeclaration); - } - } - return true; - } - }); - } - if (!hasAddedSymbolInfo) { - if (symbolKind !== ScriptElementKind.unknown) { - if (type) { - if (isThisExpression) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97 /* ThisKeyword */)); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - // For properties, variables and local vars: show the type - if (symbolKind === ScriptElementKind.memberVariableElement || - symbolFlags & 3 /* Variable */ || - symbolKind === ScriptElementKind.localVariableElement || - isThisExpression) { - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); - displayParts.push(ts.spacePart()); - // If the type is type parameter, format it specially - if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } - else { - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); - } - } - else if (symbolFlags & 16 /* Function */ || - symbolFlags & 8192 /* Method */ || - symbolFlags & 16384 /* Constructor */ || - symbolFlags & 131072 /* Signature */ || - symbolFlags & 98304 /* Accessor */ || - symbolKind === ScriptElementKind.memberFunctionElement) { - var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); - } - } - } - else { - symbolKind = getSymbolKind(symbol, location); - } - } - if (!documentation) { - documentation = symbol.getDocumentationComment(); - } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; - function addNewLineIfDisplayPartsExist() { - if (displayParts.length) { - displayParts.push(ts.lineBreakPart()); - } - } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); - ts.addRange(displayParts, fullSymbolDisplayParts); - } - function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); - if (symbolKind) { - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - } - function pushTypePart(symbolKind) { - switch (symbolKind) { - case ScriptElementKind.variableElement: - case ScriptElementKind.functionElement: - case ScriptElementKind.letElement: - case ScriptElementKind.constElement: - case ScriptElementKind.constructorImplementationElement: - displayParts.push(ts.textOrKeywordPart(symbolKind)); - return; - default: - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - return; - } - } - function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); - if (allSignatures.length > 1) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(35 /* PlusToken */)); - displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), SymbolDisplayPartKind.numericLiteral)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - } - documentation = signature.getDocumentationComment(); - } - function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } + function getCompletionEntrySymbol(fileName, position, entryName) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -55629,7 +73444,7 @@ var ts; if (node === sourceFile) { return undefined; } - if (isLabelName(node)) { + if (ts.isLabelName(node)) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -55647,228 +73462,46 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ScriptElementKind.unknown, - kindModifiers: ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.unknown, + kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: ts.typeToDisplayParts(typeChecker, type, getContainerNode(node)), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined }; } } return undefined; } - var displayPartsDocumentationsAndKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, getContainerNode(node), node); + var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); return { kind: displayPartsDocumentationsAndKind.symbolKind, - kindModifiers: getSymbolModifiers(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, documentation: displayPartsDocumentationsAndKind.documentation }; } - function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), - kind: symbolKind, - name: symbolName, - containerKind: undefined, - containerName: containerName - }; - } - function getDefinitionFromSymbol(symbol, node) { - var typeChecker = program.getTypeChecker(); - var result = []; - var declarations = symbol.getDeclarations(); - var symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol - var symbolKind = getSymbolKind(symbol, node); - var containerSymbol = symbol.parent; - var 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. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - // 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 === 121 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, - /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } - } - return false; - } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; - } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { - var declarations = []; - var definition; - ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148 /* Constructor */) || - (!selectConstructors && (d.kind === 220 /* FunctionDeclaration */ || d.kind === 147 /* MethodDeclaration */ || d.kind === 146 /* MethodSignature */))) { - declarations.push(d); - if (d.body) - definition = d; - } - }); - if (definition) { - result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); - return true; - } - else if (declarations.length) { - result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; - } - } - function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { - return ref; - } - } - return undefined; - } - function getDefinitionInfoForFileReference(name, targetFileName) { - return { - fileName: targetFileName, - textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ScriptElementKind.scriptElement, - name: name, - containerName: undefined, - containerKind: undefined - }; - } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - return undefined; - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); - if (referenceFile && referenceFile.resolvedFileName) { - return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; - } - return undefined; - } - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - // Labels - if (isJumpStatementTarget(node)) { - var labelName = node.text; - var label = getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - // Could not find a symbol e.g. node is string or number keyword, - // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol) { - return undefined; - } - // If this is an alias, and the request came at the declaration location - // get the aliased symbol instead. This allows for goto def on an import e.g. - // import {A, B} from "mod"; - // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 69 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 234 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 233 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - } - // Because name in short-hand property assignment has two different meanings: property name and property value, - // using go-to-definition at such position should go to the variable declaration of the property value rather than - // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition - // is performed at the location of property access, we would like to go to definition of the property in the short-hand - // assignment. This case and others are handled by the following code. - if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { - var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - if (!shorthandSymbol) { - return []; - } - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); - var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); - } - return getDefinitionFromSymbol(symbol, node); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + /// Goto implementation + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToImplementation.getImplementationAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); } - /// Goto type function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { - return undefined; - } - if (type.flags & 16384 /* Union */) { - var result_3 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); - } - }); - return result_3; - } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(type.symbol, node); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -55876,527 +73509,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingWord(sourceFile, position); - if (!node) { - return undefined; - } - return getSemanticDocumentHighlights(node) || getSyntacticDocumentHighlights(node); - function getHighlightSpanForNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - return { - fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: HighlightSpanKind.none - }; - } - function getSemanticDocumentHighlights(node) { - if (node.kind === 69 /* Identifier */ || - node.kind === 97 /* ThisKeyword */ || - node.kind === 165 /* ThisType */ || - node.kind === 95 /* SuperKeyword */ || - node.kind === 9 /* StringLiteral */ || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false); - return convertReferencedSymbols(referencedSymbols); - } - return undefined; - function convertReferencedSymbols(referencedSymbols) { - if (!referencedSymbols) { - return undefined; - } - var fileNameToDocumentHighlights = {}; - var result = []; - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var referencedSymbol = referencedSymbols_1[_i]; - for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { - var referenceEntry = _b[_a]; - var fileName_1 = referenceEntry.fileName; - var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); - if (!documentHighlights) { - documentHighlights = { fileName: fileName_1, highlightSpans: [] }; - fileNameToDocumentHighlights[fileName_1] = documentHighlights; - result.push(documentHighlights); - } - documentHighlights.highlightSpans.push({ - textSpan: referenceEntry.textSpan, - kind: referenceEntry.isWriteAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference - }); - } - } - return result; - } - } - function getSyntacticDocumentHighlights(node) { - var fileName = sourceFile.fileName; - var highlightSpans = getHighlightSpans(node); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: fileName, highlightSpans: highlightSpans }]; - // returns true if 'node' is defined and has a matching 'kind'. - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - // Null-propagating 'parent' function. - function parent(node) { - return node && node.parent; - } - function getHighlightSpans(node) { - if (node) { - switch (node.kind) { - case 88 /* IfKeyword */: - case 80 /* ElseKeyword */: - if (hasKind(node.parent, 203 /* IfStatement */)) { - return getIfElseOccurrences(node.parent); - } - break; - case 94 /* ReturnKeyword */: - if (hasKind(node.parent, 211 /* ReturnStatement */)) { - return getReturnOccurrences(node.parent); - } - break; - case 98 /* ThrowKeyword */: - if (hasKind(node.parent, 215 /* ThrowStatement */)) { - return getThrowOccurrences(node.parent); - } - break; - case 72 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 216 /* TryStatement */)) { - return getTryCatchFinallyOccurrences(node.parent.parent); - } - break; - case 100 /* TryKeyword */: - case 85 /* FinallyKeyword */: - if (hasKind(parent(node), 216 /* TryStatement */)) { - return getTryCatchFinallyOccurrences(node.parent); - } - break; - case 96 /* SwitchKeyword */: - if (hasKind(node.parent, 213 /* SwitchStatement */)) { - return getSwitchCaseDefaultOccurrences(node.parent); - } - break; - case 71 /* CaseKeyword */: - case 77 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 213 /* SwitchStatement */)) { - return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); - } - break; - case 70 /* BreakKeyword */: - case 75 /* ContinueKeyword */: - if (hasKind(node.parent, 210 /* BreakStatement */) || hasKind(node.parent, 209 /* ContinueStatement */)) { - return getBreakOrContinueStatementOccurrences(node.parent); - } - break; - case 86 /* ForKeyword */: - if (hasKind(node.parent, 206 /* ForStatement */) || - hasKind(node.parent, 207 /* ForInStatement */) || - hasKind(node.parent, 208 /* ForOfStatement */)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 104 /* WhileKeyword */: - case 79 /* DoKeyword */: - if (hasKind(node.parent, 205 /* WhileStatement */) || hasKind(node.parent, 204 /* DoStatement */)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 121 /* ConstructorKeyword */: - if (hasKind(node.parent, 148 /* Constructor */)) { - return getConstructorOccurrences(node.parent); - } - break; - case 123 /* GetKeyword */: - case 131 /* SetKeyword */: - if (hasKind(node.parent, 149 /* GetAccessor */) || hasKind(node.parent, 150 /* SetAccessor */)) { - return getGetAndSetOccurrences(node.parent); - } - break; - default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 200 /* VariableStatement */)) { - return getModifierOccurrences(node.kind, node.parent); - } - } - } - return undefined; - } - /** - * Aggregates all throw-statements within this node *without* crossing - * into function boundaries and try-blocks with catch-clauses. - */ - function aggregateOwnedThrowStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 215 /* ThrowStatement */) { - statementAccumulator.push(node); - } - else if (node.kind === 216 /* TryStatement */) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); - } - else { - // Exceptions thrown within a try block lacking a catch clause - // are "owned" in the current context. - aggregate(tryStatement.tryBlock); - } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); - } - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - /** - * For lack of a better name, this function takes a throw statement and returns the - * nearest ancestor that is a try-block (whose try statement has a catch clause), - * function-block, or source file. - */ - function getThrowStatementOwner(throwStatement) { - var child = throwStatement; - while (child.parent) { - var parent_20 = child.parent; - if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256 /* SourceFile */) { - return parent_20; - } - // A throw-statement is only owned by a try-statement if the try-statement has - // a catch clause, and if the throw-statement occurs within the try block. - if (parent_20.kind === 216 /* TryStatement */) { - var tryStatement = parent_20; - if (tryStatement.tryBlock === child && tryStatement.catchClause) { - return child; - } - } - child = parent_20; - } - return undefined; - } - function aggregateAllBreakAndContinueStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 210 /* BreakStatement */ || node.kind === 209 /* ContinueStatement */) { - statementAccumulator.push(node); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - function ownsBreakOrContinueStatement(owner, statement) { - var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; - } - function getBreakOrContinueOwner(statement) { - for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) { - switch (node_1.kind) { - case 213 /* SwitchStatement */: - if (statement.kind === 209 /* ContinueStatement */) { - continue; - } - // Fall through. - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: - case 204 /* DoStatement */: - if (!statement.label || isLabeledBy(node_1, statement.label.text)) { - return node_1; - } - break; - default: - // Don't cross function boundaries. - if (ts.isFunctionLike(node_1)) { - return undefined; - } - break; - } - } - return undefined; - } - function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; - // Make sure we only highlight the keyword when it makes sense to do so. - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 221 /* ClassDeclaration */ || - container.kind === 192 /* ClassExpression */ || - (declaration.kind === 142 /* Parameter */ && hasKind(container, 148 /* Constructor */)))) { - return undefined; - } - } - else if (modifier === 113 /* StaticKeyword */) { - if (!(container.kind === 221 /* ClassDeclaration */ || container.kind === 192 /* ClassExpression */)) { - return undefined; - } - } - else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { - if (!(container.kind === 226 /* ModuleBlock */ || container.kind === 256 /* SourceFile */)) { - return undefined; - } - } - else if (modifier === 115 /* AbstractKeyword */) { - if (!(container.kind === 221 /* ClassDeclaration */ || declaration.kind === 221 /* ClassDeclaration */)) { - return undefined; - } - } - else { - // unsupported modifier - return undefined; - } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; - switch (container.kind) { - case 226 /* ModuleBlock */: - case 256 /* SourceFile */: - // Container is either a class declaration or the declaration is a classDeclaration - if (modifierFlag & 128 /* Abstract */) { - nodes = declaration.members.concat(declaration); - } - else { - nodes = container.statements; - } - break; - case 148 /* Constructor */: - nodes = container.parameters.concat(container.parent.members); - break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - nodes = container.members; - // If we're an accessibility modifier, we're in an instance member and should search - // the constructor's parameter list for instance members as well. - if (modifierFlag & 28 /* AccessibilityModifier */) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 148 /* Constructor */ && member; - }); - if (constructor) { - nodes = nodes.concat(constructor.parameters); - } - } - else if (modifierFlag & 128 /* Abstract */) { - nodes = nodes.concat(container); - } - break; - default: - ts.Debug.fail("Invalid container kind."); - } - ts.forEach(nodes, function (node) { - if (node.modifiers && node.flags & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - function getFlagFromModifier(modifier) { - switch (modifier) { - case 112 /* PublicKeyword */: - return 4 /* Public */; - case 110 /* PrivateKeyword */: - return 8 /* Private */; - case 111 /* ProtectedKeyword */: - return 16 /* Protected */; - case 113 /* StaticKeyword */: - return 32 /* Static */; - case 82 /* ExportKeyword */: - return 1 /* Export */; - case 122 /* DeclareKeyword */: - return 2 /* Ambient */; - case 115 /* AbstractKeyword */: - return 128 /* Abstract */; - default: - ts.Debug.fail(); - } - } - } - function pushKeywordIf(keywordList, token) { - var expected = []; - for (var _i = 2; _i < arguments.length; _i++) { - expected[_i - 2] = arguments[_i]; - } - if (token && ts.contains(expected, token.kind)) { - keywordList.push(token); - return true; - } - return false; - } - function getGetAndSetOccurrences(accessorDeclaration) { - var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 149 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 150 /* SetAccessor */); - return ts.map(keywords, getHighlightSpanForNode); - function tryPushAccessorKeyword(accessorSymbol, accessorKind) { - var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); - if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123 /* GetKeyword */, 131 /* SetKeyword */); }); - } - } - } - function getConstructorOccurrences(constructorDeclaration) { - var declarations = constructorDeclaration.symbol.getDeclarations(); - var keywords = []; - ts.forEach(declarations, function (declaration) { - ts.forEach(declaration.getChildren(), function (token) { - return pushKeywordIf(keywords, token, 121 /* ConstructorKeyword */); - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getLoopBreakContinueOccurrences(loopNode) { - var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { - // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 204 /* DoStatement */) { - var loopTokens = loopNode.getChildren(); - for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { - break; - } - } - } - } - var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { - var owner = getBreakOrContinueOwner(breakOrContinueStatement); - if (owner) { - switch (owner.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - return getLoopBreakContinueOccurrences(owner); - case 213 /* SwitchStatement */: - return getSwitchCaseDefaultOccurrences(owner); - } - } - return undefined; - } - function getSwitchCaseDefaultOccurrences(switchStatement) { - var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); - // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. - ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); - var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); - } - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getTryCatchFinallyOccurrences(tryStatement) { - var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); - if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); - } - if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getThrowOccurrences(throwStatement) { - var owner = getThrowStatementOwner(throwStatement); - if (!owner) { - return undefined; - } - var keywords = []; - ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); - }); - // If the "owner" is a function, then we equate 'return' and 'throw' statements in their - // ability to "jump out" of the function, and include occurrences for both. - if (ts.isFunctionBlock(owner)) { - ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); - }); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getReturnOccurrences(returnStatement) { - var func = ts.getContainingFunction(returnStatement); - // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 199 /* Block */))) { - return undefined; - } - var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); - }); - // Include 'throw' statements that do not occur within a try block. - ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getIfElseOccurrences(ifStatement) { - var keywords = []; - // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 203 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); - // Generally the 'else' keyword is second-to-last, so we traverse backwards. - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 203 /* IfStatement */)) { - break; - } - ifStatement = ifStatement.elseStatement; - } - var result = []; - // We'd like to highlight else/ifs together if they are only separated by whitespace - // (i.e. the keywords are separated by no comments, no newlines). - for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { - var elseKeyword = keywords[i]; - var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. - var shouldCombindElseAndIf = true; - // Avoid recalculating getStart() by iterating backwards. - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { - if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; - break; - } - } - if (shouldCombindElseAndIf) { - result.push({ - fileName: fileName, - textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: HighlightSpanKind.reference - }); - i++; // skip the next keyword - continue; - } - } - // Ordinary case: just highlight the keyword. - result.push(getHighlightSpanForNode(keywords[i])); - } - return result; - } - } + return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); } /// References and Occurrences function getOccurrencesAtPositionCore(fileName, position) { @@ -56414,7 +73527,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, isDefinition: false }); } @@ -56422,24 +73535,13 @@ var ts; return result; } } - function convertReferences(referenceSymbols) { - if (!referenceSymbols) { - return undefined; - } - var referenceEntries = []; - for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { - var referenceSymbol = referenceSymbols_1[_i]; - ts.addRange(referenceEntries, referenceSymbol.references); - } - return referenceEntries; - } function findRenameLocations(fileName, position, findInStrings, findInComments) { var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function findReferences(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); @@ -56448,843 +73550,13 @@ var ts; } function findReferencedSymbols(fileName, position, findInStrings, findInComments) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - if (node === sourceFile) { - return undefined; - } - switch (node.kind) { - case 8 /* NumericLiteral */: - if (!isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - break; - } - // Fallthrough - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - // case SyntaxKind.SuperKeyword: TODO:GH#9268 - case 9 /* StringLiteral */: - return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); - } - return undefined; - } - function isThis(node) { - switch (node.kind) { - case 97 /* ThisKeyword */: - // case SyntaxKind.ThisType: TODO: GH#9267 - return true; - case 69 /* Identifier */: - // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; - default: - return false; - } - } - function getReferencedSymbolsForNode(node, sourceFiles, findInStrings, findInComments) { - var typeChecker = program.getTypeChecker(); - // Labels - if (isLabelName(node)) { - if (isJumpStatementTarget(node)) { - var labelDefinition = getTargetLabel(node.parent, node.text); - // if we have a label definition, look within its statement for references, if not, then - // the label is undefined and we have no results.. - return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; - } - else { - // it is a label definition and not a target, search within the parent labeledStatement - return getLabelReferencesInNode(node.parent, node); - } - } - if (isThis(node)) { - return getReferencesForThisKeyword(node, sourceFiles); - } - if (node.kind === 95 /* SuperKeyword */) { - return getReferencesForSuperKeyword(node); - } - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles); - } - // Could not find a symbol e.g. unknown identifier - if (!symbol) { - // Can't have references to something that we have no symbol for. - return undefined; - } - var declarations = symbol.declarations; - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!declarations || !declarations.length) { - return undefined; - } - var result; - // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); - // Get the text to search for. - // Note: if this is an external module symbol, the name doesn't include quotes. - var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - // Maps from a symbol ID to the ReferencedSymbol entry in 'result'. - var symbolToIndex = []; - if (scope) { - result = []; - getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; - cancellationToken.throwIfCancellationRequested(); - var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { - result = result || []; - getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - } - } - return result; - function getDefinition(symbol) { - var info = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, node.getSourceFile(), getContainerNode(node), node); - var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } - return { - containerKind: "", - containerName: "", - name: name, - kind: info.symbolKind, - fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0) - }; - } - function getAliasSymbolForPropertyNameSymbol(symbol, location) { - if (symbol.flags & 8388608 /* Alias */) { - // Default import get alias - var defaultImport = ts.getDeclarationOfKind(symbol, 231 /* ImportClause */); - if (defaultImport) { - return typeChecker.getAliasedSymbol(symbol); - } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 /* ImportSpecifier */ || - declaration.kind === 238 /* ExportSpecifier */) ? declaration : undefined; }); - if (importOrExportSpecifier && - // export { a } - (!importOrExportSpecifier.propertyName || - // export {a as class } where a is location - importOrExportSpecifier.propertyName === location)) { - // If Import specifier -> get alias - // else Export specifier -> get local target - return importOrExportSpecifier.kind === 234 /* ImportSpecifier */ ? - typeChecker.getAliasedSymbol(symbol) : - typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); - } - } - return undefined; - } - function getPropertySymbolOfDestructuringAssignment(location) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - typeChecker.getPropertySymbolOfDestructuringAssignment(location); - } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); - return bindingElement && - bindingElement.parent.kind === 167 /* ObjectBindingPattern */ && - !bindingElement.propertyName; - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); - var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); - return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - } - return undefined; - } - function getInternedName(symbol, location, declarations) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever under the cursor. - if (ts.isImportOrExportSpecifierName(location)) { - return location.getText(); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - symbol = localExportDefaultSymbol || symbol; - return ts.stripQuotes(symbol.name); - } - /** - * Determines the smallest scope in which a symbol may have named references. - * Note that not every construct has been accounted for. This function can - * probably be improved. - * - * @returns undefined if the scope cannot be determined, implying that - * a reference to a symbol can occur anywhere. - */ - function getSymbolScope(symbol) { - // If this is the symbol of a named function expression or named class expression, - // then named references are limited to its own scope. - var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { - return valueDeclaration; - } - // If this is private property or method, the scope is the containing class - if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); - if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); - } - } - // If the symbol is an import we would like to find it if we are looking for what it imports. - // So consider it visible outside its declaration scope. - if (symbol.flags & 8388608 /* Alias */) { - return undefined; - } - // If symbol is of object binding pattern element without property name we would want to - // look for property too and that could be anywhere - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - return undefined; - } - // if this symbol is visible from its parent container, e.g. exported, then bail out - // if symbol correspond to the union property - bail out - if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { - return undefined; - } - var scope; - var declarations = symbol.getDeclarations(); - if (declarations) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - var container = getContainerNode(declaration); - if (!container) { - return undefined; - } - if (scope && scope !== container) { - // Different declarations have different containers, bail out - return undefined; - } - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { - // This is a global variable and not an external module, any declaration defined - // within this scope is visible outside the file - return undefined; - } - // The search scope is the container node - scope = container; - } - } - return scope; - } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { - var positions = []; - /// TODO: Cache symbol existence for files to save text search - // Also, need to make this work for unicode escapes. - // Be resilient in the face of a symbol with no name or zero length name - if (!symbolName || !symbolName.length) { - return positions; - } - var text = sourceFile.text; - var sourceLength = text.length; - var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); - while (position >= 0) { - cancellationToken.throwIfCancellationRequested(); - // If we are past the end, stop looking - if (position > end) - break; - // We found a match. Make sure it's not part of a larger word (i.e. the char - // before and after it have to be a non-identifier char). - var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { - // Found a real match. Keep searching. - positions.push(position); - } - position = text.indexOf(symbolName, position + symbolNameLength + 1); - } - return positions; - } - function getLabelReferencesInNode(container, targetLabel) { - var references = []; - var sourceFile = container.getSourceFile(); - var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - return; - } - // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = { - containerKind: "", - containerName: "", - fileName: targetLabel.getSourceFile().fileName, - kind: ScriptElementKind.label, - name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) - }; - return [{ definition: definition, references: references }]; - } - function isValidReferencePosition(node, searchSymbolName) { - if (node) { - // Compare the length so we filter out strict superstrings of the symbol we are looking for - switch (node.kind) { - case 69 /* Identifier */: - return node.getWidth() === searchSymbolName.length; - case 9 /* StringLiteral */: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isNameOfExternalModuleImportOrDeclaration(node)) { - // For string literals we have two additional chars for the quotes - return node.getWidth() === searchSymbolName.length + 2; - } - break; - case 8 /* NumericLiteral */: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - return node.getWidth() === searchSymbolName.length; - } - break; - } - } - return false; - } - /** Search within node "container" for references for a search value, where the search value is defined as a - * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). - * searchLocation: a node where the search value - */ - function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { - var sourceFile = container.getSourceFile(); - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0) { - var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); - referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); - } - } - }); - } - return; - function getReferencedSymbol(symbol) { - var symbolId = ts.getSymbolId(symbol); - var index = symbolToIndex[symbolId]; - if (index === undefined) { - index = result.length; - symbolToIndex[symbolId] = index; - result.push({ - definition: getDefinition(symbol), - references: [] - }); - } - return result[index]; - } - function isInNonReferenceComment(sourceFile, position) { - return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - } - function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); - if (!searchSpaceNode) { - return undefined; - } - // Whether 'super' occurs in a static context within a class. - var staticFlag = 32 /* Static */; - switch (searchSpaceNode.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class - break; - default: - return undefined; - } - var references = []; - var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95 /* SuperKeyword */) { - return; - } - var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); - // If we have a 'super' container, we must have an enclosing class. - // Now make sure the owning class is the same as the search-space - // and has the same static qualifier as the original 'super's owner. - if (container && (32 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = getDefinition(searchSpaceNode.symbol); - return [{ definition: definition, references: references }]; - } - function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { - var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); - // Whether 'this' occurs in a static context within a class. - var staticFlag = 32 /* Static */; - switch (searchSpaceNode.kind) { - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - if (ts.isObjectLiteralMethod(searchSpaceNode)) { - break; - } - // fall through - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class - break; - case 256 /* SourceFile */: - if (ts.isExternalModule(searchSpaceNode)) { - return undefined; - } - // Fall through - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - break; - // Computed properties in classes are not handled here because references to this are illegal, - // so there is no point finding references to them. - default: - return undefined; - } - var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 256 /* SourceFile */) { - ts.forEach(sourceFiles, function (sourceFile) { - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: "this", - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || !isThis(node)) { - return; - } - var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); - switch (searchSpaceNode.kind) { - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - if (searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: - // Make sure the container belongs to the same class - // and has the appropriate static modifier from the original container. - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 32 /* Static */) === staticFlag) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 256 /* SourceFile */: - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { - result.push(getReferenceEntryFromNode(node)); - } - break; - } - }); - } - } - function getReferencesForStringLiteral(node, sourceFiles) { - var typeChecker = program.getTypeChecker(); - var type = getStringLiteralTypeForNode(node, typeChecker); - if (!type) { - // nothing to do here. moving on - return undefined; - } - var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); - getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: type.text, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; - cancellationToken.throwIfCancellationRequested(); - var node_2 = ts.getTouchingWord(sourceFile, position); - if (!node_2 || node_2.kind !== 9 /* StringLiteral */) { - return; - } - var type_1 = getStringLiteralTypeForNode(node_2, typeChecker); - if (type_1 === searchType) { - references.push(getReferenceEntryFromNode(node_2)); - } - } - } - } - function populateSearchSymbolSet(symbol, location) { - // The search set contains at least the current symbol - var result = [symbol]; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254 /* ShorthandPropertyAssignment */) { - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); - if (propertySymbol) { - result.push(propertySymbol); - } - } - // If the symbol is an alias, add what it aliases to the list - // import {a} from "mod"; - // export {a} - // If the symbol is an alias to default declaration, add what it aliases to the list - // declare "mod" { export default class B { } } - // import B from "mod"; - //// For export specifiers, the exported name can be referring to a local symbol, e.g.: - //// import {a} from "mod"; - //// export {a as somethingElse} - //// We want the *local* declaration of 'a' as declared in the import, - //// *not* as declared within "mod" (or farther) - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); - if (aliasSymbol) { - result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); - } - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - if (containingObjectLiteralElement) { - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); - }); - /* Because in short-hand property assignment, location has two meaning : property name and as value of the property - * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of - * property name and variable declaration of the identifier. - * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service - * should show both 'name' in 'obj' and 'name' in variable declaration - * const name = "Foo"; - * const obj = { name }; - * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment - * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration - * will be included correctly. - */ - var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); - if (shorthandValueSymbol) { - result.push(shorthandValueSymbol); - } - } - // If the symbol.valueDeclaration is a property parameter declaration, - // we should include both parameter declaration symbol and property declaration symbol - // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. - // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 /* Parameter */ && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); - if (bindingElementPropertySymbol) { - result.push(bindingElementPropertySymbol); - } - // If this is a union property, add all the symbols from all its source symbols in all unioned types. - // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list - ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ {}); - } - }); - return result; - } - /** - * Find symbol of the given property-name and add the symbol to the given result array - * @param symbol a symbol to start searching for the given propertyName - * @param propertyName a name of property to search for - * @param result an array of symbol of found property symbols - * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. - * The value of previousIterationSymbol is undefined when the function is first called. - */ - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { - if (!symbol) { - return; - } - // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited - // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. - // For example: - // interface C extends C { - // /*findRef*/propName: string; - // } - // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, - // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, - // the function will add any found symbol of the property-name, then its sub-routine will call - // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already - // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. - if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { - return; - } - if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === 222 /* InterfaceDeclaration */) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = typeChecker.getTypeAtLocation(typeReference); - if (type) { - var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); - if (propertySymbol) { - result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); - } - // Visit the typeReference as well to see if it directly or indirectly use that property - previousIterationSymbolsCache[symbol.name] = symbol; - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); - } - } - } - } - function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation) { - if (searchSymbols.indexOf(referenceSymbol) >= 0) { - return referenceSymbol; - } - // If the reference symbol is an alias, check if what it is aliasing is one of the search - // symbols but by looking up for related symbol of this alias so it can handle multiple level of indirectness. - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); - if (aliasSymbol) { - return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation); - } - // If the reference location is in an object literal, try to get the contextual type for the - // object literal, lookup the property symbol in the contextual type, and use this symbol to - // compare to our searchSymbol - var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); - if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - }); - if (contextualSymbol) { - return contextualSymbol; - } - // If the reference location is the name of property from object literal destructuring pattern - // Get the property symbol from the object literal's type and look if thats the search symbol - // In below eg. get 'property' from type of elems iterating type - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); - if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { - return propertySymbol; - } - } - // If the reference location is the binding element and doesn't have property name - // then include the binding element in the related symbols - // let { a } : { a }; - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); - if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { - return bindingElementPropertySymbol; - } - // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) - // Or a union property, use its underlying unioned symbols - return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { - // if it is in the list, then we are done - if (searchSymbols.indexOf(rootSymbol) >= 0) { - return rootSymbol; - } - // Finally, try all properties with the same name in any type the containing type extended or implemented, and - // see if any is in the list - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - var result_4 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ {}); - return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - } - return undefined; - }); - } - function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { - return nameExpression.text; - } - return undefined; - } - return node.name.text; - } - function getPropertySymbolsFromContextualType(node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol_1 = contextualType.getProperty(name); - if (symbol_1) { - result_5.push(symbol_1); - } - if (contextualType.flags & 16384 /* Union */) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; - } - /** Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations - * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class - * then we need to widen the search to include type positions as well. - * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated - * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) - * do not intersect in any of the three spaces. - */ - function getIntersectingMeaningFromDeclarations(meaning, declarations) { - if (declarations) { - var lastIterationMeaning = void 0; - do { - // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] - // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module - // intersects with the class in the value space. - // To achieve that we will keep iterating until the result stabilizes. - // Remember the last meaning - lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; - var declarationMeaning = getMeaningFromDeclaration(declaration); - if (declarationMeaning & meaning) { - meaning |= declarationMeaning; - } - } - } while (meaning !== lastIterationMeaning); - } - return meaning; - } - } - function getReferenceEntryFromNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - if (node.kind === 9 /* StringLiteral */) { - start += 1; - end -= 1; - } - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) - }; - } - /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ - function isWriteAccess(node) { - if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { - return true; - } - var parent = node.parent; - if (parent) { - if (parent.kind === 186 /* PostfixUnaryExpression */ || parent.kind === 185 /* PrefixUnaryExpression */) { - return true; - } - else if (parent.kind === 187 /* BinaryExpression */ && parent.left === node) { - var operator = parent.operatorToken.kind; - return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; - } - } - return false; + return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount) { + function getNavigateToItems(searchValue, maxResultCount, fileName) { synchronizeHostData(); - var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -57303,134 +73575,6 @@ var ts; emitSkipped: emitOutput.emitSkipped }; } - function getMeaningFromDeclaration(node) { - switch (node.kind) { - case 142 /* Parameter */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 252 /* CatchClause */: - return 1 /* Value */; - case 141 /* TypeParameter */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 159 /* TypeLiteral */: - return 2 /* Type */; - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - return 1 /* Value */ | 2 /* Type */; - case 225 /* ModuleDeclaration */: - if (ts.isAmbientModule(node)) { - return 4 /* Namespace */ | 1 /* Value */; - } - else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { - return 4 /* Namespace */ | 1 /* Value */; - } - else { - return 4 /* Namespace */; - } - case 233 /* NamedImports */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 230 /* ImportDeclaration */: - case 235 /* ExportAssignment */: - case 236 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - // An external module can be a Value - case 256 /* SourceFile */: - return 4 /* Namespace */ | 1 /* Value */; - } - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - } - function isTypeReference(node) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - return node.parent.kind === 155 /* TypeReference */ || - (node.parent.kind === 194 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node)) || - node.kind === 165 /* ThisType */; - } - function isNamespaceReference(node) { - return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); - } - function isPropertyAccessNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 172 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 172 /* PropertyAccessExpression */) { - root = root.parent; - } - isLastClause = root.name === node; - } - if (!isLastClause && root.parent.kind === 194 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 251 /* HeritageClause */) { - var decl = root.parent.parent.parent; - return (decl.kind === 221 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 222 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); - } - return false; - } - function isQualifiedNameNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 139 /* QualifiedName */) { - while (root.parent && root.parent.kind === 139 /* QualifiedName */) { - root = root.parent; - } - isLastClause = root.right === node; - } - return root.parent.kind === 155 /* TypeReference */ && !isLastClause; - } - function isInRightSideOfImport(node) { - while (node.parent.kind === 139 /* QualifiedName */) { - node = node.parent; - } - return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; - } - function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69 /* Identifier */); - // import a = |b|; // Namespace - // import a = |b.c|; // Value, type, namespace - // import a = |b.c|.d; // Namespace - if (node.parent.kind === 139 /* QualifiedName */ && - node.parent.right === node && - node.parent.parent.kind === 229 /* ImportEqualsDeclaration */) { - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - } - return 4 /* Namespace */; - } - function getMeaningFromLocation(node) { - if (node.parent.kind === 235 /* ExportAssignment */) { - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - } - else if (isInRightSideOfImport(node)) { - return getMeaningFromRightHandSideOfImportEquals(node); - } - else if (ts.isDeclarationName(node)) { - return getMeaningFromDeclaration(node.parent); - } - else if (isTypeReference(node)) { - return 2 /* Type */; - } - else if (isNamespaceReference(node)) { - return 4 /* Namespace */; - } - else { - return 1 /* Value */; - } - } // Signature help /** * This is a semantic operation. @@ -57444,6 +73588,9 @@ var ts; function getNonBoundSourceFile(fileName) { return syntaxTreeCache.getCurrentSourceFile(fileName); } + function getSourceFile(fileName) { + return getNonBoundSourceFile(fileName); + } function getNameOrDottedNameSpan(fileName, startPos, endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location @@ -57455,7 +73602,6 @@ var ts; case 172 /* PropertyAccessExpression */: case 139 /* QualifiedName */: case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: @@ -57470,11 +73616,11 @@ var ts; } var nodeForStartPos = node; while (true) { - if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node nodeForStartPos = nodeForStartPos.parent; } - else if (isNameOfModuleDeclaration(nodeForStartPos)) { + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module @@ -57505,462 +73651,20 @@ var ts; return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { - return convertClassifications(getEncodedSemanticClassifications(fileName, span)); - } - function checkForClassificationCancellation(kind) { - // We don't want to actually call back into our host on every node to find out if we've - // been canceled. That would be an enormous amount of chattyness, along with the all - // the overhead of marshalling the data to/from the host. So instead we pick a few - // reasonable node kinds to bother checking on. These node kinds represent high level - // constructs that we would expect to see commonly, but just at a far less frequent - // interval. - // - // For example, in checker.ts (around 750k) we only have around 600 of these constructs. - // That means we're calling back into the host around every 1.2k of the file we process. - // Lib.d.ts has similar numbers. - switch (kind) { - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - cancellationToken.throwIfCancellationRequested(); - } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); - var result = []; - var classifiableNames = program.getClassifiableNames(); - processNode(sourceFile); - return { spans: result, endOfLineState: 0 /* None */ }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448 /* Classifiable */) === 0 /* None */) { - return; - } - if (flags & 32 /* Class */) { - return 11 /* className */; - } - else if (flags & 384 /* Enum */) { - return 12 /* enumName */; - } - else if (flags & 524288 /* TypeAlias */) { - return 16 /* typeAliasName */; - } - else if (meaningAtPosition & 2 /* Type */) { - if (flags & 64 /* Interface */) { - return 13 /* interfaceName */; - } - else if (flags & 262144 /* TypeParameter */) { - return 15 /* typeParameterName */; - } - } - else if (flags & 1536 /* Module */) { - // Only classify a module as such if - // - It appears in a namespace context. - // - There exists a module declaration which actually impacts the value side. - if (meaningAtPosition & 4 /* Namespace */ || - (meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) { - return 14 /* moduleName */; - } - } - return undefined; - /** - * Returns true if there exists a module that introduces entities on the value side. - */ - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 /* ModuleDeclaration */ && - ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; - }); - } - } - function processNode(node) { - // Only walk into nodes that intersect the requested span. - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(kind); - if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { - var identifier = node; - // Only bother calling into the typechecker if this is an identifier that - // could possibly resolve to a type name. This makes classification run - // in a third of the time it would normally take. - if (classifiableNames[identifier.text]) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } - } - } - function getClassificationTypeName(type) { - switch (type) { - case 1 /* comment */: return ClassificationTypeNames.comment; - case 2 /* identifier */: return ClassificationTypeNames.identifier; - case 3 /* keyword */: return ClassificationTypeNames.keyword; - case 4 /* numericLiteral */: return ClassificationTypeNames.numericLiteral; - case 5 /* operator */: return ClassificationTypeNames.operator; - case 6 /* stringLiteral */: return ClassificationTypeNames.stringLiteral; - case 8 /* whiteSpace */: return ClassificationTypeNames.whiteSpace; - case 9 /* text */: return ClassificationTypeNames.text; - case 10 /* punctuation */: return ClassificationTypeNames.punctuation; - case 11 /* className */: return ClassificationTypeNames.className; - case 12 /* enumName */: return ClassificationTypeNames.enumName; - case 13 /* interfaceName */: return ClassificationTypeNames.interfaceName; - case 14 /* moduleName */: return ClassificationTypeNames.moduleName; - case 15 /* typeParameterName */: return ClassificationTypeNames.typeParameterName; - case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; - case 17 /* parameterName */: return ClassificationTypeNames.parameterName; - case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; - case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName; - case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName; - case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName; - case 22 /* jsxAttribute */: return ClassificationTypeNames.jsxAttribute; - case 23 /* jsxText */: return ClassificationTypeNames.jsxText; - case 24 /* jsxAttributeStringLiteralValue */: return ClassificationTypeNames.jsxAttributeStringLiteralValue; - } - } - function convertClassifications(classifications) { - ts.Debug.assert(classifications.spans.length % 3 === 0); - var dense = classifications.spans; - var result = []; - for (var i = 0, n = dense.length; i < n; i += 3) { - result.push({ - textSpan: ts.createTextSpan(dense[i], dense[i + 1]), - classificationType: getClassificationTypeName(dense[i + 2]) - }); - } - return result; + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getSyntacticClassifications(fileName, span) { - return convertClassifications(getEncodedSyntacticClassifications(fileName, span)); + // doesn't use compiler - no need to synchronize with host + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getEncodedSyntacticClassifications(fileName, span) { // doesn't use compiler - no need to synchronize with host - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var spanStart = span.start; - var spanLength = span.length; - // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var result = []; - processElement(sourceFile); - return { spans: result, endOfLineState: 0 /* None */ }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifyLeadingTriviaAndGetTokenStart(token) { - triviaScanner.setTextPos(token.pos); - while (true) { - var start = triviaScanner.getTextPos(); - // only bother scanning if we have something that could be trivia. - if (!ts.couldStartTrivia(sourceFile.text, start)) { - return start; - } - var kind = triviaScanner.scan(); - var end = triviaScanner.getTextPos(); - var width = end - start; - // The moment we get something that isn't trivia, then stop processing. - if (!ts.isTrivia(kind)) { - return start; - } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); - continue; - } - // for the ======== add a comment for the first line, and then lex all - // subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); - } - } - } - function classifyComment(token, kind, start, width) { - if (kind === 3 /* MultiLineCommentTrivia */) { - // See if this is a doc comment. If so, we'll classify certain portions of it - // specially. - var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); - if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { - docCommentAndDiagnostics.jsDocComment.parent = token; - classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); - return; - } - } - // Simple comment. Just add as is. - pushCommentRange(start, width); - } - function pushCommentRange(start, width) { - pushClassification(start, width, 1 /* comment */); - } - function classifyJSDocComment(docComment) { - var pos = docComment.pos; - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - // As we walk through each tag, classify the portion of text from the end of - // the last tag (or the start of the entire doc comment) as 'comment'. - if (tag.pos !== pos) { - pushCommentRange(pos, tag.pos - pos); - } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); - pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); - pos = tag.tagName.end; - switch (tag.kind) { - case 275 /* JSDocParameterTag */: - processJSDocParameterTag(tag); - break; - case 278 /* JSDocTemplateTag */: - processJSDocTemplateTag(tag); - break; - case 277 /* JSDocTypeTag */: - processElement(tag.typeExpression); - break; - case 276 /* JSDocReturnTag */: - processElement(tag.typeExpression); - break; - } - pos = tag.end; - } - if (pos !== docComment.end) { - pushCommentRange(pos, docComment.end - pos); - } - return; - function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); - pos = tag.preParameterName.end; - } - if (tag.typeExpression) { - pushCommentRange(pos, tag.typeExpression.pos - pos); - processElement(tag.typeExpression); - pos = tag.typeExpression.end; - } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); - pos = tag.postParameterName.end; - } - } - } - function processJSDocTemplateTag(tag) { - for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { - var child = _a[_i]; - processElement(child); - } - } - function classifyDisabledMergeCode(text, start, end) { - // Classify the line that the ======= marker is on as a comment. Then just lex - // all further tokens and add them to the result. - var i; - for (i = start; i < end; i++) { - if (ts.isLineBreak(text.charCodeAt(i))) { - break; - } - } - pushClassification(start, i - start, 1 /* comment */); - mergeConflictScanner.setTextPos(i); - while (mergeConflictScanner.getTextPos() < end) { - classifyDisabledCodeToken(); - } - } - function classifyDisabledCodeToken() { - var start = mergeConflictScanner.getTextPos(); - var tokenKind = mergeConflictScanner.scan(); - var end = mergeConflictScanner.getTextPos(); - var type = classifyTokenType(tokenKind); - if (type) { - pushClassification(start, end - start, type); - } - } - /** - * Returns true if node should be treated as classified and no further processing is required. - * False will mean that node is not classified and traverse routine should recurse into node contents. - */ - function tryClassifyNode(node) { - if (ts.nodeIsMissing(node)) { - return true; - } - var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { - return false; - } - var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); - var tokenWidth = node.end - tokenStart; - ts.Debug.assert(tokenWidth >= 0); - if (tokenWidth > 0) { - var type = classifiedElementName || classifyTokenType(node.kind, node); - if (type) { - pushClassification(tokenStart, tokenWidth, type); - } - } - return true; - } - function tryClassifyJsxElementName(token) { - switch (token.parent && token.parent.kind) { - case 243 /* JsxOpeningElement */: - if (token.parent.tagName === token) { - return 19 /* jsxOpenTagName */; - } - break; - case 245 /* JsxClosingElement */: - if (token.parent.tagName === token) { - return 20 /* jsxCloseTagName */; - } - break; - case 242 /* JsxSelfClosingElement */: - if (token.parent.tagName === token) { - return 21 /* jsxSelfClosingTagName */; - } - break; - case 246 /* JsxAttribute */: - if (token.parent.name === token) { - return 22 /* jsxAttribute */; - } - break; - } - return undefined; - } - // 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, token) { - if (ts.isKeyword(tokenKind)) { - return 3 /* keyword */; - } - // Special case < and > If they appear in a generic context they are punctuation, - // not operators. - if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { - // 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 && ts.getTypeArgumentOrTypeParameterList(token.parent)) { - return 10 /* punctuation */; - } - } - if (ts.isPunctuation(tokenKind)) { - if (token) { - if (tokenKind === 56 /* EqualsToken */) { - // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 218 /* VariableDeclaration */ || - token.parent.kind === 145 /* PropertyDeclaration */ || - token.parent.kind === 142 /* Parameter */ || - token.parent.kind === 246 /* JsxAttribute */) { - return 5 /* operator */; - } - } - if (token.parent.kind === 187 /* BinaryExpression */ || - token.parent.kind === 185 /* PrefixUnaryExpression */ || - token.parent.kind === 186 /* PostfixUnaryExpression */ || - token.parent.kind === 188 /* ConditionalExpression */) { - return 5 /* operator */; - } - } - return 10 /* punctuation */; - } - else if (tokenKind === 8 /* NumericLiteral */) { - return 4 /* numericLiteral */; - } - else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 166 /* StringLiteralType */) { - return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; - } - else if (tokenKind === 10 /* RegularExpressionLiteral */) { - // TODO: we should get another classification type for these literals. - return 6 /* stringLiteral */; - } - else if (ts.isTemplateLiteralKind(tokenKind)) { - // TODO (drosen): we should *also* get another classification type for these literals. - return 6 /* stringLiteral */; - } - else if (tokenKind === 244 /* JsxText */) { - return 23 /* jsxText */; - } - else if (tokenKind === 69 /* Identifier */) { - if (token) { - switch (token.parent.kind) { - case 221 /* ClassDeclaration */: - if (token.parent.name === token) { - return 11 /* className */; - } - return; - case 141 /* TypeParameter */: - if (token.parent.name === token) { - return 15 /* typeParameterName */; - } - return; - case 222 /* InterfaceDeclaration */: - if (token.parent.name === token) { - return 13 /* interfaceName */; - } - return; - case 224 /* EnumDeclaration */: - if (token.parent.name === token) { - return 12 /* enumName */; - } - return; - case 225 /* ModuleDeclaration */: - if (token.parent.name === token) { - return 14 /* moduleName */; - } - return; - case 142 /* Parameter */: - if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; - } - return; - } - } - return 2 /* identifier */; - } - } - function processElement(element) { - if (!element) { - return; - } - // Ignore nodes that don't intersect the original span to classify. - if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { - checkForClassificationCancellation(element.kind); - var children = element.getChildren(sourceFile); - for (var i = 0, n = children.length; i < n; i++) { - var child = children[i]; - if (!tryClassifyNode(child)) { - // Recurse into our child nodes. - processElement(child); - } - } - } - } + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getOutliningSpans(fileName) { // doesn't use compiler - no need to synchronize with host @@ -58010,12 +73714,12 @@ var ts; } } function getIndentationAtPosition(fileName, position, editorOptions) { - var start = new Date().getTime(); + var start = ts.timestamp(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); - start = new Date().getTime(); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); - log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { @@ -58039,93 +73743,8 @@ var ts; } return []; } - /** - * Checks if position points to a valid position to add JSDoc comments, and if so, - * returns the appropriate template. Otherwise returns an empty string. - * Valid positions are - * - outside of comments, statements, and expressions, and - * - preceding a: - * - function/constructor/method declaration - * - class declarations - * - variable statements - * - namespace declarations - * - * Hosts should ideally check that: - * - The line is all whitespace up to 'position' before performing the insertion. - * - If the keystroke sequence "/\*\*" induced the call, we also check that the next - * non-whitespace character is '*', which (approximately) indicates whether we added - * the second '*' to complete an existing (JSDoc) comment. - * @param fileName The file in which to perform the check. - * @param position The (character-indexed) position in the file where the check should - * be performed. - */ function getDocCommentTemplateAtPosition(fileName, position) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { - return undefined; - } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); - var tokenStart = tokenAtPos.getStart(); - if (!tokenAtPos || tokenStart < position) { - return undefined; - } - // TODO: add support for: - // - enums/enum members - // - interfaces - // - property declarations - // - potentially property assignments - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - case 221 /* ClassDeclaration */: - case 200 /* VariableStatement */: - break findOwner; - case 256 /* SourceFile */: - return undefined; - case 225 /* ModuleDeclaration */: - // If in walking up the tree, we hit a a nested namespace declaration, - // then we must be somewhere within a dotted namespace name; however we don't - // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 225 /* ModuleDeclaration */) { - return undefined; - } - break findOwner; - } - } - if (!commentOwner || commentOwner.getStart() < position) { - return undefined; - } - var parameters = getParametersForJsDocOwningNode(commentOwner); - var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); - var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; - var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); - var newLine = ts.getNewLineOrDefaultFromHost(host); - var docParams = ""; - for (var i = 0, numParams = parameters.length; i < numParams; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 69 /* Identifier */ ? - currentName.text : - "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; - } - // A doc comment consists of the following - // * The opening comment line - // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) - // * the '@param'-tagged lines - // * TODO: other tags. - // * the closing comment line - // * if the caret was directly in front of the object, then we add an extra line and indentation. - var preamble = "/**" + newLine + - indentationStr + " * "; - var result = preamble + newLine + - docParams + - indentationStr + " */" + - (tokenStart === position ? newLine + indentationStr : ""); - return { newText: result, caretOffset: preamble.length }; + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -58150,46 +73769,6 @@ var ts; } return true; } - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 200 /* VariableStatement */) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); - } - } - return emptyArray; - } - /** - * Digs into an an initializer or RHS operand of an assignment operation - * to get the parameters of an apt signature corresponding to a - * function expression or a class expression. - * - * @param rightHandSide the expression which may contain an appropriate set of parameters - * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. - */ - function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178 /* ParenthesizedExpression */) { - rightHandSide = rightHandSide.expression; - } - switch (rightHandSide.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - return rightHandSide.parameters; - case 192 /* ClassExpression */: - for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148 /* Constructor */) { - return member.parameters; - } - } - break; - } - return emptyArray; - } function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually // treat it as a semantic operation here. This is because we expect our host to call @@ -58231,7 +73810,7 @@ var ts; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInsideComment(sourceFile, token, matchPosition)) { continue; } var descriptor = undefined; @@ -58314,104 +73893,10 @@ var ts; (char >= 48 /* _0 */ && char <= 57 /* _9 */); } } - function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* StringLiteralType */ ? node.parent : node; - var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256 /* StringLiteral */) { - return type; - } - return undefined; - } function getRenameInfo(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); - var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - if (node) { - if (node.kind === 69 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isThis(node)) { - var symbol = typeChecker.getSymbolAtLocation(node); - // Only allow a symbol to be renamed if it actually has at least one declaration. - if (symbol) { - var declarations = symbol.getDeclarations(); - if (declarations && declarations.length > 0) { - // Disallow rename for elements that are defined in the standard TypeScript library. - if (ts.forEach(declarations, isDefinedInLibraryFile)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - var kind = getSymbolKind(symbol, node); - if (kind) { - return { - canRename: true, - kind: kind, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), - kindModifiers: getSymbolModifiers(symbol), - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - else if (node.kind === 9 /* StringLiteral */) { - var type = getStringLiteralTypeForNode(node, typeChecker); - if (type) { - if (isDefinedInLibraryFile(node)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - else { - var displayName = ts.stripQuotes(type.text); - return { - canRename: true, - kind: ScriptElementKind.variableElement, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: displayName, - kindModifiers: ScriptElementKindModifier.none, - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - } - } - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); - function getRenameInfoError(localizedErrorMessage) { - return { - canRename: false, - localizedErrorMessage: localizedErrorMessage, - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; - } - function isDefinedInLibraryFile(declaration) { - if (defaultLibFileName) { - var sourceFile_2 = declaration.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (canonicalName === canonicalDefaultLibName) { - return true; - } - } - return false; - } - function createTriggerSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var width = node.getWidth(sourceFile); - if (node.kind === 9 /* StringLiteral */) { - // Exclude the quotes - start += 1; - width -= 2; - } - return ts.createTextSpan(start, width); - } + return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } return { dispose: dispose, @@ -58425,9 +73910,11 @@ var ts; getEncodedSemanticClassifications: getEncodedSemanticClassifications, getCompletionsAtPosition: getCompletionsAtPosition, getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, findReferences: findReferences, @@ -58450,6 +73937,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, + getSourceFile: getSourceFile, getProgram: getProgram }; } @@ -58463,7 +73951,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -58501,426 +73989,6 @@ var ts; node.parent.kind === 173 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } - /// Classifier - function createClassifier() { - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false); - /// We do not have a full parser support to know when we should parse a regex or not - /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where - /// we have a series of divide operator. this list allows us to be more accurate by ruling out - /// locations where a regexp cannot exist. - var noRegexTable = []; - noRegexTable[69 /* Identifier */] = true; - noRegexTable[9 /* StringLiteral */] = true; - noRegexTable[8 /* NumericLiteral */] = true; - noRegexTable[10 /* RegularExpressionLiteral */] = true; - noRegexTable[97 /* ThisKeyword */] = true; - noRegexTable[41 /* PlusPlusToken */] = true; - noRegexTable[42 /* MinusMinusToken */] = true; - noRegexTable[18 /* CloseParenToken */] = true; - noRegexTable[20 /* CloseBracketToken */] = true; - noRegexTable[16 /* CloseBraceToken */] = true; - noRegexTable[99 /* TrueKeyword */] = true; - noRegexTable[84 /* FalseKeyword */] = true; - // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) - // classification on template strings. Because of the context free nature of templates, - // the only precise way to classify a template portion would be by propagating the stack across - // lines, just as we do with the end-of-line state. However, this is a burden for implementers, - // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead - // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. - // Situations in which this fails are - // 1) When template strings are nested across different lines: - // `hello ${ `world - // ` }` - // - // Where on the second line, you will get the closing of a template, - // a closing curly, and a new template. - // - // 2) When substitution expressions have curly braces and the curly brace falls on the next line: - // `hello ${ () => { - // return "world" } } ` - // - // Where on the second line, you will get the 'return' keyword, - // a string literal, and a template end consisting of '} } `'. - var templateStack = []; - /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 /* GetKeyword */ || - keyword2 === 131 /* SetKeyword */ || - keyword2 === 121 /* ConstructorKeyword */ || - keyword2 === 113 /* StaticKeyword */) { - // Allow things like "public get", "public constructor" and "public static". - // These are all legal. - return true; - } - // Any other keyword following "public" is actually an identifier an not a real - // keyword. - return false; - } - // Assume any other keyword combination is legal. This can be refined in the future - // if there are more cases we want the classifier to be better at. - return true; - } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0, n = dense.length; i < n; i += 3) { - var start = dense[i]; - var length_3 = dense[i + 1]; - var type = dense[i + 2]; - // Make a whitespace entry between the last item and this one. - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); - } - } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1 /* comment */: return TokenClass.Comment; - case 3 /* keyword */: return TokenClass.Keyword; - case 4 /* numericLiteral */: return TokenClass.NumberLiteral; - case 5 /* operator */: return TokenClass.Operator; - case 6 /* stringLiteral */: return TokenClass.StringLiteral; - case 8 /* whiteSpace */: return TokenClass.Whitespace; - case 10 /* punctuation */: return TokenClass.Punctuation; - case 2 /* identifier */: - case 11 /* className */: - case 12 /* enumName */: - case 13 /* interfaceName */: - case 14 /* moduleName */: - case 15 /* typeParameterName */: - case 16 /* typeAliasName */: - case 9 /* text */: - case 17 /* parameterName */: - default: - return TokenClass.Identifier; - } - } - function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - 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 getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; - var token = 0 /* Unknown */; - var lastNonTriviaToken = 0 /* Unknown */; - // Empty out the template stack for reuse. - while (templateStack.length > 0) { - templateStack.pop(); - } - // If we're in a string literal, then prepend: "\ - // (and a newline). That way when we lex we'll think we're still in a string literal. - // - // If we're in a multiline comment, then prepend: /* - // (and a newline). That way when we lex we'll think we're still in a multiline comment. - switch (lexState) { - case 3 /* InDoubleQuoteStringLiteral */: - text = "\"\\\n" + text; - offset = 3; - break; - case 2 /* InSingleQuoteStringLiteral */: - text = "'\\\n" + text; - offset = 3; - break; - case 1 /* InMultiLineCommentTrivia */: - text = "/*\n" + text; - offset = 3; - break; - case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: - text = "`\n" + text; - offset = 2; - break; - case 5 /* InTemplateMiddleOrTail */: - text = "}\n" + text; - offset = 2; - // fallthrough - case 6 /* InTemplateSubstitutionPosition */: - templateStack.push(12 /* TemplateHead */); - break; - } - scanner.setText(text); - var result = { - endOfLineState: 0 /* None */, - spans: [] - }; - // We can run into an unfortunate interaction between the lexical and syntactic classifier - // when the user is typing something generic. Consider the case where the user types: - // - // Foo tokens. It's a weak heuristic, but should - // work well enough in practice. - var angleBracketStack = 0; - do { - token = scanner.scan(); - if (!ts.isTrivia(token)) { - if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { - token = 10 /* RegularExpressionLiteral */; - } - } - else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { - token = 69 /* Identifier */; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - // We have two keywords in a row. Only treat the second as a keyword if - // it's a sequence that could legally occur in the language. Otherwise - // treat it as an identifier. This way, if someone writes "private var" - // we recognize that 'var' is actually an identifier here. - token = 69 /* Identifier */; - } - else if (lastNonTriviaToken === 69 /* Identifier */ && - token === 25 /* LessThanToken */) { - // Could be the start of something generic. Keep track of that by bumping - // up the current count of generic contexts we may be in. - angleBracketStack++; - } - else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { - // If we think we're currently in something generic, then mark that that - // generic entity is complete. - angleBracketStack--; - } - else if (token === 117 /* AnyKeyword */ || - token === 132 /* StringKeyword */ || - token === 130 /* NumberKeyword */ || - token === 120 /* BooleanKeyword */ || - token === 133 /* SymbolKeyword */) { - if (angleBracketStack > 0 && !syntacticClassifierAbsent) { - // If it looks like we're could be in something generic, don't classify this - // as a keyword. We may just get overwritten by the syntactic classifier, - // causing a noisy experience for the user. - token = 69 /* Identifier */; - } - } - else if (token === 12 /* TemplateHead */) { - templateStack.push(token); - } - else if (token === 15 /* OpenBraceToken */) { - // If we don't have anything on the template stack, - // then we aren't trying to keep track of a previously scanned template head. - if (templateStack.length > 0) { - templateStack.push(token); - } - } - else if (token === 16 /* CloseBraceToken */) { - // If we don't have anything on the template stack, - // then we aren't trying to keep track of a previously scanned template head. - if (templateStack.length > 0) { - var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12 /* TemplateHead */) { - token = scanner.reScanTemplateToken(); - // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 14 /* TemplateTail */) { - templateStack.pop(); - } - else { - ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); - } - } - else { - ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); - templateStack.pop(); - } - } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1 /* EndOfFileToken */); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9 /* StringLiteral */ || token === 166 /* StringLiteralType */) { - // Check to see if we finished up on a multiline string literal. - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { - numBackslashes++; - } - // If we have an odd number of backslashes, then the multiline string is unclosed - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 /* doubleQuote */ - ? 3 /* InDoubleQuoteStringLiteral */ - : 2 /* InSingleQuoteStringLiteral */; - } - } - } - else if (token === 3 /* MultiLineCommentTrivia */) { - // Check to see if the multiline comment was unclosed. - if (scanner.isUnterminated()) { - result.endOfLineState = 1 /* InMultiLineCommentTrivia */; - } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 14 /* TemplateTail */) { - result.endOfLineState = 5 /* InTemplateMiddleOrTail */; - } - else if (token === 11 /* NoSubstitutionTemplateLiteral */) { - result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } - } - } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { - result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; - } - } - } - function addResult(start, end, classification) { - if (classification === 8 /* whiteSpace */) { - // Don't bother with whitespace classifications. They're not needed. - return; - } - 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; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); - } - } - } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: - case 91 /* InstanceOfKeyword */: - case 90 /* InKeyword */: - case 116 /* AsKeyword */: - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: - case 46 /* AmpersandToken */: - case 48 /* CaretToken */: - case 47 /* BarToken */: - case 51 /* AmpersandAmpersandToken */: - case 52 /* BarBarToken */: - case 67 /* BarEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 56 /* EqualsToken */: - case 24 /* CommaToken */: - return true; - default: - return false; - } - } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: - return true; - default: - return false; - } - } - function isKeyword(token) { - return token >= 70 /* FirstKeyword */ && token <= 138 /* LastKeyword */; - } - function classFromKind(token) { - if (isKeyword(token)) { - return 3 /* keyword */; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5 /* operator */; - } - else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { - return 10 /* punctuation */; - } - switch (token) { - case 8 /* NumericLiteral */: - return 4 /* numericLiteral */; - case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: - return 6 /* stringLiteral */; - case 10 /* RegularExpressionLiteral */: - return 7 /* regularExpressionLiteral */; - case 7 /* ConflictMarkerTrivia */: - case 3 /* MultiLineCommentTrivia */: - case 2 /* SingleLineCommentTrivia */: - return 1 /* comment */; - case 5 /* WhitespaceTrivia */: - case 4 /* NewLineTrivia */: - return 8 /* whiteSpace */; - case 69 /* Identifier */: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6 /* stringLiteral */; - } - return 2 /* identifier */; - } - } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; - } - ts.createClassifier = createClassifier; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript * node package. @@ -58935,13 +74003,7 @@ var ts; } ts.getDefaultLibFilePath = getDefaultLibFilePath; function initializeServices() { - ts.objectAllocator = { - getNodeConstructor: function () { return NodeObject; }, - getSourceFileConstructor: function () { return SourceFileObject; }, - getSymbolConstructor: function () { return SymbolObject; }, - getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } - }; + ts.objectAllocator = getServicesObjectAllocator(); } initializeServices(); })(ts || (ts = {})); @@ -59184,7 +74246,7 @@ var ts; return spanInNode(binaryExpression.left); } } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { case 204 /* DoStatement */: // Set span as if on while keyword @@ -59269,7 +74331,7 @@ var ts; // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' if (variableDeclaration.initializer || - (variableDeclaration.flags & 1 /* Export */) || + ts.hasModifier(variableDeclaration, 1 /* Export */) || variableDeclaration.parent.parent.kind === 208 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } @@ -59285,7 +74347,7 @@ var ts; function canHaveSpanInParameterDeclaration(parameter) { // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 4 /* Public */) || !!(parameter.flags & 8 /* Private */); + ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */); } function spanInParameterDeclaration(parameter) { if (ts.isBindingPattern(parameter.name)) { @@ -59309,7 +74371,7 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1 /* Export */) || + return ts.hasModifier(functionDeclaration, 1 /* Export */) || (functionDeclaration.parent.kind === 221 /* ClassDeclaration */ && functionDeclaration.kind !== 148 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { @@ -59562,7 +74624,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = this; +var debugObjectHost = new Function("return this")(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -59615,7 +74677,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.lookUp(resolutionsInFile, name); + var result = ts.getProperty(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -59626,7 +74688,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -59701,11 +74763,21 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return this.shimHost.getDirectories(path); + return JSON.parse(this.shimHost.getDirectories(path)); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -59719,7 +74791,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = Date.now(); + var time = ts.timestamp(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { // Check no more than once every 10 ms. @@ -59772,6 +74844,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -59779,11 +74854,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = Date.now(); + start = ts.timestamp(); } var result = action(); if (logPerformance) { - var end = Date.now(); + var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -59975,6 +75050,15 @@ var ts; var _this = this; return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); @@ -60064,9 +75148,9 @@ var ts; }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ - LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; @@ -60169,6 +75253,13 @@ var ts; }; }); }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -60304,5 +75395,5 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "1.9"; +var toolsVersion = "2.1"; /* tslint:enable:no-unused-variable */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 4ffdd868f16..e9c209674b5 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -14,9 +14,12 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - interface Map { + interface MapLike { [index: string]: T; } + interface Map extends MapLike { + __mapBrand: any; + } type Path = string & { __pathBrand: any; }; @@ -199,7 +202,7 @@ declare namespace ts { IntersectionType = 163, ParenthesizedType = 164, ThisType = 165, - StringLiteralType = 166, + LiteralType = 166, ObjectBindingPattern = 167, ArrayBindingPattern = 168, BindingElement = 169, @@ -315,10 +318,18 @@ declare namespace ts { JSDocTypedefTag = 279, JSDocPropertyTag = 280, JSDocTypeLiteral = 281, - SyntaxList = 282, - Count = 283, + JSDocLiteralType = 282, + JSDocNullKeyword = 283, + JSDocUndefinedKeyword = 284, + JSDocNeverKeyword = 285, + SyntaxList = 286, + NotEmittedStatement = 287, + PartiallyEmittedExpression = 288, + Count = 289, FirstAssignment = 56, LastAssignment = 68, + FirstCompoundAssignment = 57, + LastCompoundAssignment = 68, FirstReservedWord = 70, LastReservedWord = 105, FirstKeyword = 70, @@ -341,11 +352,44 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 139, FirstJSDocNode = 257, - LastJSDocNode = 281, + LastJSDocNode = 282, FirstJSDocTagNode = 273, - LastJSDocTagNode = 281, + LastJSDocTagNode = 285, } enum NodeFlags { + None = 0, + Let = 1, + Const = 2, + NestedNamespace = 4, + Synthesized = 8, + Namespace = 16, + ExportContext = 32, + ContainsThis = 64, + HasImplicitReturn = 128, + HasExplicitReturn = 256, + GlobalAugmentation = 512, + HasClassExtends = 1024, + HasDecorators = 2048, + HasParamDecorators = 4096, + HasAsyncFunctions = 8192, + HasJsxSpreadAttributes = 16384, + DisallowInContext = 32768, + YieldContext = 65536, + DecoratorContext = 131072, + AwaitContext = 262144, + ThisNodeHasError = 524288, + JavaScriptFile = 1048576, + ThisNodeOrAnySubNodesHasError = 2097152, + HasAggregatedChildData = 4194304, + BlockScoped = 3, + ReachabilityCheckFlags = 384, + EmitHelperFlags = 31744, + ReachabilityAndEmitFlags = 32128, + ContextFlags = 1540096, + TypeExcludesFlags = 327680, + } + type ModifiersArray = NodeArray; + enum ModifierFlags { None = 0, Export = 1, Ambient = 2, @@ -357,36 +401,11 @@ declare namespace ts { Abstract = 128, Async = 256, Default = 512, - Let = 1024, Const = 2048, - Namespace = 4096, - ExportContext = 8192, - ContainsThis = 16384, - HasImplicitReturn = 32768, - HasExplicitReturn = 65536, - GlobalAugmentation = 131072, - HasClassExtends = 262144, - HasDecorators = 524288, - HasParamDecorators = 1048576, - HasAsyncFunctions = 2097152, - DisallowInContext = 4194304, - YieldContext = 8388608, - DecoratorContext = 16777216, - AwaitContext = 33554432, - ThisNodeHasError = 67108864, - JavaScriptFile = 134217728, - ThisNodeOrAnySubNodesHasError = 268435456, - HasAggregatedChildData = 536870912, - HasJsxSpreadAttribute = 1073741824, - Modifier = 1023, + HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 92, - BlockScoped = 3072, - ReachabilityCheckFlags = 98304, - EmitHelperFlags = 3932160, - ReachabilityAndEmitFlags = 4030464, - ContextFlags = 197132288, - TypeExcludesFlags = 41943040, + NonPublicAccessibilityModifier = 24, } enum JsxFlags { None = 0, @@ -403,18 +422,21 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } - interface NodeArray extends Array, TextRange { + interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface ModifiersArray extends NodeArray { - flags: NodeFlags; + interface Token extends Node { + __tokenTag: any; } - interface Modifier extends Node { + interface Modifier extends Token { } interface Identifier extends PrimaryExpression { text: string; originalKeywordKind?: SyntaxKind; } + interface TransientIdentifier extends Identifier { + resolvedSymbol: Symbol; + } interface QualifiedName extends Node { left: EntityName; right: Identifier; @@ -450,9 +472,10 @@ declare namespace ts { } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { } + type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { parent?: VariableDeclarationList; - name: Identifier | BindingPattern; + name: BindingName; type?: TypeNode; initializer?: Expression; } @@ -461,7 +484,7 @@ declare namespace ts { } interface ParameterDeclaration extends Declaration { dotDotDotToken?: Node; - name: Identifier | BindingPattern; + name: BindingName; questionToken?: Node; type?: TypeNode; initializer?: Expression; @@ -469,7 +492,7 @@ declare namespace ts { interface BindingElement extends Declaration { propertyName?: PropertyName; dotDotDotToken?: Node; - name: Identifier | BindingPattern; + name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { @@ -488,6 +511,7 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { _propertyAssignmentBrand: any; name: PropertyName; @@ -512,11 +536,14 @@ declare namespace ts { name: PropertyName; } interface BindingPattern extends Node { - elements: NodeArray; + elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + elements: NodeArray; } + type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + elements: NodeArray; } /** * Several node kinds share function-like features such as a signature, @@ -604,8 +631,9 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { + interface LiteralTypeNode extends TypeNode { _stringLiteralTypeBrand: any; + literal: Expression; } interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; @@ -615,6 +643,7 @@ declare namespace ts { contextualType?: Type; } interface OmittedExpression extends Expression { + _omittedExpressionBrand: any; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -688,9 +717,14 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface NumericLiteral extends LiteralExpression { + _numericLiteralBrand: any; + trailingComment?: string; + } interface TemplateLiteralFragment extends LiteralLikeNode { _templateLiteralFragmentBrand: any; } + type Template = TemplateExpression | LiteralExpression; interface TemplateExpression extends PrimaryExpression { head: TemplateLiteralFragment; templateSpans: NodeArray; @@ -708,14 +742,28 @@ declare namespace ts { interface SpreadElementExpression extends Expression { expression: Expression; } - interface ObjectLiteralExpression extends PrimaryExpression, Declaration { - properties: NodeArray; + /** + * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to + * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be + * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type + * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) + **/ + interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { + properties: NodeArray; } + interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + } + type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; + type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; name: Identifier; } - type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; + /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ + interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { + _propertyAccessExpressionLikeQualifiedNameBrand?: any; + expression: EntityNameExpression; + } interface ElementAccessExpression extends MemberExpression { expression: LeftHandSideExpression; argumentExpression?: Expression; @@ -733,7 +781,7 @@ declare namespace ts { } interface TaggedTemplateExpression extends MemberExpression { tag: LeftHandSideExpression; - template: LiteralExpression | TemplateExpression; + template: Template; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { @@ -763,9 +811,10 @@ declare namespace ts { _selfClosingElementBrand?: any; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { name: Identifier; - initializer?: Expression; + initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { expression: Expression; @@ -814,17 +863,18 @@ declare namespace ts { interface WhileStatement extends IterationStatement { expression: Expression; } + type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { - initializer?: VariableDeclarationList | Expression; + initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; + initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; + initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { @@ -910,7 +960,7 @@ declare namespace ts { type: TypeNode; } interface EnumMember extends Declaration { - name: DeclarationName; + name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { @@ -918,6 +968,7 @@ declare namespace ts { members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; + type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; body?: ModuleBlock | ModuleDeclaration; @@ -925,9 +976,10 @@ declare namespace ts { interface ModuleBlock extends Node, Statement { statements: NodeArray; } + type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { name: Identifier; - moduleReference: EntityName | ExternalModuleReference; + moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { expression?: Expression; @@ -936,9 +988,10 @@ declare namespace ts { importClause?: ImportClause; moduleSpecifier: Expression; } + type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { name?: Identifier; - namedBindings?: NamespaceImport | NamedImports; + namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { name: Identifier; @@ -1006,7 +1059,7 @@ declare namespace ts { type: JSDocType; } interface JSDocRecordType extends JSDocType, TypeLiteralNode { - members: NodeArray; + literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { name: EntityName; @@ -1028,17 +1081,22 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } + interface JSDocLiteralType extends JSDocType { + literal: LiteralTypeNode; + } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; type?: JSDocType; } - interface JSDocComment extends Node { - tags: NodeArray; + interface JSDoc extends Node { + tags: NodeArray | undefined; + comment: string | undefined; } interface JSDocTag extends Node { atToken: Node; tagName: Identifier; + comment: string | undefined; } interface JSDocTemplateTag extends JSDocTag { typeParameters: NodeArray; @@ -1063,9 +1121,13 @@ declare namespace ts { jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; + /** the parameter name, if provided *after* the type (JSDoc-standard) */ postParameterName?: Identifier; + /** the parameter name, regardless of the location it was provided */ + parameterName: Identifier; isBracketed: boolean; } enum FlowFlags { @@ -1106,6 +1168,11 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } interface AmdDependency { path: string; name: string; @@ -1147,6 +1214,7 @@ declare namespace ts { * @param path The path to test. */ fileExists(path: string): boolean; + readFile(path: string): string; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1263,6 +1331,7 @@ declare namespace ts { getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; + getAmbientModules(): Symbol[]; } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1302,6 +1371,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, InFirstTypeArgument = 256, + InTypeAlias = 512, } enum SymbolFormatFlags { None = 0, @@ -1360,18 +1430,18 @@ declare namespace ts { Enum = 384, Variable = 3, Value = 107455, - Type = 793056, - Namespace = 1536, + Type = 793064, + Namespace = 1920, Module = 1536, Accessor = 98304, FunctionScopedVariableExcludes = 107454, BlockScopedVariableExcludes = 107455, ParameterExcludes = 107455, PropertyExcludes = 0, - EnumMemberExcludes = 107455, + EnumMemberExcludes = 900095, FunctionExcludes = 106927, ClassExcludes = 899519, - InterfaceExcludes = 792960, + InterfaceExcludes = 792968, RegularEnumExcludes = 899327, ConstEnumExcludes = 899967, ValueModuleExcludes = 106639, @@ -1379,8 +1449,8 @@ declare namespace ts { MethodExcludes = 99263, GetAccessorExcludes = 41919, SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, + TypeParameterExcludes = 530920, + TypeAliasExcludes = 793064, AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, @@ -1400,48 +1470,65 @@ declare namespace ts { exports?: SymbolTable; globalExports?: SymbolTable; } - interface SymbolTable { - [index: string]: Symbol; - } + type SymbolTable = Map; enum TypeFlags { Any = 1, String = 2, Number = 4, Boolean = 8, - Void = 16, - Undefined = 32, - Null = 64, - Enum = 128, - StringLiteral = 256, - TypeParameter = 512, - Class = 1024, - Interface = 2048, - Reference = 4096, - Tuple = 8192, - Union = 16384, - Intersection = 32768, - Anonymous = 65536, - Instantiated = 131072, - ObjectLiteral = 524288, - ESSymbol = 16777216, - ThisType = 33554432, - ObjectLiteralPatternWithComputedProperties = 67108864, - Never = 134217728, - StringLike = 258, - NumberLike = 132, - ObjectType = 80896, - UnionOrIntersection = 49152, - StructuredType = 130048, - Narrowable = 16908175, + Enum = 16, + StringLiteral = 32, + NumberLiteral = 64, + BooleanLiteral = 128, + EnumLiteral = 256, + ESSymbol = 512, + Void = 1024, + Undefined = 2048, + Null = 4096, + Never = 8192, + TypeParameter = 16384, + Class = 32768, + Interface = 65536, + Reference = 131072, + Tuple = 262144, + Union = 524288, + Intersection = 1048576, + Anonymous = 2097152, + Instantiated = 4194304, + ThisType = 268435456, + ObjectLiteralPatternWithComputedProperties = 536870912, + Literal = 480, + StringOrNumberLiteral = 96, + PossiblyFalsy = 7406, + StringLike = 34, + NumberLike = 340, + BooleanLike = 136, + EnumLike = 272, + ObjectType = 2588672, + UnionOrIntersection = 1572864, + StructuredType = 4161536, + StructuredOrTypeParameter = 4177920, + Narrowable = 4178943, + NotUnionOrUnit = 2589191, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { flags: TypeFlags; symbol?: Symbol; pattern?: DestructuringPattern; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; } - interface StringLiteralType extends Type { + interface LiteralType extends Type { text: string; + freshType?: LiteralType; + regularType?: LiteralType; + } + interface EnumType extends Type { + memberTypes: Map; + } + interface EnumLiteralType extends LiteralType { + baseType: EnumType & UnionType; } interface ObjectType extends Type { } @@ -1464,9 +1551,6 @@ declare namespace ts { } interface GenericType extends InterfaceType, TypeReference { } - interface TupleType extends ObjectType { - elementTypes: Type[]; - } interface UnionOrIntersectionType extends Type { types: Type[]; } @@ -1531,7 +1615,7 @@ declare namespace ts { NodeJs = 2, } type RootPaths = string[]; - type PathSubstitutions = Map; + type PathSubstitutions = MapLike; type TsConfigOnlyOptions = RootPaths | PathSubstitutions; type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; interface CompilerOptions { @@ -1548,6 +1632,7 @@ declare namespace ts { emitDecoratorMetadata?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; inlineSourceMap?: boolean; inlineSources?: boolean; isolatedModules?: boolean; @@ -1656,7 +1741,7 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; - wildcardDirectories?: Map; + wildcardDirectories?: MapLike; } enum WatchDirectoryFlags { None = 0, @@ -1664,7 +1749,7 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - wildcardDirectories: Map; + wildcardDirectories: MapLike; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1673,6 +1758,7 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; realpath?(path: string): string; getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; } interface ResolvedModule { resolvedFileName: string; @@ -1696,7 +1782,6 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; - getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getDirectories(path: string): string[]; @@ -1708,6 +1793,7 @@ declare namespace ts { * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + getEnvironmentVariable?(name: string): string; } interface TextSpan { start: number; @@ -1782,6 +1868,7 @@ declare namespace ts { reScanSlashToken(): SyntaxKind; reScanTemplateToken(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; + scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; scanJSDocToken(): SyntaxKind; @@ -1804,6 +1891,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; /** Optionally, get the shebang */ @@ -1842,8 +1933,8 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; - function startsWith(str: string, prefix: string): boolean; - function endsWith(str: string, suffix: string): boolean; + function getCombinedModifierFlags(node: Node): ModifierFlags; + function getCombinedNodeFlags(node: Node): NodeFlags; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -1854,9 +1945,13 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version: string; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; + const version = "2.1.0"; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -1868,16 +1963,22 @@ declare namespace ts { function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** - * Given a set of options and a set of root files, returns the set of type directive names + * Given a set of options, returns the set of type directive names * that should be included for this program automatically. * This list could either come from the config file, * or from enumerating the types root + initial secondary types lookup location. * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1905,7 +2006,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -1916,8 +2017,6 @@ declare namespace ts { }; } declare namespace ts { - /** The version of the language service API */ - const servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -1983,7 +2082,7 @@ declare namespace ts { * change range cannot be determined. However, in that case, incremental parsing will * not happen and the entire document will be re - parsed. */ - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; /** Releases all resources held by this script snapshot */ dispose?(): void; } @@ -2016,6 +2115,9 @@ declare namespace ts { trace?(s: string): void; error?(s: string): void; useCaseSensitiveFileNames?(): boolean; + readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readFile?(path: string, encoding?: string): string; + fileExists?(path: string): boolean; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2038,6 +2140,7 @@ declare namespace ts { getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; @@ -2046,12 +2149,13 @@ declare namespace ts { findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; @@ -2112,15 +2216,19 @@ declare namespace ts { isWriteAccess: boolean; isDefinition: boolean; } + interface ImplementationLocation { + textSpan: TextSpan; + fileName: string; + } interface DocumentHighlights { fileName: string; highlightSpans: HighlightSpan[]; } namespace HighlightSpanKind { - const none: string; - const definition: string; - const reference: string; - const writtenReference: string; + const none = "none"; + const definition = "definition"; + const reference = "reference"; + const writtenReference = "writtenReference"; } interface HighlightSpan { fileName?: string; @@ -2159,8 +2267,10 @@ declare namespace ts { InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; [s: string]: boolean | number | string | undefined; @@ -2173,8 +2283,11 @@ declare namespace ts { containerKind: string; containerName: string; } + interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { + displayParts: SymbolDisplayPart[]; + } interface ReferencedSymbol { - definition: DefinitionInfo; + definition: ReferencedSymbolDefinitionInfo; references: ReferenceEntry[]; } enum SymbolDisplayPartKind { @@ -2262,6 +2375,12 @@ declare namespace ts { kind: string; kindModifiers: string; sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. It will be + * set if the required span differs from the one generated by the default replacement behavior and should + * be used in that case + */ + replacementSpan?: TextSpan; } interface CompletionEntryDetails { name: string; @@ -2349,6 +2468,135 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } + namespace ScriptElementKind { + const unknown = ""; + const warning = "warning"; + /** predefined type (void) or keyword (class) */ + const keyword = "keyword"; + /** top level script node */ + const scriptElement = "script"; + /** module foo {} */ + const moduleElement = "module"; + /** class X {} */ + const classElement = "class"; + /** var x = class X {} */ + const localClassElement = "local class"; + /** interface Y {} */ + const interfaceElement = "interface"; + /** type T = ... */ + const typeElement = "type"; + /** enum E */ + const enumElement = "enum"; + const enumMemberElement = "const"; + /** + * Inside module and script only + * const v = .. + */ + const variableElement = "var"; + /** Inside function */ + const localVariableElement = "local var"; + /** + * Inside module and script only + * function f() { } + */ + const functionElement = "function"; + /** Inside function */ + const localFunctionElement = "local function"; + /** class X { [public|private]* foo() {} } */ + const memberFunctionElement = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + const memberGetAccessorElement = "getter"; + const memberSetAccessorElement = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + const memberVariableElement = "property"; + /** class X { constructor() { } } */ + const constructorImplementationElement = "constructor"; + /** interface Y { ():number; } */ + const callSignatureElement = "call"; + /** interface Y { []:number; } */ + const indexSignatureElement = "index"; + /** interface Y { new():Y; } */ + const constructSignatureElement = "construct"; + /** function foo(*Y*: string) */ + const parameterElement = "parameter"; + const typeParameterElement = "type parameter"; + const primitiveType = "primitive type"; + const label = "label"; + const alias = "alias"; + const constElement = "const"; + const letElement = "let"; + const directory = "directory"; + const externalModuleName = "external module name"; + } + namespace ScriptElementKindModifier { + const none = ""; + const publicMemberModifier = "public"; + const privateMemberModifier = "private"; + const protectedMemberModifier = "protected"; + const exportedModifier = "export"; + const ambientModifier = "declare"; + const staticModifier = "static"; + const abstractModifier = "abstract"; + } + class ClassificationTypeNames { + static comment: string; + static identifier: string; + static keyword: string; + static numericLiteral: string; + static operator: string; + static stringLiteral: string; + static whiteSpace: string; + static text: string; + static punctuation: string; + static className: string; + static enumName: string; + static interfaceName: string; + static moduleName: string; + static typeParameterName: string; + static typeAliasName: string; + static parameterName: string; + static docCommentTagName: string; + static jsxOpenTagName: string; + static jsxCloseTagName: string; + static jsxSelfClosingTagName: string; + static jsxAttribute: string; + static jsxText: string; + static jsxAttributeStringLiteralValue: string; + } + 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, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + } +} +declare namespace ts { + function createClassifier(): Classifier; +} +declare namespace ts { /** * The document registry represents a store of SourceFile objects that can be shared between * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) @@ -2412,138 +2660,18 @@ declare namespace ts { type DocumentRegistryBucketKey = string & { __bucketKey: any; }; - namespace ScriptElementKind { - const unknown: string; - const warning: string; - /** predefined type (void) or keyword (class) */ - const keyword: string; - /** top level script node */ - const scriptElement: string; - /** module foo {} */ - const moduleElement: string; - /** class X {} */ - const classElement: string; - /** var x = class X {} */ - const localClassElement: string; - /** interface Y {} */ - const interfaceElement: string; - /** type T = ... */ - const typeElement: string; - /** enum E */ - const enumElement: string; - /** - * Inside module and script only - * const v = .. - */ - const variableElement: string; - /** Inside function */ - const localVariableElement: string; - /** - * Inside module and script only - * function f() { } - */ - const functionElement: string; - /** Inside function */ - const localFunctionElement: string; - /** class X { [public|private]* foo() {} } */ - const memberFunctionElement: string; - /** class X { [public|private]* [get|set] foo:number; } */ - const memberGetAccessorElement: string; - const memberSetAccessorElement: string; - /** - * class X { [public|private]* foo:number; } - * interface Y { foo:number; } - */ - const memberVariableElement: string; - /** class X { constructor() { } } */ - const constructorImplementationElement: string; - /** interface Y { ():number; } */ - const callSignatureElement: string; - /** interface Y { []:number; } */ - const indexSignatureElement: string; - /** interface Y { new():Y; } */ - const constructSignatureElement: string; - /** function foo(*Y*: string) */ - const parameterElement: string; - const typeParameterElement: string; - const primitiveType: string; - const label: string; - const alias: string; - const constElement: string; - const letElement: string; - } - namespace ScriptElementKindModifier { - const none: string; - const publicMemberModifier: string; - const privateMemberModifier: string; - const protectedMemberModifier: string; - const exportedModifier: string; - const ambientModifier: string; - const staticModifier: string; - const abstractModifier: string; - } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - static jsxOpenTagName: string; - static jsxCloseTagName: string; - static jsxSelfClosingTagName: string; - static jsxAttribute: string; - static jsxText: string; - static jsxAttributeStringLiteralValue: string; - } - 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, - docCommentTagName = 18, - jsxOpenTagName = 19, - jsxCloseTagName = 20, - jsxSelfClosingTagName = 21, - jsxAttribute = 22, - jsxText = 23, - jsxAttributeStringLiteralValue = 24, - } - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; - function getDefaultCompilerOptions(): CompilerOptions; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; +} +declare namespace ts { + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; +} +declare namespace ts { interface TranspileOptions { compilerOptions?: CompilerOptions; fileName?: string; reportDiagnostics?: boolean; moduleName?: string; - renamedDependencies?: Map; + renamedDependencies?: MapLike; } interface TranspileOutput { outputText: string; @@ -2552,13 +2680,19 @@ declare namespace ts { } function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; +} +declare namespace ts { + /** The version of the language service API */ + const servicesVersion = "0.5"; + interface DisplayPartsSymbolWriter extends SymbolWriter { + displayParts(): SymbolDisplayPart[]; + } + function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function getDefaultCompilerOptions(): CompilerOptions; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; - function createClassifier(): Classifier; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript * node package. diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 22cbe79129c..14fbdce59a8 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -205,7 +205,7 @@ var ts; SyntaxKind[SyntaxKind["IntersectionType"] = 163] = "IntersectionType"; SyntaxKind[SyntaxKind["ParenthesizedType"] = 164] = "ParenthesizedType"; SyntaxKind[SyntaxKind["ThisType"] = 165] = "ThisType"; - SyntaxKind[SyntaxKind["StringLiteralType"] = 166] = "StringLiteralType"; + SyntaxKind[SyntaxKind["LiteralType"] = 166] = "LiteralType"; // Binding patterns SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 167] = "ObjectBindingPattern"; SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 168] = "ArrayBindingPattern"; @@ -334,13 +334,22 @@ var ts; SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 279] = "JSDocTypedefTag"; SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 280] = "JSDocPropertyTag"; SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 281] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 282] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 283] = "JSDocNullKeyword"; + SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 284] = "JSDocUndefinedKeyword"; + SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 285] = "JSDocNeverKeyword"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 282] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 283] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 289] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 57] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 68] = "LastCompoundAssignment"; SyntaxKind[SyntaxKind["FirstReservedWord"] = 70] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 105] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 70] = "FirstKeyword"; @@ -363,58 +372,66 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 139] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 257] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 281] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 282] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 273] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 281] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Export"] = 1] = "Export"; - NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; - NodeFlags[NodeFlags["Public"] = 4] = "Public"; - NodeFlags[NodeFlags["Private"] = 8] = "Private"; - NodeFlags[NodeFlags["Protected"] = 16] = "Protected"; - NodeFlags[NodeFlags["Static"] = 32] = "Static"; - NodeFlags[NodeFlags["Readonly"] = 64] = "Readonly"; - NodeFlags[NodeFlags["Abstract"] = 128] = "Abstract"; - NodeFlags[NodeFlags["Async"] = 256] = "Async"; - NodeFlags[NodeFlags["Default"] = 512] = "Default"; - NodeFlags[NodeFlags["Let"] = 1024] = "Let"; - NodeFlags[NodeFlags["Const"] = 2048] = "Const"; - NodeFlags[NodeFlags["Namespace"] = 4096] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 8192] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 16384] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 32768] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 65536] = "HasExplicitReturn"; - NodeFlags[NodeFlags["GlobalAugmentation"] = 131072] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasClassExtends"] = 262144] = "HasClassExtends"; - NodeFlags[NodeFlags["HasDecorators"] = 524288] = "HasDecorators"; - NodeFlags[NodeFlags["HasParamDecorators"] = 1048576] = "HasParamDecorators"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 2097152] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["DisallowInContext"] = 4194304] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 8388608] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 16777216] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 33554432] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 67108864] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 134217728] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 268435456] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 536870912] = "HasAggregatedChildData"; - NodeFlags[NodeFlags["HasJsxSpreadAttribute"] = 1073741824] = "HasJsxSpreadAttribute"; - NodeFlags[NodeFlags["Modifier"] = 1023] = "Modifier"; - NodeFlags[NodeFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; - // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - NodeFlags[NodeFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; - NodeFlags[NodeFlags["BlockScoped"] = 3072] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 98304] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["EmitHelperFlags"] = 3932160] = "EmitHelperFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 4030464] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["Let"] = 1] = "Let"; + NodeFlags[NodeFlags["Const"] = 2] = "Const"; + NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; + NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; + NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasClassExtends"] = 1024] = "HasClassExtends"; + NodeFlags[NodeFlags["HasDecorators"] = 2048] = "HasDecorators"; + NodeFlags[NodeFlags["HasParamDecorators"] = 4096] = "HasParamDecorators"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 8192] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["HasJsxSpreadAttributes"] = 16384] = "HasJsxSpreadAttributes"; + NodeFlags[NodeFlags["DisallowInContext"] = 32768] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 65536] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 131072] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 262144] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 524288] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 1048576] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 2097152] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 4194304] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["EmitHelperFlags"] = 31744] = "EmitHelperFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 32128] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 197132288] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 1540096] = "ContextFlags"; // Exclude these flags when parsing a Type - NodeFlags[NodeFlags["TypeExcludesFlags"] = 41943040] = "TypeExcludesFlags"; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 327680] = "TypeExcludesFlags"; })(ts.NodeFlags || (ts.NodeFlags = {})); var NodeFlags = ts.NodeFlags; + (function (ModifierFlags) { + ModifierFlags[ModifierFlags["None"] = 0] = "None"; + ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; + ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; + ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; + ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; + ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; + ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; + ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; + ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; + ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; + ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; + ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; + ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; + })(ts.ModifierFlags || (ts.ModifierFlags = {})); + var ModifierFlags = ts.ModifierFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; /** An element from a named property of the JSX.IntrinsicElements interface */ @@ -431,6 +448,15 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); var RelationComparisonResult = ts.RelationComparisonResult; + /*@internal*/ + (function (GeneratedIdentifierKind) { + GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; + GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; + })(ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierKind = ts.GeneratedIdentifierKind; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; FlowFlags[FlowFlags["Start"] = 2] = "Start"; @@ -475,6 +501,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -512,15 +539,16 @@ var ts; // function that can be reached at runtime (e.g. a `class` // declaration or a `var` declaration for the static side // of a type, such as the global `Promise` type in lib.d.ts). - TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidType"] = 2] = "VoidType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; - TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 8] = "TypeWithCallSignature"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; // with call signatures. - TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 9] = "ObjectType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; (function (SymbolFlags) { @@ -559,8 +587,8 @@ var ts; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793056] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1536] = "Namespace"; + SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the @@ -571,10 +599,10 @@ var ts; SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792960] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; @@ -582,8 +610,8 @@ var ts; SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530912] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793056] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -618,6 +646,9 @@ var ts; NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -625,55 +656,64 @@ var ts; TypeFlags[TypeFlags["String"] = 2] = "String"; TypeFlags[TypeFlags["Number"] = 4] = "Number"; TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Void"] = 16] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 32] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 64] = "Null"; - TypeFlags[TypeFlags["Enum"] = 128] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 256] = "StringLiteral"; - TypeFlags[TypeFlags["TypeParameter"] = 512] = "TypeParameter"; - TypeFlags[TypeFlags["Class"] = 1024] = "Class"; - TypeFlags[TypeFlags["Interface"] = 2048] = "Interface"; - TypeFlags[TypeFlags["Reference"] = 4096] = "Reference"; - TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; - TypeFlags[TypeFlags["Union"] = 16384] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 32768] = "Intersection"; - TypeFlags[TypeFlags["Anonymous"] = 65536] = "Anonymous"; - TypeFlags[TypeFlags["Instantiated"] = 131072] = "Instantiated"; + TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; + TypeFlags[TypeFlags["Void"] = 1024] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 4096] = "Null"; + TypeFlags[TypeFlags["Never"] = 8192] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; + TypeFlags[TypeFlags["Class"] = 32768] = "Class"; + TypeFlags[TypeFlags["Interface"] = 65536] = "Interface"; + TypeFlags[TypeFlags["Reference"] = 131072] = "Reference"; + TypeFlags[TypeFlags["Tuple"] = 262144] = "Tuple"; + TypeFlags[TypeFlags["Union"] = 524288] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 1048576] = "Intersection"; + TypeFlags[TypeFlags["Anonymous"] = 2097152] = "Anonymous"; + TypeFlags[TypeFlags["Instantiated"] = 4194304] = "Instantiated"; /* @internal */ - TypeFlags[TypeFlags["FromSignature"] = 262144] = "FromSignature"; - TypeFlags[TypeFlags["ObjectLiteral"] = 524288] = "ObjectLiteral"; + TypeFlags[TypeFlags["ObjectLiteral"] = 8388608] = "ObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["FreshObjectLiteral"] = 1048576] = "FreshObjectLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 16777216] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsWideningType"] = 33554432] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; - TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; - TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; + TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; + TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 16015] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 16777726] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; - TypeFlags[TypeFlags["ObjectType"] = 80896] = "ObjectType"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 49152] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 130048] = "StructuredType"; + TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; + TypeFlags[TypeFlags["ObjectType"] = 2588672] = "ObjectType"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 1572864] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 4161536] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 4177920] = "StructuredOrTypeParameter"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 16908175] = "Narrowable"; + TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + TypeFlags[TypeFlags["PropagatingFlags"] = 234881024] = "PropagatingFlags"; })(ts.TypeFlags || (ts.TypeFlags = {})); var TypeFlags = ts.TypeFlags; (function (SignatureKind) { @@ -892,8 +932,195 @@ var ts; CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; })(ts.CharacterCodes || (ts.CharacterCodes = {})); var CharacterCodes = ts.CharacterCodes; + /* @internal */ + (function (TransformFlags) { + TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. + TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; + TransformFlags[TransformFlags["Jsx"] = 4] = "Jsx"; + TransformFlags[TransformFlags["ContainsJsx"] = 8] = "ContainsJsx"; + TransformFlags[TransformFlags["ES7"] = 16] = "ES7"; + TransformFlags[TransformFlags["ContainsES7"] = 32] = "ContainsES7"; + TransformFlags[TransformFlags["ES6"] = 64] = "ES6"; + TransformFlags[TransformFlags["ContainsES6"] = 128] = "ContainsES6"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 256] = "DestructuringAssignment"; + TransformFlags[TransformFlags["Generator"] = 512] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. + TransformFlags[TransformFlags["ContainsDecorators"] = 2048] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 4096] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 131072] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpreadElementExpression"] = 262144] = "ContainsSpreadElementExpression"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. + TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 12] = "AssertJsx"; + TransformFlags[TransformFlags["AssertES7"] = 48] = "AssertES7"; + TransformFlags[TransformFlags["AssertES6"] = 192] = "AssertES6"; + TransformFlags[TransformFlags["AssertGenerator"] = 1536] = "AssertGenerator"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. + TransformFlags[TransformFlags["NodeExcludes"] = 536871765] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 550710101] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 550726485] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 550593365] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 550593365] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 537590613] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 546335573] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 537430869] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537133909] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 538968917] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 538968917] = "ParameterExcludes"; + // Masks + // - Additional bitmasks + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 137216] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES6FunctionSyntaxMask"] = 81920] = "ES6FunctionSyntaxMask"; + })(ts.TransformFlags || (ts.TransformFlags = {})); + var TransformFlags = ts.TransformFlags; + /* @internal */ + (function (NodeEmitFlags) { + NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; + NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; + NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; + NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; + NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; + NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; + NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; + NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; + NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; + NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; + NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; + NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; + NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; + NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; + NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; + NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; + NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; + NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; + NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; + NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; + NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; + NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; + NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; + NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; + })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); + var NodeEmitFlags = ts.NodeEmitFlags; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +var ts; +(function (ts) { + var performance; + (function (performance) { + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true + ? onProfilerEvent + : function (markName) { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks[markName] = ts.timestamp(); + counts[markName] = (counts[markName] || 0) + 1; + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks[endMarkName] || ts.timestamp(); + var start = startMarkName && marks[startMarkName] || profilerStart; + measures[measureName] = (measures[measureName] || 0) + (end - start); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts[markName] || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures[measureName] || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + for (var key in measures) { + cb(key, measures[key]); + } + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /// +/// /* @internal */ var ts; (function (ts) { @@ -912,8 +1139,25 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; + var createObject = Object.create; + function createMap(template) { + var map = createObject(null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map["__"] = undefined; + delete map["__"]; + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) + if (hasOwnProperty.call(template, key)) { + map[key] = template[key]; + } + return map; + } + ts.createMap = createMap; function createFileMap(keyMapper) { - var files = {}; + var files = createMap(); return { get: get, set: set, @@ -935,14 +1179,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return hasProperty(files, toKey(path)); + return toKey(path) in files; } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = {}; + files = createMap(); } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -979,11 +1223,52 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ + function find(array, predicate) { + for (var i = 0, len = array.length; i < len; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0, len = array.length; i < len; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (areEqual ? areEqual(v, value) : v === value) { + if (v === value) { return true; } } @@ -1014,9 +1299,9 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var v = array_2[_i]; - if (predicate(v)) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { count++; } } @@ -1025,23 +1310,47 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { - var result; if (array) { - result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (f(item)) { - result.push(item); + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; } + return result; } } - return result; + return array; } ts.filter = filter; + function removeWhere(array, f) { + var outIndex = 0; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var item = array_2[_i]; + if (!f(item)) { + array[outIndex] = item; + outIndex++; + } + } + if (outIndex !== array.length) { + array.length = outIndex; + return true; + } + return false; + } + ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var item = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { array[outIndex] = item; outIndex++; @@ -1054,14 +1363,136 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; - result.push(f(v)); + for (var i = 0; i < array.length; i++) { + var v = array[i]; + result.push(f(v, i)); } } return result; } ts.map = map; + /** + * Flattens an array containing a mix of array or non-array elements. + * + * @param array The array to flatten. + */ + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + function flatMap(array, mapfn) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMap = flatMap; + /** + * Computes the first matching span of elements and returns a tuple of the first span + * and the remaining elements. + */ + function span(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!f(array[i], i)) { + return [array.slice(0, i), array.slice(i)]; + } + } + return [array.slice(0), []]; + } + return undefined; + } + ts.span = span; + /** + * Maps contiguous spans of values with the same key. + * + * @param array The array to map. + * @param keyfn A callback used to select the key for an element. + * @param mapfn A callback used to map a contiguous chunk of values to a single value. + */ + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapObject(object, f) { + var result; + if (object) { + result = {}; + for (var _i = 0, _a = getOwnKeys(object); _i < _a.length; _i++) { + var v = _a[_i]; + var _b = f(v, object[v]) || [undefined, undefined], key = _b[0], value = _b[1]; + if (key !== undefined) { + result[key] = value; + } + } + } + return result; + } + ts.mapObject = mapObject; function concatenate(array1, array2) { if (!array2 || !array2.length) return array1; @@ -1074,20 +1505,45 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var item = array_6[_i]; - if (!contains(result, item, areEqual)) { - result.push(item); + loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; + for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { + var res = result_1[_a]; + if (areEqual ? areEqual(res, item) : res === item) { + continue loop; + } } + result.push(item); } } return result; } ts.deduplicate = deduplicate; + /** + * Compacts an array, removing any falsey elements. + */ + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; function sum(array, prop) { var result = 0; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var v = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -1097,7 +1553,9 @@ var ts; if (to && from) { for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { var v = from_1[_i]; - to.push(v); + if (v !== undefined) { + to.push(v); + } } } } @@ -1112,14 +1570,31 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function firstOrUndefined(array) { + return array && array.length > 0 + ? array[0] + : undefined; + } + ts.firstOrUndefined = firstOrUndefined; + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; /** * Returns the last element of an array if non-empty, undefined otherwise. */ function lastOrUndefined(array) { - if (array.length === 0) { - return undefined; - } - return array[array.length - 1]; + return array && array.length > 0 + ? array[array.length - 1] + : undefined; } ts.lastOrUndefined = lastOrUndefined; /** @@ -1148,11 +1623,12 @@ var ts; return ~low; } ts.binarySearch = binarySearch; - function reduceLeft(array, f, initial) { - if (array) { - var count = array.length; - if (count > 0) { - var pos = 0; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -1161,8 +1637,8 @@ var ts; else { result = initial; } - while (pos < count) { - result = f(result, array[pos]); + while (pos <= end) { + result = f(result, array[pos], pos); pos++; } return result; @@ -1171,10 +1647,12 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial) { + function reduceRight(array, f, initial, start, count) { if (array) { - var pos = array.length - 1; - if (pos >= 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start > size - 1 ? size - 1 : start; + var end = count === undefined || pos - count < 0 ? 0 : pos - count; var result = void 0; if (arguments.length <= 2) { result = array[pos]; @@ -1183,8 +1661,8 @@ var ts; else { result = initial; } - while (pos >= 0) { - result = f(result, array[pos]); + while (pos >= end) { + result = f(result, array[pos], pos); pos--; } return result; @@ -1194,22 +1672,177 @@ var ts; } ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * NOTE: This is intended for use only with MapLike objects. For Map objects, use + * the 'in' operator. + * + * @param map A map-like. + * @param key A property key. + */ function hasProperty(map, key) { return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; - function getKeys(map) { - var keys = []; - for (var key in map) { - keys.push(key); - } - return keys; - } - ts.getKeys = getKeys; + /** + * Gets the value of an owned property in a map-like. + * + * NOTE: This is intended for use only with MapLike objects. For Map objects, use + * an indexer. + * + * @param map A map-like. + * @param key A property key. + */ function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + * + * NOTE: This is intended for use with MapLike objects. For Map objects, use + * Object.keys instead as it offers better performance. + * + * @param map A map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + /** + * Enumerates the properties of a Map, invoking a callback and returning the first truthy result. + * + * @param map A map for which properties should be enumerated. + * @param callback A callback to invoke for each property. + */ + function forEachProperty(map, callback) { + var result; + for (var key in map) { + if (result = callback(map[key], key)) + break; + } + return result; + } + ts.forEachProperty = forEachProperty; + /** + * Returns true if a Map has some matching property. + * + * @param map A map whose properties should be tested. + * @param predicate An optional callback used to test each property. + */ + function someProperties(map, predicate) { + for (var key in map) { + if (!predicate || predicate(map[key], key)) + return true; + } + return false; + } + ts.someProperties = someProperties; + /** + * Performs a shallow copy of the properties from a source Map to a target MapLike + * + * @param source A map from which properties should be copied. + * @param target A map to which properties should be copied. + */ + function copyProperties(source, target) { + for (var key in source) { + target[key] = source[key]; + } + } + ts.copyProperties = copyProperties; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var _b = 0, _c = getOwnKeys(arg); _b < _c.length; _b++) { + var p = _c[_b]; + t[p] = arg[p]; + } + } + return t; + } + ts.assign = assign; + /** + * Reduce the properties of a map. + * + * NOTE: This is intended for use with Map objects. For MapLike objects, use + * reduceOwnProperties instead as it offers better runtime safety. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + function reduceProperties(map, callback, initial) { + var result = initial; + for (var key in map) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceProperties = reduceProperties; + /** + * Reduce the properties defined on a map-like (but not from its prototype chain). + * + * NOTE: This is intended for use with MapLike objects. For Map objects, use + * reduceProperties instead as it offers better performance. + * + * @param map The map-like to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + function reduceOwnProperties(map, callback, initial) { + var result = initial; + for (var key in map) + if (hasOwnProperty.call(map, key)) { + result = callback(result, map[key], String(key)); + } + return result; + } + ts.reduceOwnProperties = reduceOwnProperties; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key) === undefined) + return false; + if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + return false; + } + for (var key in right) + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; function isEmpty(map) { for (var id in map) { if (hasProperty(map, id)) { @@ -1219,92 +1852,65 @@ var ts; return true; } ts.isEmpty = isEmpty; + function cloneMap(map) { + var clone = createMap(); + copyProperties(map, clone); + return clone; + } + ts.cloneMap = cloneMap; function clone(object) { var result = {}; for (var id in object) { - result[id] = object[id]; + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in first) { - result[id] = first[id]; - } - for (var id in second) { - if (!hasProperty(result, id)) { + for (var id in second) + if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - } + for (var id in first) + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } return result; } ts.extend = extend; - function forEachValue(map, callback) { - var result; - for (var id in map) { - if (result = callback(map[id])) - break; - } - return result; - } - ts.forEachValue = forEachValue; - function forEachKey(map, callback) { - var result; - for (var id in map) { - if (result = callback(id)) - break; - } - return result; - } - ts.forEachKey = forEachKey; - function lookUp(map, key) { - return hasProperty(map, key) ? map[key] : undefined; - } - ts.lookUp = lookUp; - function copyMap(source, target) { - for (var p in source) { - target[p] = source[p]; - } - } - ts.copyMap = copyMap; /** - * Creates a map from the elements of an array. - * - * @param array the array of input elements. - * @param makeKey a function that produces a key for a given element. - * - * This function makes no effort to avoid collisions; if any two elements produce - * the same key with the given 'makeKey' function, then the element with the higher - * index in the array will be the one associated with the produced key. + * Adds the value to an array of values associated with the key, and returns the array. + * Creates the array if it does not already exist. */ - function arrayToMap(array, makeKey) { - var result = {}; - forEach(array, function (value) { - result[makeKey(value)] = value; - }); - return result; + function multiMapAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + return values; + } + else { + return map[key] = [value]; + } } - ts.arrayToMap = arrayToMap; + ts.multiMapAdd = multiMapAdd; /** - * Reduce the properties of a map. - * - * @param map The map to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. + * Removes a value from an array of values associated with the key. + * Does not preserve the order of those values. + * Does nothing if `key` is not in `map`, or `value` is not in `map[key]`. */ - function reduceProperties(map, callback, initial) { - var result = initial; - if (map) { - for (var key in map) { - if (hasProperty(map, key)) { - result = callback(result, map[key], String(key)); - } + function multiMapRemove(map, key, value) { + var values = map[key]; + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + delete map[key]; } } - return result; } - ts.reduceProperties = reduceProperties; + ts.multiMapRemove = multiMapRemove; /** * Tests whether a value is an array. */ @@ -1329,9 +1935,7 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] - ? ts.localizedDiagnosticMessages[message.key] - : message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -1526,6 +2130,7 @@ var ts; } ts.getRootLength = getRootLength; ts.directorySeparator = "/"; + var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; @@ -1549,10 +2154,22 @@ var ts; function normalizePath(path) { path = normalizeSlashes(path); var rootLength = getRootLength(path); + var root = path.substr(0, rootLength); var normalized = getNormalizedParts(path, rootLength); - return path.substr(0, rootLength) + normalized.join(ts.directorySeparator); + if (normalized.length) { + var joinedParts = root + normalized.join(ts.directorySeparator); + return pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts; + } + else { + return root; + } } ts.normalizePath = normalizePath; + /** A path ending with '/' refers to a directory only, never a file. */ + function pathEndsWithDirectorySeparator(path) { + return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; + } + ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; function getDirectoryPath(path) { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); } @@ -1756,10 +2373,19 @@ var ts; return true; } ts.containsPath = containsPath; + /* @internal */ + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + /* @internal */ + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - var pathLen = path.length; - var extLen = extension.length; - return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; + return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -1777,10 +2403,25 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory seperators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; + var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } + var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; + var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -1805,7 +2446,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -1817,6 +2458,19 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } + if (usage !== "exclude") { + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + subpattern += "[^./]"; + component = component.substr(1); + } + } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -1837,8 +2491,14 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildcardCharacter(match) { - return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + function replaceWildCardCharacterFiles(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); + } + function replaceWildCardCharacterOther(match) { + return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1957,6 +2617,8 @@ var ts; * List of supported extensions in order of file resolution precedence. */ ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { @@ -2040,9 +2702,13 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; + return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -2062,14 +2728,21 @@ var ts; function Signature(checker) { } function Node(kind, pos, end) { + this.id = 0; this.kind = kind; this.pos = pos; this.end = end; this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; this.parent = undefined; + this.original = undefined; + this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -2084,9 +2757,9 @@ var ts; var AssertionLevel = ts.AssertionLevel; var Debug; (function (Debug) { - var currentAssertionLevel = 0 /* None */; + var currentAssertionLevel; function shouldAssert(level) { - return currentAssertionLevel >= level; + return getCurrentAssertionLevel() >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2104,20 +2777,61 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; + function getCurrentAssertionLevel() { + if (currentAssertionLevel !== undefined) { + return currentAssertionLevel; + } + if (ts.sys === undefined) { + return 0 /* None */; + } + var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); + currentAssertionLevel = developmentMode + ? 1 /* Normal */ + : 0 /* None */; + return currentAssertionLevel; + } })(Debug = ts.Debug || (ts.Debug = {})); - function copyListRemovingItem(item, list) { - var copiedList = []; - for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { - var e = list_1[_i]; - if (e !== item) { - copiedList.push(e); + function getEnvironmentVariable(name, host) { + if (host && host.getEnvironmentVariable) { + return host.getEnvironmentVariable(name); + } + if (ts.sys && ts.sys.getEnvironmentVariable) { + return ts.sys.getEnvironmentVariable(name); + } + return ""; + } + ts.getEnvironmentVariable = getEnvironmentVariable; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + break; } } - return copiedList; } - ts.copyListRemovingItem = copyListRemovingItem; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? (function (fileName) { return fileName; }) : (function (fileName) { return fileName.toLowerCase(); }); } @@ -2216,7 +2930,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - return { + var wscriptSystem = { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -2235,7 +2949,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!wscriptSystem.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -2246,6 +2960,9 @@ var ts; return shell.CurrentDirectory; }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%" + name + "%"); + }, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -2255,6 +2972,7 @@ var ts; } } }; + return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -2263,14 +2981,14 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = {}; + var dirWatchers = ts.createMap(); // One file can have multiple watchers - var fileWatcherCallbacks = {}; + var fileWatcherCallbacks = ts.createMap(); return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - if (ts.hasProperty(dirWatchers, dirName)) { - var watcher = dirWatchers[dirName]; + var watcher = dirWatchers[dirName]; + if (watcher) { watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -2279,23 +2997,18 @@ var ts; } } function addDirWatcher(dirPath) { - if (ts.hasProperty(dirWatchers, dirPath)) { - var watcher_1 = dirWatchers[dirPath]; - watcher_1.referenceCount += 1; + var watcher = dirWatchers[dirPath]; + if (watcher) { + watcher.referenceCount += 1; return; } - var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - fileWatcherCallbacks[filePath].push(callback); - } - else { - fileWatcherCallbacks[filePath] = [callback]; - } + ts.multiMapAdd(fileWatcherCallbacks, filePath, callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -2307,15 +3020,7 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); - if (newCallbacks.length === 0) { - delete fileWatcherCallbacks[filePath]; - } - else { - fileWatcherCallbacks[filePath] = newCallbacks; - } - } + ts.multiMapRemove(fileWatcherCallbacks, filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" @@ -2323,7 +3028,7 @@ var ts; ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); // Some applications save a working file via rename operations - if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -2442,9 +3147,9 @@ var ts; return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - return { + var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -2500,7 +3205,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!this.directoryExists(directoryName)) { + if (!nodeSystem.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -2511,6 +3216,9 @@ var ts; return process.cwd(); }, getDirectories: getDirectories, + getEnvironmentVariable: function (name) { + return process.env[name] || ""; + }, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -2546,8 +3254,16 @@ var ts; }, realpath: function (path) { return _fs.realpathSync(path); + }, + tryEnableSourceMapsForHost: function () { + try { + require("source-map-support").install(); + } + catch (e) { + } } }; + return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -2574,6 +3290,7 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), readDirectory: function (path, extensions, excludes, includes) { var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); @@ -2809,9 +3526,9 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher_1311", message: "Async functions are only available when targeting ECMAScript 2015 or higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, @@ -2866,12 +3583,11 @@ var ts; Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped_function_calls_may_not_accept_type_arguments_2347", message: "Untyped function calls may not accept type arguments." }, Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", message: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, - Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_2349", message: "Cannot invoke an expression whose type lacks a call signature." }, + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", message: "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures." }, Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, @@ -3013,7 +3729,6 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_yield_expressions_2504", message: "No best common type exists among yield expressions." }, A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, @@ -3030,7 +3745,7 @@ var ts; A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, @@ -3043,6 +3758,7 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, + Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3090,6 +3806,13 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, + A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, + Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -3160,7 +3883,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -3188,6 +3911,7 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -3218,6 +3942,7 @@ var ts; VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, + STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, @@ -3304,10 +4029,12 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, - Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, + Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, + Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, + Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3316,7 +4043,6 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -3331,6 +4057,8 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -3358,7 +4086,9 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." } + Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } }; })(ts || (ts = {})); /// @@ -3370,7 +4100,7 @@ var ts; return token >= 69 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115 /* AbstractKeyword */, "any": 117 /* AnyKeyword */, "as": 116 /* AsKeyword */, @@ -3494,7 +4224,7 @@ var ts; "|=": 67 /* BarEqualsToken */, "^=": 68 /* CaretEqualsToken */, "@": 55 /* AtToken */ - }; + }); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -3580,9 +4310,7 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - if (source.hasOwnProperty(name_4)) { - result[source[name_4]] = name_4; - } + result[source[name_4]] = name_4; } return result; } @@ -3743,9 +4471,7 @@ var ts; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { if (stopAtComments === void 0) { stopAtComments = false; } - // Using ! with a greater than test is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - if (!(pos >= 0)) { + if (ts.positionIsSynthesized(pos)) { return pos; } // Keep in sync with couldStartTrivia @@ -3876,20 +4602,34 @@ var ts; return pos; } /** - * Extract comments from text prefixing the token closest following `pos`. - * The return value is an array containing a TextRange for each comment. - * Single-line comment ranges include the beginning '//' characters but not the ending line break. - * Multi - line comment ranges include the beginning '/* and ending '/' characters. - * The return value is undefined if no comments were found. - * @param trailing - * If false, whitespace is skipped until the first line break and comments between that location - * and the next token are returned. - * If true, comments occurring between the given position and the next line break are returned. + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. */ - function getCommentRanges(text, pos, trailing) { - var result; + function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + var pendingPos; + var pendingEnd; + var pendingKind; + var pendingHasTrailingNewLine; + var hasPendingCommentRange = false; var collecting = trailing || pos === 0; - while (pos < text.length) { + var accumulator = initial; + scan: while (pos >= 0 && pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13 /* carriageReturn */: @@ -3899,11 +4639,11 @@ var ts; case 10 /* lineFeed */: pos++; if (trailing) { - return result; + break scan; } collecting = true; - if (result && result.length) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; } continue; case 9 /* tab */: @@ -3938,34 +4678,68 @@ var ts; } } if (collecting) { - if (!result) { - result = []; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. + return accumulator; + } + hasPendingCommentRange = false; } - result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; } continue; } - break; + break scan; default: if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch))) { - if (result && result.length && isLineBreak(ch)) { - ts.lastOrUndefined(result).hasTrailingNewLine = true; + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; } pos++; continue; } - break; + break scan; } - return result; } - return result; + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; + } + function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); + } + ts.forEachLeadingCommentRange = forEachLeadingCommentRange; + function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); + } + ts.forEachTrailingCommentRange = forEachTrailingCommentRange; + function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); + } + ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; + function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); + } + ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; + function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + if (!comments) { + comments = []; + } + comments.push({ pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + return comments; } function getLeadingCommentRanges(text, pos) { - return getCommentRanges(text, pos, /*trailing*/ false); + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getLeadingCommentRanges = getLeadingCommentRanges; function getTrailingCommentRanges(text, pos) { - return getCommentRanges(text, pos, /*trailing*/ true); + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined); } ts.getTrailingCommentRanges = getTrailingCommentRanges; /** Optionally, get the shebang */ @@ -3988,7 +4762,7 @@ var ts; } ts.isIdentifierPart = isIdentifierPart; /* @internal */ - function isIdentifier(name, languageVersion) { + function isIdentifierText(name, languageVersion) { if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { return false; } @@ -3999,7 +4773,7 @@ var ts; } return true; } - ts.isIdentifier = isIdentifier; + ts.isIdentifierText = isIdentifierText; // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } @@ -4033,6 +4807,7 @@ var ts; reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, scanJsxIdentifier: scanJsxIdentifier, + scanJsxAttributeValue: scanJsxAttributeValue, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, scanJSDocToken: scanJSDocToken, @@ -4124,7 +4899,8 @@ var ts; } return value; } - function scanString() { + function scanString(allowEscapes) { + if (allowEscapes === void 0) { allowEscapes = true; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -4142,7 +4918,7 @@ var ts; pos++; break; } - if (ch === 92 /* backslash */) { + if (ch === 92 /* backslash */ && allowEscapes) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; @@ -4887,43 +5663,62 @@ var ts; } return token; } + function scanJsxAttributeValue() { + startPos = pos; + switch (text.charCodeAt(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*allowEscapes*/ false); + return token = 9 /* StringLiteral */; + default: + // If this scans anything other than `{`, it's a parse error. + return scan(); + } + } function scanJSDocToken() { if (pos >= end) { return token = 1 /* EndOfFileToken */; } startPos = pos; - // Eat leading whitespace - var ch = text.charCodeAt(pos); - while (pos < end) { - ch = text.charCodeAt(pos); - if (isWhiteSpaceSingleLine(ch)) { - pos++; - } - else { - break; - } - } tokenPos = pos; + var ch = text.charCodeAt(pos); switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - return pos += 1, token = 55 /* AtToken */; + pos++; + return token = 55 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - return pos += 1, token = 4 /* NewLineTrivia */; + pos++; + return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - return pos += 1, token = 37 /* AsteriskToken */; + pos++; + return token = 37 /* AsteriskToken */; case 123 /* openBrace */: - return pos += 1, token = 15 /* OpenBraceToken */; + pos++; + return token = 15 /* OpenBraceToken */; case 125 /* closeBrace */: - return pos += 1, token = 16 /* CloseBraceToken */; + pos++; + return token = 16 /* CloseBraceToken */; case 91 /* openBracket */: - return pos += 1, token = 19 /* OpenBracketToken */; + pos++; + return token = 19 /* OpenBracketToken */; case 93 /* closeBracket */: - return pos += 1, token = 20 /* CloseBracketToken */; + pos++; + return token = 20 /* CloseBracketToken */; case 61 /* equals */: - return pos += 1, token = 56 /* EqualsToken */; + pos++; + return token = 56 /* EqualsToken */; case 44 /* comma */: - return pos += 1, token = 24 /* CommaToken */; + pos++; + return token = 24 /* CommaToken */; } if (isIdentifierStart(ch, 2 /* Latest */)) { pos++; @@ -5020,6 +5815,7 @@ var ts; /* @internal */ var ts; (function (ts) { + ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -5070,24 +5866,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function mapIsEqualTo(map1, map2) { - if (!map1 || !map2) { - return map1 === map2; - } - return containsAll(map1, map2) && containsAll(map2, map1); - } - ts.mapIsEqualTo = mapIsEqualTo; - function containsAll(map, other) { - for (var key in map) { - if (!ts.hasProperty(map, key)) { - continue; - } - if (!ts.hasProperty(other, key) || map[key] !== other[key]) { - return false; - } - } - return true; - } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -5105,7 +5883,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5114,14 +5892,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = {}; + sourceFile.resolvedModules = ts.createMap(); } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = {}; + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -5143,7 +5921,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; + var oldResolution = oldResolutions && oldResolutions[names[i]]; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -5157,24 +5935,24 @@ var ts; // Returns true if this node contains a parse error anywhere underneath it. function containsParseError(node) { aggregateChildData(node); - return (node.flags & 268435456 /* ThisNodeOrAnySubNodesHasError */) !== 0; + return (node.flags & 2097152 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 536870912 /* HasAggregatedChildData */)) { + if (!(node.flags & 4194304 /* HasAggregatedChildData */)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. - var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864 /* ThisNodeHasError */) !== 0) || + var thisNodeOrAnySubNodesHasError = ((node.flags & 524288 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.flags |= 268435456 /* ThisNodeOrAnySubNodesHasError */; + node.flags |= 2097152 /* ThisNodeOrAnySubNodesHasError */; } // Also mark that we've propagated the child information to this node. This way we can // always consult the bit directly on this node without needing to check its children // again. - node.flags |= 536870912 /* HasAggregatedChildData */; + node.flags |= 4194304 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { @@ -5212,6 +5990,10 @@ var ts; return node.pos; } ts.getStartPosOfNode = getStartPosOfNode; + function isDefined(value) { + return value !== undefined; + } + ts.isDefined = isDefined; function getEndLinePosition(line, sourceFile) { ts.Debug.assert(line >= 0); var lineStarts = ts.getLineStarts(sourceFile); @@ -5251,7 +6033,7 @@ var ts; // However, this node will be 'missing' in the sense that no actual source-code/tokens are // contained within it. function nodeIsMissing(node) { - if (!node) { + if (node === undefined) { return true; } return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; @@ -5277,16 +6059,20 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 282 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 281 /* LastJSDocNode */; + return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 282 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; + function isJSDocTag(node) { + return node.kind >= 273 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5315,6 +6101,56 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getLiteralText(node, sourceFile, languageVersion) { + // Any template literal or string literal with an extended escape + // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. + if (languageVersion < 2 /* ES6 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + return getQuotedEscapedLiteralText('"', node.text, '"'); + } + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (!nodeIsSynthesized(node) && node.parent) { + var text = getSourceTextOfNodeFromSourceFile(sourceFile, node); + if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { + return node.text; + } + return text; + } + // If we can't reach the original source text, use the canonical form if it's a number, + // or an escaped quoted form of the original text if it's string-like. + switch (node.kind) { + case 9 /* StringLiteral */: + return getQuotedEscapedLiteralText('"', node.text, '"'); + case 11 /* NoSubstitutionTemplateLiteral */: + return getQuotedEscapedLiteralText("`", node.text, "`"); + case 12 /* TemplateHead */: + return getQuotedEscapedLiteralText("`", node.text, "${"); + case 13 /* TemplateMiddle */: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 14 /* TemplateTail */: + return getQuotedEscapedLiteralText("}", node.text, "`"); + case 8 /* NumericLiteral */: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function isBinaryOrOctalIntegerLiteral(node, text) { + if (node.kind === 8 /* NumericLiteral */ && text.length > 1) { + switch (text.charCodeAt(1)) { + case 98 /* b */: + case 66 /* B */: + case 111 /* o */: + case 79 /* O */: + return true; + } + } + return false; + } + ts.isBinaryOrOctalIntegerLiteral = isBinaryOrOctalIntegerLiteral; + function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { + return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote; + } // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeIdentifier(identifier) { return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; @@ -5332,7 +6168,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 3072 /* BlockScoped */) !== 0 || + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -5341,20 +6177,22 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. return node.kind === 225 /* ModuleDeclaration */ && (!node.body); } - ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || - isFunctionLike(node) || - isFunctionBlock(node); + isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { - return !!(module.flags & 131072 /* GlobalAugmentation */); + return !!(module.flags & 512 /* GlobalAugmentation */); } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { @@ -5373,30 +6211,39 @@ var ts; return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 256 /* SourceFile */: + case 227 /* CaseBlock */: + case 252 /* CatchClause */: + case 225 /* ModuleDeclaration */: + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + case 148 /* Constructor */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + return true; + case 199 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + return parentNode && !isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { - if (isFunctionLike(current)) { + if (isBlockScope(current, current.parent)) { return current; } - switch (current.kind) { - case 256 /* SourceFile */: - case 227 /* CaseBlock */: - case 252 /* CatchClause */: - case 225 /* ModuleDeclaration */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - return current; - case 199 /* Block */: - // function block is not considered block-scope container - // see comment in binder.ts: bind(...), case for SyntaxKind.Block - if (!isFunctionLike(current.parent)) { - return current; - } - } current = current.parent; } } @@ -5508,41 +6355,13 @@ var ts; return node.kind === 224 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 /* BindingElement */ || isBindingPattern(node))) { - node = node.parent; - } - return node; - } - // Returns the node flags for this node and all relevant parent nodes. This is done so that - // nodes like variable declarations and binding elements can returned a view of their flags - // that includes the modifiers from their container. i.e. flags like export/declare aren't - // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration - // list. By calling this function, all those flags are combined so that the client can treat - // the node as if it actually had those flags. - function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 218 /* VariableDeclaration */) { - node = node.parent; - } - if (node && node.kind === 219 /* VariableDeclarationList */) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 200 /* VariableStatement */) { - flags |= node.flags; - } - return flags; - } - ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 2048 /* Const */); + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */) + || !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 1024 /* Let */); + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; function isSuperCallExpression(n) { @@ -5584,7 +6403,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; - function isTypeNode(node) { + function isPartOfTypeNode(node) { if (154 /* FirstTypeNode */ <= node.kind && node.kind <= 166 /* LastTypeNode */) { return true; } @@ -5612,7 +6431,7 @@ var ts; node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 139 /* QualifiedName */: case 172 /* PropertyAccessExpression */: case 97 /* ThisKeyword */: @@ -5620,11 +6439,11 @@ var ts; if (parent_1.kind === 158 /* TypeQuery */) { return false; } - // Do not recursively call isTypeNode on the parent. In the example: + // Do not recursively call isPartOfTypeNode on the parent. In the example: // // let a: A.B.C; // - // Calling isTypeNode would consider the qualified name A.B a type node. Only C or + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. if (154 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 166 /* LastTypeNode */) { return true; @@ -5664,7 +6483,7 @@ var ts; } return false; } - ts.isTypeNode = isTypeNode; + ts.isPartOfTypeNode = isPartOfTypeNode; // Warning: This has the same semantics as the forEach family of functions, // in that traversal terminates in the event that 'visitor' supplies a truthy value. function forEachReturnStatement(body, visitor) { @@ -5723,7 +6542,7 @@ var ts; return; } } - else if (!isTypeNode(node)) { + else if (!isPartOfTypeNode(node)) { // This is the general case, which should include mostly expressions and statements. // Also includes NodeArrays. ts.forEachChild(node, traverse); @@ -5969,18 +6788,19 @@ var ts; /** * Determines whether a node is a property or element access expression for super. */ - function isSuperPropertyOrElementAccess(node) { - return (node.kind === 172 /* PropertyAccessExpression */ - || node.kind === 173 /* ElementAccessExpression */) + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 172 /* PropertyAccessExpression */ || kind === 173 /* ElementAccessExpression */) && node.expression.kind === 95 /* SuperKeyword */; } - ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; + ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { case 155 /* TypeReference */: return node.typeName; case 194 /* ExpressionWithTypeArguments */: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69 /* Identifier */: case 139 /* QualifiedName */: @@ -5990,6 +6810,18 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function isCallLikeExpression(node) { + switch (node.kind) { + case 174 /* CallExpression */: + case 175 /* NewExpression */: + case 176 /* TaggedTemplateExpression */: + case 143 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { if (node.kind === 176 /* TaggedTemplateExpression */) { return node.tag; @@ -6028,14 +6860,20 @@ var ts; && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function isPropertyAccessExpression(node) { - return node.kind === 172 /* PropertyAccessExpression */; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isElementAccessExpression(node) { - return node.kind === 173 /* ElementAccessExpression */; + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 221 /* ClassDeclaration */: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 147 /* MethodDeclaration */: + case 150 /* SetAccessor */: + return ts.forEach(node.parameters, nodeIsDecorated); + } } - ts.isElementAccessExpression = isElementAccessExpression; + ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; if (parent.kind === 243 /* JsxOpeningElement */ || @@ -6046,7 +6884,7 @@ var ts; return false; } ts.isJSXTagName = isJSXTagName; - function isExpression(node) { + function isPartOfExpression(node) { switch (node.kind) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: @@ -6142,18 +6980,18 @@ var ts; case 194 /* ExpressionWithTypeArguments */: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: - if (isExpression(parent_3)) { + if (isPartOfExpression(parent_3)) { return true; } } } return false; } - ts.isExpression = isExpression; + ts.isPartOfExpression = isPartOfExpression; function isExternalModuleNameRelative(moduleName) { // TypeScript 1.0 spec (April 2014): 11.2.1 // An external module name is "relative" if the first term is "." or "..". - return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + return /^\.\.?($|[\\/])/.test(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { @@ -6180,7 +7018,7 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 134217728 /* JavaScriptFile */); + return node && !!(node.flags & 1048576 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; /** @@ -6276,6 +7114,22 @@ var ts; } } ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + if (node.kind === 229 /* ImportEqualsDeclaration */) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232 /* NamespaceImport */) { + return importClause.namedBindings; + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 230 /* ImportDeclaration */ + && node.importClause + && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { @@ -6302,37 +7156,71 @@ var ts; if (!node) { return undefined; } - var jsDocComments = getJSDocComments(node, checkParentVariableStatement); - if (!jsDocComments) { + var jsDocTags = getJSDocTags(node, checkParentVariableStatement); + if (!jsDocTags) { return undefined; } - for (var _i = 0, jsDocComments_1 = jsDocComments; _i < jsDocComments_1.length; _i++) { - var jsDocComment = jsDocComments_1[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === kind) { - return tag; - } + for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { + var tag = jsDocTags_1[_i]; + if (tag.kind === kind) { + return tag; } } } - function getJSDocComments(node, checkParentVariableStatement) { - if (node.jsDocComments) { - return node.jsDocComments; + function append(previous, additional) { + if (additional) { + if (!previous) { + previous = []; + } + for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { + var x = additional_1[_i]; + previous.push(x); + } } - // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. - // /** - // * @param {number} name - // * @returns {number} - // */ - // var x = function(name) { return name.length; } + return previous; + } + function getJSDocComments(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); + } + ts.getJSDocComments = getJSDocComments; + function getJSDocTags(node, checkParentVariableStatement) { + return getJSDocs(node, checkParentVariableStatement, function (docs) { + var result = []; + for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { + var doc = docs_1[_i]; + if (doc.tags) { + result.push.apply(result, doc.tags); + } + } + return result; + }, function (tags) { return tags; }); + } + function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { + // TODO: Get rid of getJsDocComments and friends (note the lowercase 's' in Js) + // TODO: A lot of this work should be cached, maybe. I guess it's only used in services right now... + var result = undefined; + // prepend documentation from parent sources if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 218 /* VariableDeclaration */ && - node.parent.initializer === node && + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && + (node.parent).initializer === node && node.parent.parent.parent.kind === 200 /* VariableStatement */; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + var isVariableOfVariableDeclarationStatement = isVariableLike(node) && + node.parent.parent.kind === 200 /* VariableStatement */; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : + isVariableOfVariableDeclarationStatement ? node.parent.parent : + undefined; if (variableStatementNode) { - return variableStatementNode.jsDocComments; + result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + } + if (node.kind === 225 /* ModuleDeclaration */ && + node.parent && node.parent.kind === 225 /* ModuleDeclaration */) { + result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } // Also recognize when the node is the RHS of an assignment expression var parent_4 = node.parent; @@ -6341,14 +7229,56 @@ var ts; parent_4.operatorToken.kind === 56 /* EqualsToken */ && parent_4.parent.kind === 202 /* ExpressionStatement */; if (isSourceOfAssignmentExpressionStatement) { - return parent_4.parent.jsDocComments; + result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); } var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253 /* PropertyAssignment */; if (isPropertyAssignmentExpression) { - return parent_4.jsDocComments; + result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + } + // Pull parameter comments from declaring function as well + if (node.kind === 142 /* Parameter */) { + var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); + if (paramTags) { + result = append(result, getTags(paramTags)); + } } } - return undefined; + if (isVariableLike(node) && node.initializer) { + result = append(result, getJSDocs(node.initializer, /*checkParentVariableStatement*/ false, getDocs, getTags)); + } + if (node.jsDocComments) { + if (result) { + result = append(result, getDocs(node.jsDocComments)); + } + else { + return getDocs(node.jsDocComments); + } + } + return result; + } + function getJSDocParameterTag(param, checkParentVariableStatement) { + var func = param.parent; + var tags = getJSDocTags(func, checkParentVariableStatement); + if (!param.name) { + // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification + var i = func.parameters.indexOf(param); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */; }); + if (paramTags && 0 <= i && i < paramTags.length) { + return [paramTags[i]]; + } + } + else if (param.name.kind === 69 /* Identifier */) { + var name_6 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */ && tag.parameterName.text === name_6; }); + if (paramTags) { + return paramTags; + } + } + else { + // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines + // But multi-line object types aren't supported yet either + return undefined; + } } function getJSDocTypeTag(node) { return getJSDocTag(node, 277 /* JSDocTypeTag */, /*checkParentVariableStatement*/ false); @@ -6367,19 +7297,16 @@ var ts; // If it's a parameter, see if the parent has a jsdoc comment with an @param // annotation. var parameterName = parameter.name.text; - var jsDocComments = getJSDocComments(parameter.parent, /*checkParentVariableStatement*/ true); - if (jsDocComments) { - for (var _i = 0, jsDocComments_2 = jsDocComments; _i < jsDocComments_2.length; _i++) { - var jsDocComment = jsDocComments_2[_i]; - for (var _a = 0, _b = jsDocComment.tags; _a < _b.length; _a++) { - var tag = _b[_a]; - if (tag.kind === 275 /* JSDocParameterTag */) { - var parameterTag = tag; - var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_6.text === parameterName) { - return parameterTag; - } - } + var jsDocTags = getJSDocTags(parameter.parent, /*checkParentVariableStatement*/ true); + if (!jsDocTags) { + return undefined; + } + for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { + var tag = jsDocTags_2[_i]; + if (tag.kind === 275 /* JSDocParameterTag */) { + var parameterTag = tag; + if (parameterTag.parameterName.text === parameterName) { + return parameterTag; } } } @@ -6396,7 +7323,7 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 134217728 /* JavaScriptFile */)) { + if (node && (node.flags & 1048576 /* JavaScriptFile */)) { if (node.type && node.type.kind === 270 /* JSDocVariadicType */) { return true; } @@ -6412,22 +7339,6 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isTemplateLiteralKind(kind) { - return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isBindingPattern(node) { - return !!node && (node.kind === 168 /* ArrayBindingPattern */ || node.kind === 167 /* ObjectBindingPattern */); - } - ts.isBindingPattern = isBindingPattern; // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. @@ -6446,14 +7357,14 @@ var ts; continue; } return parent_5.kind === 187 /* BinaryExpression */ && - parent_5.operatorToken.kind === 56 /* EqualsToken */ && + isAssignmentOperator(parent_5.operatorToken.kind) && parent_5.left === node || (parent_5.kind === 207 /* ForInStatement */ || parent_5.kind === 208 /* ForOfStatement */) && parent_5.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; - function isNodeDescendentOf(node, ancestor) { + function isNodeDescendantOf(node, ancestor) { while (node) { if (node === ancestor) return true; @@ -6461,10 +7372,10 @@ var ts; } return false; } - ts.isNodeDescendentOf = isNodeDescendentOf; + ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (node.flags & 2 /* Ambient */ || (node.kind === 256 /* SourceFile */ && node.isDeclarationFile)) { + if (hasModifier(node, 2 /* Ambient */) || (node.kind === 256 /* SourceFile */ && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6472,84 +7383,6 @@ var ts; return false; } ts.isInAmbientContext = isInAmbientContext; - function isDeclaration(node) { - switch (node.kind) { - case 180 /* ArrowFunction */: - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 148 /* Constructor */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 238 /* ExportSpecifier */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 149 /* GetAccessor */: - case 231 /* ImportClause */: - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 222 /* InterfaceDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 225 /* ModuleDeclaration */: - case 232 /* NamespaceImport */: - case 142 /* Parameter */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 150 /* SetAccessor */: - case 254 /* ShorthandPropertyAssignment */: - case 223 /* TypeAliasDeclaration */: - case 141 /* TypeParameter */: - case 218 /* VariableDeclaration */: - case 279 /* JSDocTypedefTag */: - return true; - } - return false; - } - ts.isDeclaration = isDeclaration; - function isStatement(n) { - switch (n.kind) { - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: - case 217 /* DebuggerStatement */: - case 204 /* DoStatement */: - case 202 /* ExpressionStatement */: - case 201 /* EmptyStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 206 /* ForStatement */: - case 203 /* IfStatement */: - case 214 /* LabeledStatement */: - case 211 /* ReturnStatement */: - case 213 /* SwitchStatement */: - case 215 /* ThrowStatement */: - case 216 /* TryStatement */: - case 200 /* VariableStatement */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 235 /* ExportAssignment */: - return true; - default: - return false; - } - } - ts.isStatement = isStatement; - function isClassElement(n) { - switch (n.kind) { - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - return true; - default: - return false; - } - } - ts.isClassElement = isClassElement; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { if (name.kind !== 69 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { @@ -6614,8 +7447,8 @@ var ts; // import * as from ... // import { x as } from ... // export { x as } from ... - // export = ... - // export default ... + // export = + // export default function isAliasSymbolDeclaration(node) { return node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 228 /* NamespaceExportDeclaration */ || @@ -6623,9 +7456,13 @@ var ts; node.kind === 232 /* NamespaceImport */ || node.kind === 234 /* ImportSpecifier */ || node.kind === 238 /* ExportSpecifier */ || - node.kind === 235 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; + node.kind === 235 /* ExportAssignment */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + return isEntityNameExpression(node.expression); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -6713,7 +7550,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node); + return isFunctionLike(node) && hasModifier(node, 256 /* Async */) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; function isStringOrNumericLiteral(kind) { @@ -6804,80 +7641,250 @@ var ts; return node; } ts.getRootDeclaration = getRootDeclaration; - function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 225 /* ModuleDeclaration */ || n.kind === 256 /* SourceFile */; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 148 /* Constructor */ + || kind === 179 /* FunctionExpression */ + || kind === 220 /* FunctionDeclaration */ + || kind === 180 /* ArrowFunction */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 225 /* ModuleDeclaration */ + || kind === 256 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - /** - * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" - * properties are excluded by default, and can be provided via the "location", "flags", and - * "parent" parameters. - * @param node The node to clone. - * @param location An optional TextRange to use to supply the new position. - * @param flags The NodeFlags to use for the cloned node. - * @param parent The parent for the new node. - */ - function cloneNode(node, location, flags, parent) { - // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of - // the original node. We also need to exclude specific properties and only include own- - // properties (to skip members already defined on the shared prototype). - var clone = location !== undefined - ? ts.createNode(node.kind, location.pos, location.end) - : createSynthesizedNode(node.kind); - for (var key in node) { - if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { - continue; - } - clone[key] = node[key]; - } - if (flags !== undefined) { - clone.flags = flags; - } - if (parent !== undefined) { - clone.parent = parent; - } - return clone; - } - ts.cloneNode = cloneNode; - /** - * Creates a deep clone of an EntityName, with new parent pointers. - * @param node The EntityName to clone. - * @param parent The parent for the cloned node. - */ - function cloneEntityName(node, parent) { - var clone = cloneNode(node, node, node.flags, parent); - if (isQualifiedName(clone)) { - var left = clone.left, right = clone.right; - clone.left = cloneEntityName(left, clone); - clone.right = cloneNode(right, right, right.flags, parent); - } - return clone; - } - ts.cloneEntityName = cloneEntityName; - function isQualifiedName(node) { - return node.kind === 139 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { - return node.pos === -1; + return positionIsSynthesized(node.pos) + || positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function createSynthesizedNode(kind, startsOnNewLine) { - var node = ts.createNode(kind, /* pos */ -1, /* end */ -1); - node.startsOnNewLine = startsOnNewLine; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function getOriginalNode(node) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } return node; } - ts.createSynthesizedNode = createSynthesizedNode; - function createSynthesizedNodeArray() { - var array = []; - array.pos = -1; - array.end = -1; - return array; + ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ + function isParseTreeNode(node) { + return (node.flags & 8 /* Synthesized */) === 0; } - ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function getOriginalSourceFiles(sourceFiles) { + var originalSourceFiles = []; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + var originalSourceFile = getParseTreeNode(sourceFile, isSourceFile); + if (originalSourceFile) { + originalSourceFiles.push(originalSourceFile); + } + } + return originalSourceFiles; + } + ts.getOriginalSourceFiles = getOriginalSourceFiles; + function getOriginalNodeId(node) { + node = getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + (function (Associativity) { + Associativity[Associativity["Left"] = 0] = "Left"; + Associativity[Associativity["Right"] = 1] = "Right"; + })(ts.Associativity || (ts.Associativity = {})); + var Associativity = ts.Associativity; + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 175 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 185 /* PrefixUnaryExpression */: + case 182 /* TypeOfExpression */: + case 183 /* VoidExpression */: + case 181 /* DeleteExpression */: + case 184 /* AwaitExpression */: + case 188 /* ConditionalExpression */: + case 190 /* YieldExpression */: + return 1 /* Right */; + case 187 /* BinaryExpression */: + switch (operator) { + case 38 /* AsteriskAsteriskToken */: + case 56 /* EqualsToken */: + case 57 /* PlusEqualsToken */: + case 58 /* MinusEqualsToken */: + case 60 /* AsteriskAsteriskEqualsToken */: + case 59 /* AsteriskEqualsToken */: + case 61 /* SlashEqualsToken */: + case 62 /* PercentEqualsToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* AmpersandEqualsToken */: + case 68 /* CaretEqualsToken */: + case 67 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 187 /* BinaryExpression */) { + return expression.operatorToken.kind; + } + else if (expression.kind === 185 /* PrefixUnaryExpression */ || expression.kind === 186 /* PostfixUnaryExpression */) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 97 /* ThisKeyword */: + case 95 /* SuperKeyword */: + case 69 /* Identifier */: + case 93 /* NullKeyword */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 170 /* ArrayLiteralExpression */: + case 171 /* ObjectLiteralExpression */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 192 /* ClassExpression */: + case 241 /* JsxElement */: + case 242 /* JsxSelfClosingElement */: + case 10 /* RegularExpressionLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 189 /* TemplateExpression */: + case 178 /* ParenthesizedExpression */: + case 193 /* OmittedExpression */: + return 19; + case 176 /* TaggedTemplateExpression */: + case 172 /* PropertyAccessExpression */: + case 173 /* ElementAccessExpression */: + return 18; + case 175 /* NewExpression */: + return hasArguments ? 18 : 17; + case 174 /* CallExpression */: + return 17; + case 186 /* PostfixUnaryExpression */: + return 16; + case 185 /* PrefixUnaryExpression */: + case 182 /* TypeOfExpression */: + case 183 /* VoidExpression */: + case 181 /* DeleteExpression */: + case 184 /* AwaitExpression */: + return 15; + case 187 /* BinaryExpression */: + switch (operatorKind) { + case 49 /* ExclamationToken */: + case 50 /* TildeToken */: + return 15; + case 38 /* AsteriskAsteriskToken */: + case 37 /* AsteriskToken */: + case 39 /* SlashToken */: + case 40 /* PercentToken */: + return 14; + case 35 /* PlusToken */: + case 36 /* MinusToken */: + return 13; + case 43 /* LessThanLessThanToken */: + case 44 /* GreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 25 /* LessThanToken */: + case 28 /* LessThanEqualsToken */: + case 27 /* GreaterThanToken */: + case 29 /* GreaterThanEqualsToken */: + case 90 /* InKeyword */: + case 91 /* InstanceOfKeyword */: + return 11; + case 30 /* EqualsEqualsToken */: + case 32 /* EqualsEqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + return 10; + case 46 /* AmpersandToken */: + return 9; + case 48 /* CaretToken */: + return 8; + case 47 /* BarToken */: + return 7; + case 51 /* AmpersandAmpersandToken */: + return 6; + case 52 /* BarBarToken */: + return 5; + case 56 /* EqualsToken */: + case 57 /* PlusEqualsToken */: + case 58 /* MinusEqualsToken */: + case 60 /* AsteriskAsteriskEqualsToken */: + case 59 /* AsteriskEqualsToken */: + case 61 /* SlashEqualsToken */: + case 62 /* PercentEqualsToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* AmpersandEqualsToken */: + case 68 /* CaretEqualsToken */: + case 67 /* BarEqualsToken */: + return 3; + case 24 /* CommaToken */: + return 0; + default: + return -1; + } + case 188 /* ConditionalExpression */: + return 4; + case 190 /* YieldExpression */: + return 2; + case 191 /* SpreadElementExpression */: + return 1; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6930,9 +7937,7 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); - } + ts.forEach(fileDiagnostics[key], pushDiagnostic); } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -6943,9 +7948,7 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - if (ts.hasProperty(fileDiagnostics, key)) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); - } + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } } } @@ -6956,7 +7959,7 @@ var ts; // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { + var escapedCharsMap = ts.createMap({ "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -6969,7 +7972,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine - }; + }); /** * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) @@ -7079,10 +8082,23 @@ var ts; getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, reset: reset }; } ts.createTextWriter = createTextWriter; + function getResolvedExternalModuleName(host, file) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; /** * Resolves a local path to a path which is absolute to the base of the emit */ @@ -7127,6 +8143,105 @@ var ts; getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; } ts.getEmitModuleKind = getEmitModuleKind; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + var moduleKind = getEmitModuleKind(options); + var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var sourceFiles = host.getSourceFiles(); + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, isNonDeclarationFile); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function isNonDeclarationFile(sourceFile) { + return !isDeclarationFile(sourceFile); + } + function isBundleEmitNonExternalModule(sourceFile) { + return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + /** + * Iterates over each source file to emit. The source files are expected to have been + * transformed for use by the pretty printer. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param sourceFiles The transformed source files to emit. + * @param action The action to execute. + */ + function forEachTransformedEmitFile(host, sourceFiles, action) { + var options = host.getCompilerOptions(); + // Emit on each source file + if (options.outFile || options.out) { + onBundledEmit(host, sourceFiles); + } + else { + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + // Don't emit if source file is a declaration file, or was located under node_modules + if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + var extension = ".js"; + if (options.jsx === 1 /* Preserve */) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); + } + function onBundledEmit(host, sourceFiles) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + action(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, /*isBundledEmit*/ true); + } + } + } + ts.forEachTransformedEmitFile = forEachTransformedEmitFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + /** + * Iterates over the source files that are expected to have an emit output. This function + * is used by the legacy emitter and the declaration emitter and should not be used by + * the tree transforming emitter. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param targetSourceFile An optional target source file to emit. + */ function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); // Emit on each source file @@ -7135,8 +8250,8 @@ var ts; } else { var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; // Don't emit if source file is a declaration file, or was located under node_modules if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { onSingleFileEmit(host, sourceFile); @@ -7184,9 +8299,6 @@ var ts; action(emitFileNames, bundledSources, /*isBundledEmit*/ true); } } - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } } ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { @@ -7248,7 +8360,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 149 /* GetAccessor */ || member.kind === 150 /* SetAccessor */) - && (member.flags & 32 /* Static */) === (accessor.flags & 32 /* Static */)) { + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -7277,32 +8389,49 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { // If the leading comments start on different line than the start of node, write new line - if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } - ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { - var emitLeadingSpace = !trailingSeparator; - ts.forEach(comments, function (comment) { - if (emitLeadingSpace) { - writer.write(" "); - emitLeadingSpace = false; - } - writeComment(text, lineMap, writer, comment, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - else if (trailingSeparator) { + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { writer.write(" "); } - else { - // Emit leading space to separate comment during next comment emit - emitLeadingSpace = true; + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.write(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } } - }); + if (emitInterveningSeparator && trailingSeparator) { + writer.write(" "); + } + } } ts.emitComments = emitComments; /** @@ -7353,7 +8482,7 @@ var ts; if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } @@ -7365,19 +8494,19 @@ var ts; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(text, lineMap, writer, comment, newLine) { - if (text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); var lineCount = lineMap.length; var firstCommentLineIndent = void 0; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount ? text.length + 1 : lineMap[currentLine + 1]; - if (pos !== comment.pos) { + if (pos !== commentPos) { // If we are not emitting first line, we need to write the spaces to adjust the alignment if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); } // These are number of spaces writer is going to write at current indent var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); @@ -7413,23 +8542,23 @@ var ts; } } // Write the comment line text - writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { // Single line comment of style //.... - writer.write(text.substring(comment.pos, comment.end)); + writer.write(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; - function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text writer.write(currentLineText); - if (end !== comment.end) { + if (end !== commentEnd) { writer.writeLine(); } } @@ -7452,6 +8581,32 @@ var ts; } return currentLineIndent; } + function hasModifiers(node) { + return getModifierFlags(node) !== 0 /* None */; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return (getModifierFlags(node) & flags) !== 0; + } + ts.hasModifier = hasModifier; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; + } + var flags = 0 /* None */; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 /* NestedNamespace */) { + flags |= 1 /* Export */; + } + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { case 113 /* StaticKeyword */: return 32 /* Static */; @@ -7466,52 +8621,39 @@ var ts; case 118 /* AsyncKeyword */: return 256 /* Async */; case 128 /* ReadonlyKeyword */: return 64 /* Readonly */; } - return 0; + return 0 /* None */; } ts.modifierToFlag = modifierToFlag; - function isLeftHandSideExpression(expr) { - if (expr) { - switch (expr.kind) { - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: - case 175 /* NewExpression */: - case 174 /* CallExpression */: - case 196 /* NonNullExpression */: - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 176 /* TaggedTemplateExpression */: - case 170 /* ArrayLiteralExpression */: - case 178 /* ParenthesizedExpression */: - case 171 /* ObjectLiteralExpression */: - case 192 /* ClassExpression */: - case 179 /* FunctionExpression */: - case 69 /* Identifier */: - case 10 /* RegularExpressionLiteral */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 189 /* TemplateExpression */: - case 84 /* FalseKeyword */: - case 93 /* NullKeyword */: - case 97 /* ThisKeyword */: - case 99 /* TrueKeyword */: - case 95 /* SuperKeyword */: - return true; - } - } - return false; + function isLogicalOperator(token) { + return token === 52 /* BarBarToken */ + || token === 51 /* AmpersandAmpersandToken */ + || token === 49 /* ExclamationToken */; } - ts.isLeftHandSideExpression = isLeftHandSideExpression; + ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { return token >= 56 /* FirstAssignment */ && token <= 68 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; - function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 194 /* ExpressionWithTypeArguments */ && + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ + function tryGetClassExtendingExpressionWithTypeArguments(node) { + if (node.kind === 194 /* ExpressionWithTypeArguments */ && node.parent.token === 83 /* ExtendsKeyword */ && - isClassLike(node.parent.parent); + isClassLike(node.parent.parent)) { + return node.parent.parent; + } } - ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isDestructuringAssignment(node) { + if (isBinaryExpression(node)) { + if (node.operatorToken.kind === 56 /* EqualsToken */) { + var kind = node.left.kind; + return kind === 171 /* ObjectLiteralExpression */ + || kind === 170 /* ArrayLiteralExpression */; + } + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; // Returns false if this heritage clause element's expression contains something unsupported // (i.e. not a name or dotted name). function isSupportedExpressionWithTypeArguments(node) { @@ -7529,6 +8671,15 @@ var ts; return false; } } + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isEntityNameExpression(node) { + return node.kind === 69 /* Identifier */ || + node.kind === 172 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + } + ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) || (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node); @@ -7546,7 +8697,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { @@ -7557,6 +8708,11 @@ var ts; return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ + function tryExtractTypeScriptExtension(fileName) { + return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -7626,7 +8782,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -7685,6 +8841,847 @@ var ts; return carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; + /** + * Tests whether a node and its subtree is simple enough to have its position + * information ignored when emitting source maps in a destructuring assignment. + * + * @param node The expression to test. + */ + function isSimpleExpression(node) { + return isSimpleExpressionWorker(node, 0); + } + ts.isSimpleExpression = isSimpleExpression; + function isSimpleExpressionWorker(node, depth) { + if (depth <= 5) { + var kind = node.kind; + if (kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 10 /* RegularExpressionLiteral */ + || kind === 11 /* NoSubstitutionTemplateLiteral */ + || kind === 69 /* Identifier */ + || kind === 97 /* ThisKeyword */ + || kind === 95 /* SuperKeyword */ + || kind === 99 /* TrueKeyword */ + || kind === 84 /* FalseKeyword */ + || kind === 93 /* NullKeyword */) { + return true; + } + else if (kind === 172 /* PropertyAccessExpression */) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 173 /* ElementAccessExpression */) { + return isSimpleExpressionWorker(node.expression, depth + 1) + && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + } + else if (kind === 185 /* PrefixUnaryExpression */ + || kind === 186 /* PostfixUnaryExpression */) { + return isSimpleExpressionWorker(node.operand, depth + 1); + } + else if (kind === 187 /* BinaryExpression */) { + return node.operatorToken.kind !== 38 /* AsteriskAsteriskToken */ + && isSimpleExpressionWorker(node.left, depth + 1) + && isSimpleExpressionWorker(node.right, depth + 1); + } + else if (kind === 188 /* ConditionalExpression */) { + return isSimpleExpressionWorker(node.condition, depth + 1) + && isSimpleExpressionWorker(node.whenTrue, depth + 1) + && isSimpleExpressionWorker(node.whenFalse, depth + 1); + } + else if (kind === 183 /* VoidExpression */ + || kind === 182 /* TypeOfExpression */ + || kind === 181 /* DeleteExpression */) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 170 /* ArrayLiteralExpression */) { + return node.elements.length === 0; + } + else if (kind === 171 /* ObjectLiteralExpression */) { + return node.properties.length === 0; + } + else if (kind === 174 /* CallExpression */) { + if (!isSimpleExpressionWorker(node.expression, depth + 1)) { + return false; + } + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (!isSimpleExpressionWorker(argument, depth + 1)) { + return false; + } + } + return true; + } + } + return false; + } + var syntaxKindCache = ts.createMap(); + function formatSyntaxKind(kind) { + var syntaxKindEnum = ts.SyntaxKind; + if (syntaxKindEnum) { + if (syntaxKindCache[kind]) { + return syntaxKindCache[kind]; + } + for (var name_7 in syntaxKindEnum) { + if (syntaxKindEnum[name_7] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_7 + ")"; + } + } + } + else { + return kind.toString(); + } + } + ts.formatSyntaxKind = formatSyntaxKind; + /** + * Increases (or decreases) a position by the provided amount. + * + * @param pos The position. + * @param value The delta. + */ + function movePos(pos, value) { + return positionIsSynthesized(pos) ? -1 : pos + value; + } + ts.movePos = movePos; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ + function createRange(pos, end) { + return { pos: pos, end: end }; + } + ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange from a provided range with its end position collapsed to its + * start position. + * + * @param range A TextRange. + */ + function collapseRangeToStart(range) { + return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); + } + ts.collapseRangeToStart = collapseRangeToStart; + /** + * Creates a new TextRange from a provided range with its start position collapsed to its + * end position. + * + * @param range A TextRange. + */ + function collapseRangeToEnd(range) { + return isCollapsedRange(range) ? range : moveRangePos(range, range.end); + } + ts.collapseRangeToEnd = collapseRangeToEnd; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function collectExternalModuleInfo(sourceFile, resolver) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 230 /* ImportDeclaration */: + if (!node.importClause || + resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { + // import "mod" + // import x from "mod" where x is referenced + // import * as x from "mod" where x is referenced + // import { x, y } from "mod" where at least one import is referenced + externalImports.push(node); + } + break; + case 229 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 240 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + // import x = require("mod") where x is referenced + externalImports.push(node); + } + break; + case 236 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + } + else if (resolver.isValueAliasDeclaration(node)) { + // export { x, y } from "mod" where at least one export is a value symbol + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + var name_8 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_8] || (exportSpecifiers[name_8] = [])).push(specifier); + } + } + break; + case 235 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + /** + * Gets a value indicating whether a node is merged with a class declaration in the same scope. + */ + function isMergedWithClass(node) { + if (node.symbol) { + for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 221 /* ClassDeclaration */ && declaration !== node) { + return true; + } + } + } + return false; + } + ts.isMergedWithClass = isMergedWithClass; + /** + * Gets a value indicating whether a node is the first declaration of its kind. + * + * @param node A Declaration node. + * @param kind The SyntaxKind to find among related declarations. + */ + function isFirstDeclarationOfKind(node, kind) { + return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; + } + ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; + // Node tests + // + // All node tests in the following list should *not* reference parent pointers so that + // they may be used with transformations. + // Node Arrays + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 11 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isTextualLiteralKind(kind) { + return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; + } + ts.isTextualLiteralKind = isTextualLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + function isTemplateLiteralKind(kind) { + return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralFragmentKind(kind) { + return kind === 12 /* TemplateHead */ + || kind === 13 /* TemplateMiddle */ + || kind === 14 /* TemplateTail */; + } + function isTemplateLiteralFragment(node) { + return isTemplateLiteralFragmentKind(node.kind); + } + ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + // Identifiers + function isIdentifier(node) { + return node.kind === 69 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + function isGeneratedIdentifier(node) { + // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. + return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + // Names + function isQualifiedName(node) { + return node.kind === 139 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 140 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isEntityName(node) { + var kind = node.kind; + return kind === 139 /* QualifiedName */ + || kind === 69 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 140 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isModuleName(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 9 /* StringLiteral */; + } + ts.isModuleName = isModuleName; + function isBindingName(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 167 /* ObjectBindingPattern */ + || kind === 168 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Signature elements + function isTypeParameter(node) { + return node.kind === 141 /* TypeParameter */; + } + ts.isTypeParameter = isTypeParameter; + function isParameter(node) { + return node.kind === 142 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 143 /* Decorator */; + } + ts.isDecorator = isDecorator; + // Type members + function isMethodDeclaration(node) { + return node.kind === 147 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isClassElement(node) { + var kind = node.kind; + return kind === 148 /* Constructor */ + || kind === 145 /* PropertyDeclaration */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 153 /* IndexSignature */ + || kind === 198 /* SemicolonClassElement */; + } + ts.isClassElement = isClassElement; + function isObjectLiteralElementLike(node) { + var kind = node.kind; + return kind === 253 /* PropertyAssignment */ + || kind === 254 /* ShorthandPropertyAssignment */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 239 /* MissingDeclaration */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + function isTypeNodeKind(kind) { + return (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) + || kind === 117 /* AnyKeyword */ + || kind === 130 /* NumberKeyword */ + || kind === 120 /* BooleanKeyword */ + || kind === 132 /* StringKeyword */ + || kind === 133 /* SymbolKeyword */ + || kind === 103 /* VoidKeyword */ + || kind === 127 /* NeverKeyword */ + || kind === 194 /* ExpressionWithTypeArguments */; + } + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + // Binding patterns + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 168 /* ArrayBindingPattern */ + || kind === 167 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isBindingElement(node) { + return node.kind === 169 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 169 /* BindingElement */ + || kind === 193 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + // Expression + function isPropertyAccessExpression(node) { + return node.kind === 172 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 173 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isBinaryExpression(node) { + return node.kind === 187 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 188 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isCallExpression(node) { + return node.kind === 174 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isTemplate(node) { + var kind = node.kind; + return kind === 189 /* TemplateExpression */ + || kind === 11 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplate = isTemplate; + function isSpreadElementExpression(node) { + return node.kind === 191 /* SpreadElementExpression */; + } + ts.isSpreadElementExpression = isSpreadElementExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 194 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isLeftHandSideExpressionKind(kind) { + return kind === 172 /* PropertyAccessExpression */ + || kind === 173 /* ElementAccessExpression */ + || kind === 175 /* NewExpression */ + || kind === 174 /* CallExpression */ + || kind === 241 /* JsxElement */ + || kind === 242 /* JsxSelfClosingElement */ + || kind === 176 /* TaggedTemplateExpression */ + || kind === 170 /* ArrayLiteralExpression */ + || kind === 178 /* ParenthesizedExpression */ + || kind === 171 /* ObjectLiteralExpression */ + || kind === 192 /* ClassExpression */ + || kind === 179 /* FunctionExpression */ + || kind === 69 /* Identifier */ + || kind === 10 /* RegularExpressionLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 9 /* StringLiteral */ + || kind === 11 /* NoSubstitutionTemplateLiteral */ + || kind === 189 /* TemplateExpression */ + || kind === 84 /* FalseKeyword */ + || kind === 93 /* NullKeyword */ + || kind === 97 /* ThisKeyword */ + || kind === 99 /* TrueKeyword */ + || kind === 95 /* SuperKeyword */ + || kind === 196 /* NonNullExpression */; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 185 /* PrefixUnaryExpression */ + || kind === 186 /* PostfixUnaryExpression */ + || kind === 181 /* DeleteExpression */ + || kind === 182 /* TypeOfExpression */ + || kind === 183 /* VoidExpression */ + || kind === 184 /* AwaitExpression */ + || kind === 177 /* TypeAssertionExpression */ + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 188 /* ConditionalExpression */ + || kind === 190 /* YieldExpression */ + || kind === 180 /* ArrowFunction */ + || kind === 187 /* BinaryExpression */ + || kind === 191 /* SpreadElementExpression */ + || kind === 195 /* AsExpression */ + || kind === 193 /* OmittedExpression */ + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 177 /* TypeAssertionExpression */ + || kind === 195 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isOmittedExpression(node) { + return node.kind === 193 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + // Misc + function isTemplateSpan(node) { + return node.kind === 197 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + // Element + function isBlock(node) { + return node.kind === 199 /* Block */; + } + ts.isBlock = isBlock; + function isConciseBody(node) { + return isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isVariableDeclaration(node) { + return node.kind === 218 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 219 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isCaseBlock(node) { + return node.kind === 227 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isModuleBody(node) { + var kind = node.kind; + return kind === 226 /* ModuleBlock */ + || kind === 225 /* ModuleDeclaration */; + } + ts.isModuleBody = isModuleBody; + function isImportEqualsDeclaration(node) { + return node.kind === 229 /* ImportEqualsDeclaration */; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportClause(node) { + return node.kind === 231 /* ImportClause */; + } + ts.isImportClause = isImportClause; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 233 /* NamedImports */ + || kind === 232 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isImportSpecifier(node) { + return node.kind === 234 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isNamedExports(node) { + return node.kind === 237 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 238 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isModuleOrEnumDeclaration(node) { + return node.kind === 225 /* ModuleDeclaration */ || node.kind === 224 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 180 /* ArrowFunction */ + || kind === 169 /* BindingElement */ + || kind === 221 /* ClassDeclaration */ + || kind === 192 /* ClassExpression */ + || kind === 148 /* Constructor */ + || kind === 224 /* EnumDeclaration */ + || kind === 255 /* EnumMember */ + || kind === 238 /* ExportSpecifier */ + || kind === 220 /* FunctionDeclaration */ + || kind === 179 /* FunctionExpression */ + || kind === 149 /* GetAccessor */ + || kind === 231 /* ImportClause */ + || kind === 229 /* ImportEqualsDeclaration */ + || kind === 234 /* ImportSpecifier */ + || kind === 222 /* InterfaceDeclaration */ + || kind === 147 /* MethodDeclaration */ + || kind === 146 /* MethodSignature */ + || kind === 225 /* ModuleDeclaration */ + || kind === 228 /* NamespaceExportDeclaration */ + || kind === 232 /* NamespaceImport */ + || kind === 142 /* Parameter */ + || kind === 253 /* PropertyAssignment */ + || kind === 145 /* PropertyDeclaration */ + || kind === 144 /* PropertySignature */ + || kind === 150 /* SetAccessor */ + || kind === 254 /* ShorthandPropertyAssignment */ + || kind === 223 /* TypeAliasDeclaration */ + || kind === 141 /* TypeParameter */ + || kind === 218 /* VariableDeclaration */ + || kind === 279 /* JSDocTypedefTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 220 /* FunctionDeclaration */ + || kind === 239 /* MissingDeclaration */ + || kind === 221 /* ClassDeclaration */ + || kind === 222 /* InterfaceDeclaration */ + || kind === 223 /* TypeAliasDeclaration */ + || kind === 224 /* EnumDeclaration */ + || kind === 225 /* ModuleDeclaration */ + || kind === 230 /* ImportDeclaration */ + || kind === 229 /* ImportEqualsDeclaration */ + || kind === 236 /* ExportDeclaration */ + || kind === 235 /* ExportAssignment */ + || kind === 228 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 210 /* BreakStatement */ + || kind === 209 /* ContinueStatement */ + || kind === 217 /* DebuggerStatement */ + || kind === 204 /* DoStatement */ + || kind === 202 /* ExpressionStatement */ + || kind === 201 /* EmptyStatement */ + || kind === 207 /* ForInStatement */ + || kind === 208 /* ForOfStatement */ + || kind === 206 /* ForStatement */ + || kind === 203 /* IfStatement */ + || kind === 214 /* LabeledStatement */ + || kind === 211 /* ReturnStatement */ + || kind === 213 /* SwitchStatement */ + || kind === 215 /* ThrowStatement */ + || kind === 216 /* TryStatement */ + || kind === 200 /* VariableStatement */ + || kind === 205 /* WhileStatement */ + || kind === 212 /* WithStatement */ + || kind === 287 /* NotEmittedStatement */; + } + function isDeclaration(node) { + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 199 /* Block */; + } + ts.isStatement = isStatement; + // Module references + function isModuleReference(node) { + var kind = node.kind; + return kind === 240 /* ExternalModuleReference */ + || kind === 139 /* QualifiedName */ + || kind === 69 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + function isJsxOpeningElement(node) { + return node.kind === 243 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 245 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 97 /* ThisKeyword */ + || kind === 69 /* Identifier */ + || kind === 172 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 241 /* JsxElement */ + || kind === 248 /* JsxExpression */ + || kind === 242 /* JsxSelfClosingElement */ + || kind === 244 /* JsxText */; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 246 /* JsxAttribute */ + || kind === 247 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isJsxSpreadAttribute(node) { + return node.kind === 247 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxAttribute(node) { + return node.kind === 246 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 248 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 249 /* CaseClause */ + || kind === 250 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isHeritageClause(node) { + return node.kind === 251 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 252 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 253 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 254 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 255 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 256 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; function isWatchSet(options) { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); @@ -7913,30 +9910,2542 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 169 /* BindingElement */ || ts.isBindingPattern(node))) { + node = node.parent; + } + return node; } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return str.indexOf(suffix, expectedPos) === expectedPos; + function getCombinedModifierFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = ts.getModifierFlags(node); + if (node.kind === 218 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 219 /* VariableDeclarationList */) { + flags |= ts.getModifierFlags(node); + node = node.parent; + } + if (node && node.kind === 200 /* VariableStatement */) { + flags |= ts.getModifierFlags(node); + } + return flags; + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 218 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 219 /* VariableDeclarationList */) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 200 /* VariableStatement */) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + var NodeConstructor; + var SourceFileConstructor; + function createNode(kind, location, flags) { + var ConstructorForKind = kind === 256 /* SourceFile */ + ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) + : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); + var node = location + ? new ConstructorForKind(kind, location.pos, location.end) + : new ConstructorForKind(kind, /*pos*/ -1, /*end*/ -1); + node.flags = flags | 8 /* Synthesized */; + return node; + } + function updateNode(updated, original) { + if (updated !== original) { + setOriginalNode(updated, original); + if (original.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + } + return updated; + } + ts.updateNode = updateNode; + function createNodeArray(elements, location, hasTrailingComma) { + if (elements) { + if (ts.isNodeArray(elements)) { + return elements; + } + } + else { + elements = []; + } + var array = elements; + if (location) { + array.pos = location.pos; + array.end = location.end; + } + else { + array.pos = -1; + array.end = -1; + } + if (hasTrailingComma) { + array.hasTrailingComma = true; + } + return array; + } + ts.createNodeArray = createNodeArray; + function createSynthesizedNode(kind, startsOnNewLine) { + var node = createNode(kind, /*location*/ undefined); + node.startsOnNewLine = startsOnNewLine; + return node; + } + ts.createSynthesizedNode = createSynthesizedNode; + function createSynthesizedNodeArray(elements) { + return createNodeArray(elements, /*location*/ undefined); + } + ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + var clone = createNode(node.kind, /*location*/ undefined, node.flags); + clone.original = node; + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + ts.getSynthesizedClone = getSynthesizedClone; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ + function getMutableClone(node) { + var clone = getSynthesizedClone(node); + clone.pos = node.pos; + clone.end = node.end; + clone.parent = node.parent; + return clone; + } + ts.getMutableClone = getMutableClone; + function createLiteral(value, location) { + if (typeof value === "number") { + var node = createNode(8 /* NumericLiteral */, location, /*flags*/ undefined); + node.text = value.toString(); + return node; + } + else if (typeof value === "boolean") { + return createNode(value ? 99 /* TrueKeyword */ : 84 /* FalseKeyword */, location, /*flags*/ undefined); + } + else if (typeof value === "string") { + var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); + node.text = value; + return node; + } + else { + var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); + node.textSourceNode = value; + node.text = value.text; + return node; + } + } + ts.createLiteral = createLiteral; + // Identifiers + var nextAutoGenerateId = 0; + function createIdentifier(text, location) { + var node = createNode(69 /* Identifier */, location); + node.text = ts.escapeIdentifier(text); + node.originalKeywordKind = ts.stringToToken(text); + node.autoGenerateKind = 0 /* None */; + node.autoGenerateId = 0; + return node; + } + ts.createIdentifier = createIdentifier; + function createTempVariable(recordTempVariable, location) { + var name = createNode(69 /* Identifier */, location); + name.text = ""; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + if (recordTempVariable) { + recordTempVariable(name); + } + return name; + } + ts.createTempVariable = createTempVariable; + function createLoopVariable(location) { + var name = createNode(69 /* Identifier */, location); + name.text = ""; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createLoopVariable = createLoopVariable; + function createUniqueName(text, location) { + var name = createNode(69 /* Identifier */, location); + name.text = text; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createUniqueName = createUniqueName; + function getGeneratedNameForNode(node, location) { + var name = createNode(69 /* Identifier */, location); + name.original = node; + name.text = ""; + name.originalKeywordKind = 0 /* Unknown */; + name.autoGenerateKind = 4 /* Node */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation + function createToken(token) { + return createNode(token); + } + ts.createToken = createToken; + // Reserved words + function createSuper() { + var node = createNode(95 /* SuperKeyword */); + return node; + } + ts.createSuper = createSuper; + function createThis(location) { + var node = createNode(97 /* ThisKeyword */, location); + return node; + } + ts.createThis = createThis; + function createNull() { + var node = createNode(93 /* NullKeyword */); + return node; + } + ts.createNull = createNull; + // Names + function createComputedPropertyName(expression, location) { + var node = createNode(140 /* ComputedPropertyName */, location); + node.expression = expression; + return node; + } + ts.createComputedPropertyName = createComputedPropertyName; + function updateComputedPropertyName(node, expression) { + if (node.expression !== expression) { + return updateNode(createComputedPropertyName(expression, node), node); + } + return node; + } + ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements + function createParameter(name, initializer, location) { + return createParameterDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, + /*type*/ undefined, initializer, location); + } + ts.createParameter = createParameter; + function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(142 /* Parameter */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createParameterDeclaration = createParameterDeclaration; + function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); + } + return node; + } + ts.updateParameterDeclaration = updateParameterDeclaration; + // Type members + function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { + var node = createNode(145 /* PropertyDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = questionToken; + node.type = type; + node.initializer = initializer; + return node; + } + ts.createProperty = createProperty; + function updateProperty(node, decorators, modifiers, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer, node), node); + } + return node; + } + ts.updateProperty = updateProperty; + function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(147 /* MethodDeclaration */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createMethod = createMethod; + function updateMethod(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createMethod(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateMethod = updateMethod; + function createConstructor(decorators, modifiers, parameters, body, location, flags) { + var node = createNode(148 /* Constructor */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = undefined; + node.body = body; + return node; + } + ts.createConstructor = createConstructor; + function updateConstructor(node, decorators, modifiers, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body) { + return updateNode(createConstructor(decorators, modifiers, parameters, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateConstructor = updateConstructor; + function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { + var node = createNode(149 /* GetAccessor */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createGetAccessor = createGetAccessor; + function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateGetAccessor = updateGetAccessor; + function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { + var node = createNode(150 /* SetAccessor */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = undefined; + node.parameters = createNodeArray(parameters); + node.body = body; + return node; + } + ts.createSetAccessor = createSetAccessor; + function updateSetAccessor(node, decorators, modifiers, name, parameters, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body) { + return updateNode(createSetAccessor(decorators, modifiers, name, parameters, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateSetAccessor = updateSetAccessor; + // Binding Patterns + function createObjectBindingPattern(elements, location) { + var node = createNode(167 /* ObjectBindingPattern */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createObjectBindingPattern = createObjectBindingPattern; + function updateObjectBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createObjectBindingPattern(elements, node), node); + } + return node; + } + ts.updateObjectBindingPattern = updateObjectBindingPattern; + function createArrayBindingPattern(elements, location) { + var node = createNode(168 /* ArrayBindingPattern */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createArrayBindingPattern = createArrayBindingPattern; + function updateArrayBindingPattern(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayBindingPattern(elements, node), node); + } + return node; + } + ts.updateArrayBindingPattern = updateArrayBindingPattern; + function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { + var node = createNode(169 /* BindingElement */, location); + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + node.dotDotDotToken = dotDotDotToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.initializer = initializer; + return node; + } + ts.createBindingElement = createBindingElement; + function updateBindingElement(node, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + } + return node; + } + ts.updateBindingElement = updateBindingElement; + // Expression + function createArrayLiteral(elements, location, multiLine) { + var node = createNode(170 /* ArrayLiteralExpression */, location); + node.elements = parenthesizeListElements(createNodeArray(elements)); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createArrayLiteral = createArrayLiteral; + function updateArrayLiteral(node, elements) { + if (node.elements !== elements) { + return updateNode(createArrayLiteral(elements, node, node.multiLine), node); + } + return node; + } + ts.updateArrayLiteral = updateArrayLiteral; + function createObjectLiteral(properties, location, multiLine) { + var node = createNode(171 /* ObjectLiteralExpression */, location); + node.properties = createNodeArray(properties); + if (multiLine) { + node.multiLine = true; + } + return node; + } + ts.createObjectLiteral = createObjectLiteral; + function updateObjectLiteral(node, properties) { + if (node.properties !== properties) { + return updateNode(createObjectLiteral(properties, node, node.multiLine), node); + } + return node; + } + ts.updateObjectLiteral = updateObjectLiteral; + function createPropertyAccess(expression, name, location, flags) { + var node = createNode(172 /* PropertyAccessExpression */, location, flags); + node.expression = parenthesizeForAccess(expression); + node.emitFlags = 1048576 /* NoIndentation */; + node.name = typeof name === "string" ? createIdentifier(name) : name; + return node; + } + ts.createPropertyAccess = createPropertyAccess; + function updatePropertyAccess(node, expression, name) { + if (node.expression !== expression || node.name !== name) { + var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); + // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess + propertyAccess.emitFlags = node.emitFlags; + return updateNode(propertyAccess, node); + } + return node; + } + ts.updatePropertyAccess = updatePropertyAccess; + function createElementAccess(expression, index, location) { + var node = createNode(173 /* ElementAccessExpression */, location); + node.expression = parenthesizeForAccess(expression); + node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; + return node; + } + ts.createElementAccess = createElementAccess; + function updateElementAccess(node, expression, argumentExpression) { + if (node.expression !== expression || node.argumentExpression !== argumentExpression) { + return updateNode(createElementAccess(expression, argumentExpression, node), node); + } + return node; + } + ts.updateElementAccess = updateElementAccess; + function createCall(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(174 /* CallExpression */, location, flags); + node.expression = parenthesizeForAccess(expression); + if (typeArguments) { + node.typeArguments = createNodeArray(typeArguments); + } + node.arguments = parenthesizeListElements(createNodeArray(argumentsArray)); + return node; + } + ts.createCall = createCall; + function updateCall(node, expression, typeArguments, argumentsArray) { + if (expression !== node.expression || typeArguments !== node.typeArguments || argumentsArray !== node.arguments) { + return updateNode(createCall(expression, typeArguments, argumentsArray, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateCall = updateCall; + function createNew(expression, typeArguments, argumentsArray, location, flags) { + var node = createNode(175 /* NewExpression */, location, flags); + node.expression = parenthesizeForNew(expression); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; + return node; + } + ts.createNew = createNew; + function updateNew(node, expression, typeArguments, argumentsArray) { + if (node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray) { + return updateNode(createNew(expression, typeArguments, argumentsArray, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateNew = updateNew; + function createTaggedTemplate(tag, template, location) { + var node = createNode(176 /* TaggedTemplateExpression */, location); + node.tag = parenthesizeForAccess(tag); + node.template = template; + return node; + } + ts.createTaggedTemplate = createTaggedTemplate; + function updateTaggedTemplate(node, tag, template) { + if (node.tag !== tag || node.template !== template) { + return updateNode(createTaggedTemplate(tag, template, node), node); + } + return node; + } + ts.updateTaggedTemplate = updateTaggedTemplate; + function createParen(expression, location) { + var node = createNode(178 /* ParenthesizedExpression */, location); + node.expression = expression; + return node; + } + ts.createParen = createParen; + function updateParen(node, expression) { + if (node.expression !== expression) { + return updateNode(createParen(expression, node), node); + } + return node; + } + ts.updateParen = updateParen; + function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(179 /* FunctionExpression */, location, flags); + node.modifiers = undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionExpression = createFunctionExpression; + function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateFunctionExpression = updateFunctionExpression; + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { + var node = createNode(180 /* ArrowFunction */, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.body = parenthesizeConciseBody(body); + return node; + } + ts.createArrowFunction = createArrowFunction; + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + if (node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateArrowFunction = updateArrowFunction; + function createDelete(expression, location) { + var node = createNode(181 /* DeleteExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createDelete = createDelete; + function updateDelete(node, expression) { + if (node.expression !== expression) { + return updateNode(createDelete(expression, node), expression); + } + return node; + } + ts.updateDelete = updateDelete; + function createTypeOf(expression, location) { + var node = createNode(182 /* TypeOfExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createTypeOf = createTypeOf; + function updateTypeOf(node, expression) { + if (node.expression !== expression) { + return updateNode(createTypeOf(expression, node), expression); + } + return node; + } + ts.updateTypeOf = updateTypeOf; + function createVoid(expression, location) { + var node = createNode(183 /* VoidExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createVoid = createVoid; + function updateVoid(node, expression) { + if (node.expression !== expression) { + return updateNode(createVoid(expression, node), node); + } + return node; + } + ts.updateVoid = updateVoid; + function createAwait(expression, location) { + var node = createNode(184 /* AwaitExpression */, location); + node.expression = parenthesizePrefixOperand(expression); + return node; + } + ts.createAwait = createAwait; + function updateAwait(node, expression) { + if (node.expression !== expression) { + return updateNode(createAwait(expression, node), node); + } + return node; + } + ts.updateAwait = updateAwait; + function createPrefix(operator, operand, location) { + var node = createNode(185 /* PrefixUnaryExpression */, location); + node.operator = operator; + node.operand = parenthesizePrefixOperand(operand); + return node; + } + ts.createPrefix = createPrefix; + function updatePrefix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPrefix(node.operator, operand, node), node); + } + return node; + } + ts.updatePrefix = updatePrefix; + function createPostfix(operand, operator, location) { + var node = createNode(186 /* PostfixUnaryExpression */, location); + node.operand = parenthesizePostfixOperand(operand); + node.operator = operator; + return node; + } + ts.createPostfix = createPostfix; + function updatePostfix(node, operand) { + if (node.operand !== operand) { + return updateNode(createPostfix(operand, node.operator, node), node); + } + return node; + } + ts.updatePostfix = updatePostfix; + function createBinary(left, operator, right, location) { + var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorKind = operatorToken.kind; + var node = createNode(187 /* BinaryExpression */, location); + node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); + node.operatorToken = operatorToken; + node.right = parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); + return node; + } + ts.createBinary = createBinary; + function updateBinary(node, left, right) { + if (node.left !== left || node.right !== right) { + return updateNode(createBinary(left, node.operatorToken, right, /*location*/ node), node); + } + return node; + } + ts.updateBinary = updateBinary; + function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { + var node = createNode(188 /* ConditionalExpression */, location); + node.condition = condition; + node.questionToken = questionToken; + node.whenTrue = whenTrue; + node.colonToken = colonToken; + node.whenFalse = whenFalse; + return node; + } + ts.createConditional = createConditional; + function updateConditional(node, condition, whenTrue, whenFalse) { + if (node.condition !== condition || node.whenTrue !== whenTrue || node.whenFalse !== whenFalse) { + return updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse, node), node); + } + return node; + } + ts.updateConditional = updateConditional; + function createTemplateExpression(head, templateSpans, location) { + var node = createNode(189 /* TemplateExpression */, location); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + return node; + } + ts.createTemplateExpression = createTemplateExpression; + function updateTemplateExpression(node, head, templateSpans) { + if (node.head !== head || node.templateSpans !== templateSpans) { + return updateNode(createTemplateExpression(head, templateSpans, node), node); + } + return node; + } + ts.updateTemplateExpression = updateTemplateExpression; + function createYield(asteriskToken, expression, location) { + var node = createNode(190 /* YieldExpression */, location); + node.asteriskToken = asteriskToken; + node.expression = expression; + return node; + } + ts.createYield = createYield; + function updateYield(node, expression) { + if (node.expression !== expression) { + return updateNode(createYield(node.asteriskToken, expression, node), node); + } + return node; + } + ts.updateYield = updateYield; + function createSpread(expression, location) { + var node = createNode(191 /* SpreadElementExpression */, location); + node.expression = parenthesizeExpressionForList(expression); + return node; + } + ts.createSpread = createSpread; + function updateSpread(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpread(expression, node), node); + } + return node; + } + ts.updateSpread = updateSpread; + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(192 /* ClassExpression */, location); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassExpression = createClassExpression; + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + if (node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassExpression = updateClassExpression; + function createOmittedExpression(location) { + var node = createNode(193 /* OmittedExpression */, location); + return node; + } + ts.createOmittedExpression = createOmittedExpression; + function createExpressionWithTypeArguments(typeArguments, expression, location) { + var node = createNode(194 /* ExpressionWithTypeArguments */, location); + node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; + node.expression = parenthesizeForAccess(expression); + return node; + } + ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node, typeArguments, expression) { + if (node.typeArguments !== typeArguments || node.expression !== expression) { + return updateNode(createExpressionWithTypeArguments(typeArguments, expression, node), node); + } + return node; + } + ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; + // Misc + function createTemplateSpan(expression, literal, location) { + var node = createNode(197 /* TemplateSpan */, location); + node.expression = expression; + node.literal = literal; + return node; + } + ts.createTemplateSpan = createTemplateSpan; + function updateTemplateSpan(node, expression, literal) { + if (node.expression !== expression || node.literal !== literal) { + return updateNode(createTemplateSpan(expression, literal, node), node); + } + return node; + } + ts.updateTemplateSpan = updateTemplateSpan; + // Element + function createBlock(statements, location, multiLine, flags) { + var block = createNode(199 /* Block */, location, flags); + block.statements = createNodeArray(statements); + if (multiLine) { + block.multiLine = true; + } + return block; + } + ts.createBlock = createBlock; + function updateBlock(node, statements) { + if (statements !== node.statements) { + return updateNode(createBlock(statements, /*location*/ node, node.multiLine, node.flags), node); + } + return node; + } + ts.updateBlock = updateBlock; + function createVariableStatement(modifiers, declarationList, location, flags) { + var node = createNode(200 /* VariableStatement */, location, flags); + node.decorators = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + return node; + } + ts.createVariableStatement = createVariableStatement; + function updateVariableStatement(node, modifiers, declarationList) { + if (node.modifiers !== modifiers || node.declarationList !== declarationList) { + return updateNode(createVariableStatement(modifiers, declarationList, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateVariableStatement = updateVariableStatement; + function createVariableDeclarationList(declarations, location, flags) { + var node = createNode(219 /* VariableDeclarationList */, location, flags); + node.declarations = createNodeArray(declarations); + return node; + } + ts.createVariableDeclarationList = createVariableDeclarationList; + function updateVariableDeclarationList(node, declarations) { + if (node.declarations !== declarations) { + return updateNode(createVariableDeclarationList(declarations, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateVariableDeclarationList = updateVariableDeclarationList; + function createVariableDeclaration(name, type, initializer, location, flags) { + var node = createNode(218 /* VariableDeclaration */, location, flags); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.type = type; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createVariableDeclaration = createVariableDeclaration; + function updateVariableDeclaration(node, name, type, initializer) { + if (node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createVariableDeclaration(name, type, initializer, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateVariableDeclaration = updateVariableDeclaration; + function createEmptyStatement(location) { + return createNode(201 /* EmptyStatement */, location); + } + ts.createEmptyStatement = createEmptyStatement; + function createStatement(expression, location, flags) { + var node = createNode(202 /* ExpressionStatement */, location, flags); + node.expression = parenthesizeExpressionForExpressionStatement(expression); + return node; + } + ts.createStatement = createStatement; + function updateStatement(node, expression) { + if (node.expression !== expression) { + return updateNode(createStatement(expression, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateStatement = updateStatement; + function createIf(expression, thenStatement, elseStatement, location) { + var node = createNode(203 /* IfStatement */, location); + node.expression = expression; + node.thenStatement = thenStatement; + node.elseStatement = elseStatement; + return node; + } + ts.createIf = createIf; + function updateIf(node, expression, thenStatement, elseStatement) { + if (node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement) { + return updateNode(createIf(expression, thenStatement, elseStatement, /*location*/ node), node); + } + return node; + } + ts.updateIf = updateIf; + function createDo(statement, expression, location) { + var node = createNode(204 /* DoStatement */, location); + node.statement = statement; + node.expression = expression; + return node; + } + ts.createDo = createDo; + function updateDo(node, statement, expression) { + if (node.statement !== statement || node.expression !== expression) { + return updateNode(createDo(statement, expression, node), node); + } + return node; + } + ts.updateDo = updateDo; + function createWhile(expression, statement, location) { + var node = createNode(205 /* WhileStatement */, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWhile = createWhile; + function updateWhile(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWhile(expression, statement, node), node); + } + return node; + } + ts.updateWhile = updateWhile; + function createFor(initializer, condition, incrementor, statement, location) { + var node = createNode(206 /* ForStatement */, location, /*flags*/ undefined); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = statement; + return node; + } + ts.createFor = createFor; + function updateFor(node, initializer, condition, incrementor, statement) { + if (node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement) { + return updateNode(createFor(initializer, condition, incrementor, statement, node), node); + } + return node; + } + ts.updateFor = updateFor; + function createForIn(initializer, expression, statement, location) { + var node = createNode(207 /* ForInStatement */, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForIn = createForIn; + function updateForIn(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForIn(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForIn = updateForIn; + function createForOf(initializer, expression, statement, location) { + var node = createNode(208 /* ForOfStatement */, location); + node.initializer = initializer; + node.expression = expression; + node.statement = statement; + return node; + } + ts.createForOf = createForOf; + function updateForOf(node, initializer, expression, statement) { + if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) { + return updateNode(createForOf(initializer, expression, statement, node), node); + } + return node; + } + ts.updateForOf = updateForOf; + function createContinue(label, location) { + var node = createNode(209 /* ContinueStatement */, location); + if (label) { + node.label = label; + } + return node; + } + ts.createContinue = createContinue; + function updateContinue(node, label) { + if (node.label !== label) { + return updateNode(createContinue(label, node), node); + } + return node; + } + ts.updateContinue = updateContinue; + function createBreak(label, location) { + var node = createNode(210 /* BreakStatement */, location); + if (label) { + node.label = label; + } + return node; + } + ts.createBreak = createBreak; + function updateBreak(node, label) { + if (node.label !== label) { + return updateNode(createBreak(label, node), node); + } + return node; + } + ts.updateBreak = updateBreak; + function createReturn(expression, location) { + var node = createNode(211 /* ReturnStatement */, location); + node.expression = expression; + return node; + } + ts.createReturn = createReturn; + function updateReturn(node, expression) { + if (node.expression !== expression) { + return updateNode(createReturn(expression, /*location*/ node), node); + } + return node; + } + ts.updateReturn = updateReturn; + function createWith(expression, statement, location) { + var node = createNode(212 /* WithStatement */, location); + node.expression = expression; + node.statement = statement; + return node; + } + ts.createWith = createWith; + function updateWith(node, expression, statement) { + if (node.expression !== expression || node.statement !== statement) { + return updateNode(createWith(expression, statement, node), node); + } + return node; + } + ts.updateWith = updateWith; + function createSwitch(expression, caseBlock, location) { + var node = createNode(213 /* SwitchStatement */, location); + node.expression = parenthesizeExpressionForList(expression); + node.caseBlock = caseBlock; + return node; + } + ts.createSwitch = createSwitch; + function updateSwitch(node, expression, caseBlock) { + if (node.expression !== expression || node.caseBlock !== caseBlock) { + return updateNode(createSwitch(expression, caseBlock, node), node); + } + return node; + } + ts.updateSwitch = updateSwitch; + function createLabel(label, statement, location) { + var node = createNode(214 /* LabeledStatement */, location); + node.label = typeof label === "string" ? createIdentifier(label) : label; + node.statement = statement; + return node; + } + ts.createLabel = createLabel; + function updateLabel(node, label, statement) { + if (node.label !== label || node.statement !== statement) { + return updateNode(createLabel(label, statement, node), node); + } + return node; + } + ts.updateLabel = updateLabel; + function createThrow(expression, location) { + var node = createNode(215 /* ThrowStatement */, location); + node.expression = expression; + return node; + } + ts.createThrow = createThrow; + function updateThrow(node, expression) { + if (node.expression !== expression) { + return updateNode(createThrow(expression, node), node); + } + return node; + } + ts.updateThrow = updateThrow; + function createTry(tryBlock, catchClause, finallyBlock, location) { + var node = createNode(216 /* TryStatement */, location); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + return node; + } + ts.createTry = createTry; + function updateTry(node, tryBlock, catchClause, finallyBlock) { + if (node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock) { + return updateNode(createTry(tryBlock, catchClause, finallyBlock, node), node); + } + return node; + } + ts.updateTry = updateTry; + function createCaseBlock(clauses, location) { + var node = createNode(227 /* CaseBlock */, location); + node.clauses = createNodeArray(clauses); + return node; + } + ts.createCaseBlock = createCaseBlock; + function updateCaseBlock(node, clauses) { + if (node.clauses !== clauses) { + return updateNode(createCaseBlock(clauses, node), node); + } + return node; + } + ts.updateCaseBlock = updateCaseBlock; + function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(220 /* FunctionDeclaration */, location, flags); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.asteriskToken = asteriskToken; + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + return node; + } + ts.createFunctionDeclaration = createFunctionDeclaration; + function updateFunctionDeclaration(node, decorators, modifiers, name, typeParameters, parameters, type, body) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionDeclaration(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + } + return node; + } + ts.updateFunctionDeclaration = updateFunctionDeclaration; + function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { + var node = createNode(221 /* ClassDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.name = name; + node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; + node.heritageClauses = createNodeArray(heritageClauses); + node.members = createNodeArray(members); + return node; + } + ts.createClassDeclaration = createClassDeclaration; + function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) { + return updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, node), node); + } + return node; + } + ts.updateClassDeclaration = updateClassDeclaration; + function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { + var node = createNode(230 /* ImportDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createImportDeclaration = createImportDeclaration; + function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateImportDeclaration = updateImportDeclaration; + function createImportClause(name, namedBindings, location) { + var node = createNode(231 /* ImportClause */, location); + node.name = name; + node.namedBindings = namedBindings; + return node; + } + ts.createImportClause = createImportClause; + function updateImportClause(node, name, namedBindings) { + if (node.name !== name || node.namedBindings !== namedBindings) { + return updateNode(createImportClause(name, namedBindings, node), node); + } + return node; + } + ts.updateImportClause = updateImportClause; + function createNamespaceImport(name, location) { + var node = createNode(232 /* NamespaceImport */, location); + node.name = name; + return node; + } + ts.createNamespaceImport = createNamespaceImport; + function updateNamespaceImport(node, name) { + if (node.name !== name) { + return updateNode(createNamespaceImport(name, node), node); + } + return node; + } + ts.updateNamespaceImport = updateNamespaceImport; + function createNamedImports(elements, location) { + var node = createNode(233 /* NamedImports */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedImports = createNamedImports; + function updateNamedImports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedImports(elements, node), node); + } + return node; + } + ts.updateNamedImports = updateNamedImports; + function createImportSpecifier(propertyName, name, location) { + var node = createNode(234 /* ImportSpecifier */, location); + node.propertyName = propertyName; + node.name = name; + return node; + } + ts.createImportSpecifier = createImportSpecifier; + function updateImportSpecifier(node, propertyName, name) { + if (node.propertyName !== propertyName || node.name !== name) { + return updateNode(createImportSpecifier(propertyName, name, node), node); + } + return node; + } + ts.updateImportSpecifier = updateImportSpecifier; + function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { + var node = createNode(235 /* ExportAssignment */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.isExportEquals = isExportEquals; + node.expression = expression; + return node; + } + ts.createExportAssignment = createExportAssignment; + function updateExportAssignment(node, decorators, modifiers, expression) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.expression !== expression) { + return updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression, node), node); + } + return node; + } + ts.updateExportAssignment = updateExportAssignment; + function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { + var node = createNode(236 /* ExportDeclaration */, location); + node.decorators = decorators ? createNodeArray(decorators) : undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + return node; + } + ts.createExportDeclaration = createExportDeclaration; + function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier) { + return updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, node), node); + } + return node; + } + ts.updateExportDeclaration = updateExportDeclaration; + function createNamedExports(elements, location) { + var node = createNode(237 /* NamedExports */, location); + node.elements = createNodeArray(elements); + return node; + } + ts.createNamedExports = createNamedExports; + function updateNamedExports(node, elements) { + if (node.elements !== elements) { + return updateNode(createNamedExports(elements, node), node); + } + return node; + } + ts.updateNamedExports = updateNamedExports; + function createExportSpecifier(name, propertyName, location) { + var node = createNode(238 /* ExportSpecifier */, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; + return node; + } + ts.createExportSpecifier = createExportSpecifier; + function updateExportSpecifier(node, name, propertyName) { + if (node.name !== name || node.propertyName !== propertyName) { + return updateNode(createExportSpecifier(name, propertyName, node), node); + } + return node; + } + ts.updateExportSpecifier = updateExportSpecifier; + // JSX + function createJsxElement(openingElement, children, closingElement, location) { + var node = createNode(241 /* JsxElement */, location); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + return node; + } + ts.createJsxElement = createJsxElement; + function updateJsxElement(node, openingElement, children, closingElement) { + if (node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement) { + return updateNode(createJsxElement(openingElement, children, closingElement, node), node); + } + return node; + } + ts.updateJsxElement = updateJsxElement; + function createJsxSelfClosingElement(tagName, attributes, location) { + var node = createNode(242 /* JsxSelfClosingElement */, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxSelfClosingElement = createJsxSelfClosingElement; + function updateJsxSelfClosingElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxSelfClosingElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; + function createJsxOpeningElement(tagName, attributes, location) { + var node = createNode(243 /* JsxOpeningElement */, location); + node.tagName = tagName; + node.attributes = createNodeArray(attributes); + return node; + } + ts.createJsxOpeningElement = createJsxOpeningElement; + function updateJsxOpeningElement(node, tagName, attributes) { + if (node.tagName !== tagName || node.attributes !== attributes) { + return updateNode(createJsxOpeningElement(tagName, attributes, node), node); + } + return node; + } + ts.updateJsxOpeningElement = updateJsxOpeningElement; + function createJsxClosingElement(tagName, location) { + var node = createNode(245 /* JsxClosingElement */, location); + node.tagName = tagName; + return node; + } + ts.createJsxClosingElement = createJsxClosingElement; + function updateJsxClosingElement(node, tagName) { + if (node.tagName !== tagName) { + return updateNode(createJsxClosingElement(tagName, node), node); + } + return node; + } + ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxAttribute(name, initializer, location) { + var node = createNode(246 /* JsxAttribute */, location); + node.name = name; + node.initializer = initializer; + return node; + } + ts.createJsxAttribute = createJsxAttribute; + function updateJsxAttribute(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createJsxAttribute(name, initializer, node), node); + } + return node; + } + ts.updateJsxAttribute = updateJsxAttribute; + function createJsxSpreadAttribute(expression, location) { + var node = createNode(247 /* JsxSpreadAttribute */, location); + node.expression = expression; + return node; + } + ts.createJsxSpreadAttribute = createJsxSpreadAttribute; + function updateJsxSpreadAttribute(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxSpreadAttribute(expression, node), node); + } + return node; + } + ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; + function createJsxExpression(expression, location) { + var node = createNode(248 /* JsxExpression */, location); + node.expression = expression; + return node; + } + ts.createJsxExpression = createJsxExpression; + function updateJsxExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createJsxExpression(expression, node), node); + } + return node; + } + ts.updateJsxExpression = updateJsxExpression; + // Clauses + function createHeritageClause(token, types, location) { + var node = createNode(251 /* HeritageClause */, location); + node.token = token; + node.types = createNodeArray(types); + return node; + } + ts.createHeritageClause = createHeritageClause; + function updateHeritageClause(node, types) { + if (node.types !== types) { + return updateNode(createHeritageClause(node.token, types, node), node); + } + return node; + } + ts.updateHeritageClause = updateHeritageClause; + function createCaseClause(expression, statements, location) { + var node = createNode(249 /* CaseClause */, location); + node.expression = parenthesizeExpressionForList(expression); + node.statements = createNodeArray(statements); + return node; + } + ts.createCaseClause = createCaseClause; + function updateCaseClause(node, expression, statements) { + if (node.expression !== expression || node.statements !== statements) { + return updateNode(createCaseClause(expression, statements, node), node); + } + return node; + } + ts.updateCaseClause = updateCaseClause; + function createDefaultClause(statements, location) { + var node = createNode(250 /* DefaultClause */, location); + node.statements = createNodeArray(statements); + return node; + } + ts.createDefaultClause = createDefaultClause; + function updateDefaultClause(node, statements) { + if (node.statements !== statements) { + return updateNode(createDefaultClause(statements, node), node); + } + return node; + } + ts.updateDefaultClause = updateDefaultClause; + function createCatchClause(variableDeclaration, block, location) { + var node = createNode(252 /* CatchClause */, location); + node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + node.block = block; + return node; + } + ts.createCatchClause = createCatchClause; + function updateCatchClause(node, variableDeclaration, block) { + if (node.variableDeclaration !== variableDeclaration || node.block !== block) { + return updateNode(createCatchClause(variableDeclaration, block, node), node); + } + return node; + } + ts.updateCatchClause = updateCatchClause; + // Property assignments + function createPropertyAssignment(name, initializer, location) { + var node = createNode(253 /* PropertyAssignment */, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.questionToken = undefined; + node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; + return node; + } + ts.createPropertyAssignment = createPropertyAssignment; + function updatePropertyAssignment(node, name, initializer) { + if (node.name !== name || node.initializer !== initializer) { + return updateNode(createPropertyAssignment(name, initializer, node), node); + } + return node; + } + ts.updatePropertyAssignment = updatePropertyAssignment; + function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { + var node = createNode(254 /* ShorthandPropertyAssignment */, location); + node.name = typeof name === "string" ? createIdentifier(name) : name; + node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; + return node; + } + ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { + return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); + } + return node; + } + ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + // Top-level nodes + function updateSourceFileNode(node, statements) { + if (node.statements !== statements) { + var updated = createNode(256 /* SourceFile */, /*location*/ node, node.flags); + updated.statements = createNodeArray(statements); + updated.endOfFileToken = node.endOfFileToken; + updated.fileName = node.fileName; + updated.path = node.path; + updated.text = node.text; + if (node.amdDependencies !== undefined) + updated.amdDependencies = node.amdDependencies; + if (node.moduleName !== undefined) + updated.moduleName = node.moduleName; + if (node.referencedFiles !== undefined) + updated.referencedFiles = node.referencedFiles; + if (node.typeReferenceDirectives !== undefined) + updated.typeReferenceDirectives = node.typeReferenceDirectives; + if (node.languageVariant !== undefined) + updated.languageVariant = node.languageVariant; + if (node.isDeclarationFile !== undefined) + updated.isDeclarationFile = node.isDeclarationFile; + if (node.renamedDependencies !== undefined) + updated.renamedDependencies = node.renamedDependencies; + if (node.hasNoDefaultLib !== undefined) + updated.hasNoDefaultLib = node.hasNoDefaultLib; + if (node.languageVersion !== undefined) + updated.languageVersion = node.languageVersion; + if (node.scriptKind !== undefined) + updated.scriptKind = node.scriptKind; + if (node.externalModuleIndicator !== undefined) + updated.externalModuleIndicator = node.externalModuleIndicator; + if (node.commonJsModuleIndicator !== undefined) + updated.commonJsModuleIndicator = node.commonJsModuleIndicator; + if (node.identifiers !== undefined) + updated.identifiers = node.identifiers; + if (node.nodeCount !== undefined) + updated.nodeCount = node.nodeCount; + if (node.identifierCount !== undefined) + updated.identifierCount = node.identifierCount; + if (node.symbolCount !== undefined) + updated.symbolCount = node.symbolCount; + if (node.parseDiagnostics !== undefined) + updated.parseDiagnostics = node.parseDiagnostics; + if (node.bindDiagnostics !== undefined) + updated.bindDiagnostics = node.bindDiagnostics; + if (node.lineMap !== undefined) + updated.lineMap = node.lineMap; + if (node.classifiableNames !== undefined) + updated.classifiableNames = node.classifiableNames; + if (node.resolvedModules !== undefined) + updated.resolvedModules = node.resolvedModules; + if (node.resolvedTypeReferenceDirectiveNames !== undefined) + updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; + if (node.imports !== undefined) + updated.imports = node.imports; + if (node.moduleAugmentations !== undefined) + updated.moduleAugmentations = node.moduleAugmentations; + if (node.externalHelpersModuleName !== undefined) + updated.externalHelpersModuleName = node.externalHelpersModuleName; + return updateNode(updated, node); + } + return node; + } + ts.updateSourceFileNode = updateSourceFileNode; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ + function createNotEmittedStatement(original) { + var node = createNode(287 /* NotEmittedStatement */, /*location*/ original); + node.original = original; + return node; + } + ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ + function createPartiallyEmittedExpression(expression, original, location) { + var node = createNode(288 /* PartiallyEmittedExpression */, /*location*/ location || original); + node.expression = expression; + node.original = original; + return node; + } + ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression; + function updatePartiallyEmittedExpression(node, expression) { + if (node.expression !== expression) { + return updateNode(createPartiallyEmittedExpression(expression, node.original, node), node); + } + return node; + } + ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + // Compound nodes + function createComma(left, right) { + return createBinary(left, 24 /* CommaToken */, right); + } + ts.createComma = createComma; + function createLessThan(left, right, location) { + return createBinary(left, 25 /* LessThanToken */, right, location); + } + ts.createLessThan = createLessThan; + function createAssignment(left, right, location) { + return createBinary(left, 56 /* EqualsToken */, right, location); + } + ts.createAssignment = createAssignment; + function createStrictEquality(left, right) { + return createBinary(left, 32 /* EqualsEqualsEqualsToken */, right); + } + ts.createStrictEquality = createStrictEquality; + function createStrictInequality(left, right) { + return createBinary(left, 33 /* ExclamationEqualsEqualsToken */, right); + } + ts.createStrictInequality = createStrictInequality; + function createAdd(left, right) { + return createBinary(left, 35 /* PlusToken */, right); + } + ts.createAdd = createAdd; + function createSubtract(left, right) { + return createBinary(left, 36 /* MinusToken */, right); + } + ts.createSubtract = createSubtract; + function createPostfixIncrement(operand, location) { + return createPostfix(operand, 41 /* PlusPlusToken */, location); + } + ts.createPostfixIncrement = createPostfixIncrement; + function createLogicalAnd(left, right) { + return createBinary(left, 51 /* AmpersandAmpersandToken */, right); + } + ts.createLogicalAnd = createLogicalAnd; + function createLogicalOr(left, right) { + return createBinary(left, 52 /* BarBarToken */, right); + } + ts.createLogicalOr = createLogicalOr; + function createLogicalNot(operand) { + return createPrefix(49 /* ExclamationToken */, operand); + } + ts.createLogicalNot = createLogicalNot; + function createVoidZero() { + return createVoid(createLiteral(0)); + } + ts.createVoidZero = createVoidZero; + function createMemberAccessForPropertyName(target, memberName, location) { + if (ts.isComputedPropertyName(memberName)) { + return createElementAccess(target, memberName.expression, location); + } + else { + var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); + expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + return expression; + } + } + ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; + function createRestParameter(name) { + return createParameterDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + ts.createRestParameter = createRestParameter; + function createFunctionCall(func, thisArg, argumentsList, location) { + return createCall(createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ + thisArg + ].concat(argumentsList), location); + } + ts.createFunctionCall = createFunctionCall; + function createFunctionApply(func, thisArg, argumentsExpression, location) { + return createCall(createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ + thisArg, + argumentsExpression + ], location); + } + ts.createFunctionApply = createFunctionApply; + function createArraySlice(array, start) { + var argumentsList = []; + if (start !== undefined) { + argumentsList.push(typeof start === "number" ? createLiteral(start) : start); + } + return createCall(createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); + } + ts.createArraySlice = createArraySlice; + function createArrayConcat(array, values) { + return createCall(createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); + } + ts.createArrayConcat = createArrayConcat; + function createMathPow(left, right, location) { + return createCall(createPropertyAccess(createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right], location); + } + ts.createMathPow = createMathPow; + function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. + var react = createIdentifier(reactNamespace || "React"); + react.flags &= ~8 /* Synthesized */; + react.parent = parent; + return react; + } + function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + var argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(createNull()); + } + if (children.length > 1) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + child.startsOnNewLine = true; + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), + /*typeArguments*/ undefined, argumentsList, location); + } + ts.createReactCreateElement = createReactCreateElement; + function createLetDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 1 /* Let */); + } + ts.createLetDeclarationList = createLetDeclarationList; + function createConstDeclarationList(declarations, location) { + return createVariableDeclarationList(declarations, location, 2 /* Const */); + } + ts.createConstDeclarationList = createConstDeclarationList; + // Helpers + function createHelperName(externalHelpersModuleName, name) { + return externalHelpersModuleName + ? createPropertyAccess(externalHelpersModuleName, name) + : createIdentifier(name); + } + ts.createHelperName = createHelperName; + function createExtendsHelper(externalHelpersModuleName, name) { + return createCall(createHelperName(externalHelpersModuleName, "__extends"), + /*typeArguments*/ undefined, [ + name, + createIdentifier("_super") + ]); + } + ts.createExtendsHelper = createExtendsHelper; + function createAssignHelper(externalHelpersModuleName, attributesSegments) { + return createCall(createHelperName(externalHelpersModuleName, "__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; + function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { + return createCall(createHelperName(externalHelpersModuleName, "__param"), + /*typeArguments*/ undefined, [ + createLiteral(parameterOffset), + expression + ], location); + } + ts.createParamHelper = createParamHelper; + function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { + return createCall(createHelperName(externalHelpersModuleName, "__metadata"), + /*typeArguments*/ undefined, [ + createLiteral(metadataKey), + metadataValue + ]); + } + ts.createMetadataHelper = createMetadataHelper; + function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { + var argumentsArray = []; + argumentsArray.push(createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return createCall(createHelperName(externalHelpersModuleName, "__decorate"), /*typeArguments*/ undefined, argumentsArray, location); + } + ts.createDecorateHelper = createDecorateHelper; + function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { + var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; + return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), + /*typeArguments*/ undefined, [ + createThis(), + hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), + promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), + generatorFunc + ]); + } + ts.createAwaiterHelper = createAwaiterHelper; + function createHasOwnProperty(target, propertyName) { + return createCall(createPropertyAccess(target, "hasOwnProperty"), + /*typeArguments*/ undefined, [propertyName]); + } + ts.createHasOwnProperty = createHasOwnProperty; + function createObjectCreate(prototype) { + return createCall(createPropertyAccess(createIdentifier("Object"), "create"), + /*typeArguments*/ undefined, [prototype]); + } + function createGeti(target) { + // name => super[name] + return createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, [createParameter("name")], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createElementAccess(target, createIdentifier("name"))); + } + function createSeti(target) { + // (name, value) => super[name] = value + return createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, [ + createParameter("name"), + createParameter("value") + ], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); + } + function createAdvancedAsyncSuperHelper() { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // const cache = Object.create(null); + var createCache = createVariableStatement( + /*modifiers*/ undefined, createConstDeclarationList([ + createVariableDeclaration("cache", + /*type*/ undefined, createObjectCreate(createNull())) + ])); + // get value() { return geti(name); } + var getter = createGetAccessor( + /*decorators*/ undefined, + /*modifiers*/ undefined, "value", + /*parameters*/ [], + /*type*/ undefined, createBlock([ + createReturn(createCall(createIdentifier("geti"), + /*typeArguments*/ undefined, [createIdentifier("name")])) + ])); + // set value(v) { seti(name, v); } + var setter = createSetAccessor( + /*decorators*/ undefined, + /*modifiers*/ undefined, "value", [createParameter("v")], createBlock([ + createStatement(createCall(createIdentifier("seti"), + /*typeArguments*/ undefined, [ + createIdentifier("name"), + createIdentifier("v") + ])) + ])); + // return name => cache[name] || ... + var getOrCreateAccessorsForName = createReturn(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, [createParameter("name")], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ + getter, + setter + ])))))); + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + return createVariableStatement( + /*modifiers*/ undefined, createConstDeclarationList([ + createVariableDeclaration("_super", + /*type*/ undefined, createCall(createParen(createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + createParameter("geti"), + createParameter("seti") + ], + /*type*/ undefined, createBlock([ + createCache, + getOrCreateAccessorsForName + ]))), + /*typeArguments*/ undefined, [ + createGeti(createSuper()), + createSeti(createSuper()) + ])) + ])); + } + ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; + function createSimpleAsyncSuperHelper() { + return createVariableStatement( + /*modifiers*/ undefined, createConstDeclarationList([ + createVariableDeclaration("_super", + /*type*/ undefined, createGeti(createSuper())) + ])); + } + ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + var target = skipParentheses(node); + switch (target.kind) { + case 69 /* Identifier */: + return cacheIdentifiers; + case 97 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return false; + case 170 /* ArrayLiteralExpression */: + var elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 171 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + var callee = skipOuterExpressions(expression, 7 /* All */); + var thisArg; + var target; + if (ts.isSuperProperty(callee)) { + thisArg = createThis(); + target = callee; + } + else if (callee.kind === 95 /* SuperKeyword */) { + thisArg = createThis(); + target = languageVersion < 2 /* ES6 */ ? createIdentifier("_super", /*location*/ callee) : callee; + } + else { + switch (callee.kind) { + case 172 /* PropertyAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` + thisArg = createTempVariable(recordTempVariable); + target = createPropertyAccess(createAssignment(thisArg, callee.expression, + /*location*/ callee.expression), callee.name, + /*location*/ callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + case 173 /* ElementAccessExpression */: { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` + thisArg = createTempVariable(recordTempVariable); + target = createElementAccess(createAssignment(thisArg, callee.expression, + /*location*/ callee.expression), callee.argumentExpression, + /*location*/ callee); + } + else { + thisArg = callee.expression; + target = callee; + } + break; + } + default: { + // for `a()` target is `a` and thisArg is `void 0` + thisArg = createVoidZero(); + target = parenthesizeForAccess(expression); + break; + } + } + } + return { target: target, thisArg: thisArg }; + } + ts.createCallBinding = createCallBinding; + function inlineExpressions(expressions) { + return ts.reduceLeft(expressions, createComma); + } + ts.inlineExpressions = inlineExpressions; + function createExpressionFromEntityName(node) { + if (ts.isQualifiedName(node)) { + var left = createExpressionFromEntityName(node.left); + var right = getMutableClone(node.right); + return createPropertyAccess(left, right, /*location*/ node); + } + else { + return getMutableClone(node); + } + } + ts.createExpressionFromEntityName = createExpressionFromEntityName; + function createExpressionForPropertyName(memberName) { + if (ts.isIdentifier(memberName)) { + return createLiteral(memberName, /*location*/ undefined); + } + else if (ts.isComputedPropertyName(memberName)) { + return getMutableClone(memberName.expression); + } + else { + return getMutableClone(memberName); + } + } + ts.createExpressionForPropertyName = createExpressionForPropertyName; + function createExpressionForObjectLiteralElementLike(node, property, receiver) { + switch (property.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + case 253 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(property, receiver); + case 254 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(property, receiver); + case 147 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(property, receiver); + } + } + ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike; + function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { + var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + if (property === firstAccessor) { + var properties_1 = []; + if (getAccessor) { + var getterFunction = createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body, + /*location*/ getAccessor); + setOriginalNode(getterFunction, getAccessor); + var getter = createPropertyAssignment("get", getterFunction); + properties_1.push(getter); + } + if (setAccessor) { + var setterFunction = createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body, + /*location*/ setAccessor); + setOriginalNode(setterFunction, setAccessor); + var setter = createPropertyAssignment("set", setterFunction); + properties_1.push(setter); + } + properties_1.push(createPropertyAssignment("enumerable", createLiteral(true))); + properties_1.push(createPropertyAssignment("configurable", createLiteral(true))); + var expression = createCall(createPropertyAccess(createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + receiver, + createExpressionForPropertyName(property.name), + createObjectLiteral(properties_1, /*location*/ undefined, multiLine) + ], + /*location*/ firstAccessor); + return ts.aggregateTransformFlags(expression); + } + return undefined; + } + function createExpressionForPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer, + /*location*/ property), + /*original*/ property)); + } + function createExpressionForShorthandPropertyAssignment(property, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), getSynthesizedClone(property.name), + /*location*/ property), + /*original*/ property)); + } + function createExpressionForMethodDeclaration(method, receiver) { + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body, + /*location*/ method), + /*original*/ method), + /*location*/ method), + /*original*/ method)); + } + // Utilities + function isUseStrictPrologue(node) { + return node.expression.text === "use strict"; + } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ + function addPrologueDirectives(target, source, ensureUseStrict, visitor) { + ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + var foundUseStrict = false; + var statementOffset = 0; + var numStatements = source.length; + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + } + target.push(statement); + } + else { + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + foundUseStrict = true; + } + if (statement.emitFlags & 8388608 /* CustomPrologue */) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; + } + } + statementOffset++; + } + return statementOffset; + } + ts.addPrologueDirectives = addPrologueDirectives; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + var skipped = skipPartiallyEmittedExpressions(operand); + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 178 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + ? createParen(operand) + : operand; + } + ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(187 /* BinaryExpression */, binaryOperator); + var emittedOperand = skipPartiallyEmittedExpressions(operand); + var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); + switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. + if (!isLeftSideOfBinary + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 190 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; + } + else { + if (ts.isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 35 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) + var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ + function operatorHasAssociativeProperty(binaryOperator) { + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 37 /* AsteriskToken */ + || binaryOperator === 47 /* BarToken */ + || binaryOperator === 46 /* AmpersandToken */ + || binaryOperator === 48 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ + function getLiteralKindOfBinaryPlusOperand(node) { + node = skipPartiallyEmittedExpressions(node); + if (ts.isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 35 /* PlusToken */) { + if (node.cachedLiteralKind !== undefined) { + return node.cachedLiteralKind; + } + var leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + var literalKind = ts.isLiteralKind(leftKind) + && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) + ? leftKind + : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ + function parenthesizeForNew(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + switch (emittedExpression.kind) { + case 174 /* CallExpression */: + return createParen(expression); + case 175 /* NewExpression */: + return emittedExpression.arguments + ? expression + : createParen(expression); + } + return parenthesizeForAccess(expression); + } + ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ + function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exceptions are: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // NumericLiteral + // 1.x -> not the same as (1).x + // + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isLeftHandSideExpression(emittedExpression) + && (emittedExpression.kind !== 175 /* NewExpression */ || emittedExpression.arguments) + && emittedExpression.kind !== 8 /* NumericLiteral */) { + return expression; + } + return createParen(expression, /*location*/ expression); + } + ts.parenthesizeForAccess = parenthesizeForAccess; + function parenthesizePostfixOperand(operand) { + return ts.isLeftHandSideExpression(operand) + ? operand + : createParen(operand, /*location*/ operand); + } + ts.parenthesizePostfixOperand = parenthesizePostfixOperand; + function parenthesizePrefixOperand(operand) { + return ts.isUnaryExpression(operand) + ? operand + : createParen(operand, /*location*/ operand); + } + ts.parenthesizePrefixOperand = parenthesizePrefixOperand; + function parenthesizeListElements(elements) { + var result; + for (var i = 0; i < elements.length; i++) { + var element = parenthesizeExpressionForList(elements[i]); + if (result !== undefined || element !== elements[i]) { + if (result === undefined) { + result = elements.slice(0, i); + } + result.push(element); + } + } + if (result !== undefined) { + return createNodeArray(result, elements, elements.hasTrailingComma); + } + return elements; + } + function parenthesizeExpressionForList(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); + var commaPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, 24 /* CommaToken */); + return expressionPrecedence > commaPrecedence + ? expression + : createParen(expression, /*location*/ expression); + } + ts.parenthesizeExpressionForList = parenthesizeExpressionForList; + function parenthesizeExpressionForExpressionStatement(expression) { + var emittedExpression = skipPartiallyEmittedExpressions(expression); + if (ts.isCallExpression(emittedExpression)) { + var callee = emittedExpression.expression; + var kind = skipPartiallyEmittedExpressions(callee).kind; + if (kind === 179 /* FunctionExpression */ || kind === 180 /* ArrowFunction */) { + var mutableCall = getMutableClone(emittedExpression); + mutableCall.expression = createParen(callee, /*location*/ callee); + return recreatePartiallyEmittedExpressions(expression, mutableCall); + } + } + else { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 171 /* ObjectLiteralExpression */ || leftmostExpressionKind === 179 /* FunctionExpression */) { + return createParen(expression, /*location*/ expression); + } + } + return expression; + } + ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; + /** + * Clones a series of not-emitted expressions with a new inner expression. + * + * @param originalOuterExpression The original outer expression. + * @param newInnerExpression The new inner expression. + */ + function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { + if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { + var clone_1 = getMutableClone(originalOuterExpression); + clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); + return clone_1; + } + return newInnerExpression; + } + function getLeftmostExpression(node) { + while (true) { + switch (node.kind) { + case 186 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 187 /* BinaryExpression */: + node = node.left; + continue; + case 188 /* ConditionalExpression */: + node = node.condition; + continue; + case 174 /* CallExpression */: + case 173 /* ElementAccessExpression */: + case 172 /* PropertyAccessExpression */: + node = node.expression; + continue; + case 288 /* PartiallyEmittedExpression */: + node = node.expression; + continue; + } + return node; + } + } + function parenthesizeConciseBody(body) { + var emittedBody = skipPartiallyEmittedExpressions(body); + if (emittedBody.kind === 171 /* ObjectLiteralExpression */) { + return createParen(body, /*location*/ body); + } + return body; + } + ts.parenthesizeConciseBody = parenthesizeConciseBody; + (function (OuterExpressionKinds) { + OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + })(ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + var OuterExpressionKinds = ts.OuterExpressionKinds; + function skipOuterExpressions(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + var previousNode; + do { + previousNode = node; + if (kinds & 1 /* Parentheses */) { + node = skipParentheses(node); + } + if (kinds & 2 /* Assertions */) { + node = skipAssertions(node); + } + if (kinds & 4 /* PartiallyEmittedExpressions */) { + node = skipPartiallyEmittedExpressions(node); + } + } while (previousNode !== node); + return node; + } + ts.skipOuterExpressions = skipOuterExpressions; + function skipParentheses(node) { + while (node.kind === 178 /* ParenthesizedExpression */) { + node = node.expression; + } + return node; + } + ts.skipParentheses = skipParentheses; + function skipAssertions(node) { + while (ts.isAssertionExpression(node)) { + node = node.expression; + } + return node; + } + ts.skipAssertions = skipAssertions; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function startOnNewLine(node) { + node.startsOnNewLine = true; + return node; + } + ts.startOnNewLine = startOnNewLine; + function setOriginalNode(node, original) { + node.original = original; + if (original) { + var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; + if (emitFlags) + node.emitFlags = emitFlags; + if (commentRange) + node.commentRange = commentRange; + if (sourceMapRange) + node.sourceMapRange = sourceMapRange; + } + return node; + } + ts.setOriginalNode = setOriginalNode; + function setTextRange(node, location) { + if (location) { + node.pos = location.pos; + node.end = location.end; + } + return node; + } + ts.setTextRange = setTextRange; + function setNodeFlags(node, flags) { + node.flags = flags; + return node; + } + ts.setNodeFlags = setNodeFlags; + function setMultiLine(node, multiLine) { + node.multiLine = multiLine; + return node; + } + ts.setMultiLine = setMultiLine; + function setHasTrailingComma(nodes, hasTrailingComma) { + nodes.hasTrailingComma = hasTrailingComma; + return nodes; + } + ts.setHasTrailingComma = setHasTrailingComma; + /** + * Get the name of that target module from an import or export declaration + */ + function getLocalNameForExternalImport(node, sourceFile) { + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + var name_9 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_9) ? name_9 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + } + if (node.kind === 230 /* ImportDeclaration */ && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 236 /* ExportDeclaration */ && node.moduleSpecifier) { + return getGeneratedNameForNode(node); + } + return undefined; + } + ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { + var moduleName = ts.getExternalModuleName(importNode); + if (moduleName.kind === 9 /* StringLiteral */) { + return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) + || tryRenameExternalModule(moduleName, sourceFile) + || getSynthesizedClone(moduleName); + } + return undefined; + } + ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName, sourceFile) { + if (sourceFile.renamedDependencies && ts.hasProperty(sourceFile.renamedDependencies, moduleName.text)) { + return createLiteral(sourceFile.renamedDependencies[moduleName.text]); + } + return undefined; + } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ + function tryGetModuleNameFromFile(file, host, options) { + if (!file) { + return undefined; + } + if (file.moduleName) { + return createLiteral(file.moduleName); + } + if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) { + return createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName)); + } + return undefined; + } + ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile; + function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { + return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } - ts.endsWith = endsWith; })(ts || (ts = {})); /// /// +/// var ts; (function (ts) { - /* @internal */ ts.parseTime = 0; var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } + else if (kind === 69 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (kind < 139 /* FirstNode */) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -8052,6 +12561,8 @@ var ts; return visitNodes(cbNodes, node.types); case 164 /* ParenthesizedType */: return visitNode(cbNode, node.type); + case 166 /* LiteralType */: + return visitNode(cbNode, node.literal); case 167 /* ObjectBindingPattern */: case 168 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); @@ -8291,7 +12802,7 @@ var ts; case 263 /* JSDocNullableType */: return visitNode(cbNode, node.type); case 265 /* JSDocRecordType */: - return visitNodes(cbNodes, node.members); + return visitNode(cbNode, node.literal); case 267 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); @@ -8330,14 +12841,19 @@ var ts; case 280 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + case 288 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + case 282 /* JSDocLiteralType */: + return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - var start = new Date().getTime(); + ts.performance.mark("beforeParse"); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); - ts.parseTime += new Date().getTime() - start; + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; } ts.createSourceFile = createSourceFile; @@ -8361,10 +12877,10 @@ var ts; /* @internal */ function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDocComment) { + if (result && result.jsDoc) { // because the jsDocComment was parsed out of the source file, it might // not be covered by the fixupParentReferences. - Parser.fixupParentReferences(result.jsDocComment); + Parser.fixupParentReferences(result.jsDoc); } return result; } @@ -8383,14 +12899,16 @@ var ts; // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */; + var disallowInAndDecoratorContext = 32768 /* DisallowInContext */ | 131072 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -8485,15 +13003,17 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 1048576 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); @@ -8516,10 +13036,10 @@ var ts; sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; // Prime the scanner. - token = nextToken(); + nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); - ts.Debug.assert(token === 1 /* EndOfFileToken */); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -8532,20 +13052,18 @@ var ts; return sourceFile; } function addJSDocComment(node) { - if (contextFlags & 134217728 /* JavaScriptFile */) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDocComment) { - continue; - } - if (!node.jsDocComments) { - node.jsDocComments = []; - } - node.jsDocComments.push(jsDocComment); + var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; } + if (!node.jsDocComments) { + node.jsDocComments = []; + } + node.jsDocComments.push(jsDoc); } } return node; @@ -8603,16 +13121,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 4194304 /* DisallowInContext */); + setContextFlag(val, 32768 /* DisallowInContext */); } function setYieldContext(val) { - setContextFlag(val, 8388608 /* YieldContext */); + setContextFlag(val, 65536 /* YieldContext */); } function setDecoratorContext(val) { - setContextFlag(val, 16777216 /* DecoratorContext */); + setContextFlag(val, 131072 /* DecoratorContext */); } function setAwaitContext(val) { - setContextFlag(val, 33554432 /* AwaitContext */); + setContextFlag(val, 262144 /* AwaitContext */); } function doOutsideOfContext(context, func) { // contextFlagsToClear will contain only the context flags that are @@ -8653,40 +13171,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(4194304 /* DisallowInContext */, func); + return doOutsideOfContext(32768 /* DisallowInContext */, func); } function disallowInAnd(func) { - return doInsideOfContext(4194304 /* DisallowInContext */, func); + return doInsideOfContext(32768 /* DisallowInContext */, func); } function doInYieldContext(func) { - return doInsideOfContext(8388608 /* YieldContext */, func); + return doInsideOfContext(65536 /* YieldContext */, func); } function doInDecoratorContext(func) { - return doInsideOfContext(16777216 /* DecoratorContext */, func); + return doInsideOfContext(131072 /* DecoratorContext */, func); } function doInAwaitContext(func) { - return doInsideOfContext(33554432 /* AwaitContext */, func); + return doInsideOfContext(262144 /* AwaitContext */, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(33554432 /* AwaitContext */, func); + return doOutsideOfContext(262144 /* AwaitContext */, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(8388608 /* YieldContext */ | 33554432 /* AwaitContext */, func); + return doInsideOfContext(65536 /* YieldContext */ | 262144 /* AwaitContext */, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(8388608 /* YieldContext */); + return inContext(65536 /* YieldContext */); } function inDisallowInContext() { - return inContext(4194304 /* DisallowInContext */); + return inContext(32768 /* DisallowInContext */); } function inDecoratorContext() { - return inContext(16777216 /* DecoratorContext */); + return inContext(131072 /* DecoratorContext */); } function inAwaitContext() { - return inContext(33554432 /* AwaitContext */); + return inContext(262144 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -8713,34 +13231,46 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } function nextToken() { - return token = scanner.scan(); + return currentToken = scanner.scan(); } function reScanGreaterToken() { - return token = scanner.reScanGreaterToken(); + return currentToken = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return token = scanner.reScanSlashToken(); + return currentToken = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return token = scanner.reScanTemplateToken(); + return currentToken = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return token = scanner.scanJsxIdentifier(); + return currentToken = scanner.scanJsxIdentifier(); } function scanJsxText() { - return token = scanner.scanJsxToken(); + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); } function speculationHelper(callback, isLookAhead) { // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; // Note: it is not actually necessary to save/restore the context flags here. That's // because the saving/restoring of these flags happens naturally through the recursive // descent nature of our parser. However, we still store this here just so we can - // assert that that invariant holds. + // assert that invariant holds. var saveContextFlags = contextFlags; // If we're only looking ahead, then tell the scanner to only lookahead as well. // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the @@ -8752,7 +13282,7 @@ var ts; // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -8775,24 +13305,24 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token === 69 /* Identifier */) { + if (token() === 69 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token === 114 /* YieldKeyword */ && inYieldContext()) { + if (token() === 114 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token === 119 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token > 105 /* LastReservedWord */; + return token() > 105 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token === kind) { + if (token() === kind) { if (shouldAdvance) { nextToken(); } @@ -8808,14 +13338,14 @@ var ts; return false; } function parseOptional(t) { - if (token === t) { + if (token() === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token === t) { + if (token() === t) { return parseTokenNode(); } return undefined; @@ -8825,21 +13355,21 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token); + var node = createNode(token()); nextToken(); return finishNode(node); } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token === 16 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 16 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } @@ -8855,7 +13385,18 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new NodeConstructor(kind, pos, pos); + return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : + kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -8867,7 +13408,7 @@ var ts; // flag so that we don't mark any subsequent nodes. if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 67108864 /* ThisNodeHasError */; + node.flags |= 524288 /* ThisNodeHasError */; } return node; } @@ -8884,7 +13425,7 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); + return identifiers[text] || (identifiers[text] = text); } // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for @@ -8894,8 +13435,8 @@ var ts; if (isIdentifier) { var node = createNode(69 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token !== 69 /* Identifier */) { - node.originalKeywordKind = token; + if (token() !== 69 /* Identifier */) { + node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -8907,18 +13448,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token) || - token === 9 /* StringLiteral */ || - token === 8 /* NumericLiteral */; + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */) { + if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { return parseLiteralNode(/*internName*/ true); } - if (allowComputedPropertyNames && token === 19 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 19 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -8930,7 +13471,7 @@ var ts; return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { - return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { // PropertyName [Yield]: @@ -8946,7 +13487,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8956,40 +13497,40 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token === 74 /* ConstKeyword */) { + if (token() === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. return nextToken() === 81 /* EnumKeyword */; } - if (token === 82 /* ExportKeyword */) { + if (token() === 82 /* ExportKeyword */) { nextToken(); - if (token === 77 /* DefaultKeyword */) { + if (token() === 77 /* DefaultKeyword */) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token !== 37 /* AsteriskToken */ && token !== 116 /* AsKeyword */ && token !== 15 /* OpenBraceToken */ && canFollowModifier(); + return token() !== 37 /* AsteriskToken */ && token() !== 116 /* AsKeyword */ && token() !== 15 /* OpenBraceToken */ && canFollowModifier(); } - if (token === 77 /* DefaultKeyword */) { + if (token() === 77 /* DefaultKeyword */) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token === 113 /* StaticKeyword */) { + if (token() === 113 /* StaticKeyword */) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token === 19 /* OpenBracketToken */ - || token === 15 /* OpenBraceToken */ - || token === 37 /* AsteriskToken */ - || token === 22 /* DotDotDotToken */ + return token() === 19 /* OpenBracketToken */ + || token() === 15 /* OpenBraceToken */ + || token() === 37 /* AsteriskToken */ + || token() === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token === 73 /* ClassKeyword */ || token === 87 /* FunctionKeyword */ || - (token === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 73 /* ClassKeyword */ || token() === 87 /* FunctionKeyword */ || + (token() === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -9007,9 +13548,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; + return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -9017,19 +13558,19 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token === 23 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); + return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -9044,23 +13585,23 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); case 17 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 18 /* TypeArguments */: case 19 /* TupleElementTypes */: - return token === 24 /* CommaToken */ || isStartOfType(); + return token() === 24 /* CommaToken */ || isStartOfType(); case 20 /* HeritageClauses */: return isHeritageClause(); case 21 /* ImportOrExportSpecifiers */: - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token) || token === 15 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; case 22 /* JSDocFunctionParameters */: @@ -9073,7 +13614,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token === 15 /* OpenBraceToken */); + ts.Debug.assert(token() === 15 /* OpenBraceToken */); if (nextToken() === 16 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: @@ -9093,11 +13634,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token === 106 /* ImplementsKeyword */ || - token === 83 /* ExtendsKeyword */) { + if (token() === 106 /* ImplementsKeyword */ || + token() === 83 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -9108,7 +13649,7 @@ var ts; } // True if positioned at a list terminator function isListTerminator(kind) { - if (token === 1 /* EndOfFileToken */) { + if (token() === 1 /* EndOfFileToken */) { // Being at the end of the file ends all lists. return true; } @@ -9121,43 +13662,43 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 21 /* ImportOrExportSpecifiers */: - return token === 16 /* CloseBraceToken */; + return token() === 16 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; + return token() === 16 /* CloseBraceToken */ || token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + return token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 17 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */ || token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */; + return token() === 18 /* CloseParenToken */ || token() === 23 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 19 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token === 20 /* CloseBracketToken */; + return token() === 20 /* CloseBracketToken */; case 16 /* Parameters */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: // Tokens other than '>' are here for better error recovery - return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */; + return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; case 20 /* HeritageClauses */: - return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */; + return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */; + return token() === 27 /* GreaterThanToken */ || token() === 39 /* SlashToken */; case 14 /* JsxChildren */: - return token === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); case 22 /* JSDocFunctionParameters */: - return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */; + return token() === 18 /* CloseParenToken */ || token() === 54 /* ColonToken */ || token() === 16 /* CloseBraceToken */; case 23 /* JSDocTypeArguments */: - return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */; + return token() === 27 /* GreaterThanToken */ || token() === 16 /* CloseBraceToken */; case 25 /* JSDocTupleTypes */: - return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */; + return token() === 20 /* CloseBracketToken */ || token() === 16 /* CloseBraceToken */; case 24 /* JSDocRecordMembers */: - return token === 16 /* CloseBraceToken */; + return token() === 16 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -9168,14 +13709,14 @@ var ts; } // in the case where we're parsing the variable declarator of a 'for-in' statement, we // are done if we see an 'in' keyword in front of us. Same with for-of - if (isInOrOfKeyword(token)) { + if (isInOrOfKeyword(token())) { return true; } // ERROR RECOVERY TWEAK: // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token === 34 /* EqualsGreaterThanToken */) { + if (token() === 34 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -9196,8 +13737,7 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); @@ -9259,7 +13799,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 197132288 /* ContextFlags */; + var nodeContextFlags = node.flags & 1540096 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -9494,8 +14034,7 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = []; - result.pos = getNodePos(); + var result = createNodeArray(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { @@ -9516,7 +14055,7 @@ var ts; // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimiter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9542,11 +14081,7 @@ var ts; return result; } function createMissingList() { - var pos = getNodePos(); - var result = []; - result.pos = pos; - result.end = pos; - return result; + return createNodeArray(); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -9587,7 +14122,7 @@ var ts; // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". // In the first case though, ASI will not take effect because there is not a // line terminator after the identifier or keyword. - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, @@ -9602,8 +14137,7 @@ var ts; var template = createNode(189 /* TemplateExpression */); template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); - var templateSpans = []; - templateSpans.pos = getNodePos(); + var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); } while (ts.lastOrUndefined(templateSpans).literal.kind === 13 /* TemplateMiddle */); @@ -9615,7 +14149,7 @@ var ts; var span = createNode(197 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16 /* CloseBraceToken */) { + if (token() === 16 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -9625,14 +14159,11 @@ var ts; span.literal = literal; return finishNode(span); } - function parseStringLiteralTypeNode() { - return parseLiteralLikeNode(166 /* StringLiteralType */, /*internName*/ true); - } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token, internName); + return parseLiteralLikeNode(token(), internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token, /*internName*/ false); + return parseLiteralLikeNode(token(), /*internName*/ false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -9665,7 +14196,7 @@ var ts; var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); var node = createNode(155 /* TypeReference */, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token === 25 /* LessThanToken */) { + if (!scanner.hasPrecedingLineBreak() && token() === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); @@ -9713,7 +14244,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { return parseBracketedList(17 /* TypeParameters */, parseTypeParameter, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } } @@ -9724,28 +14255,22 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */ || token === 97 /* ThisKeyword */; - } - function setModifiers(node, modifiers) { - if (modifiers) { - node.flags |= modifiers.flags; - node.modifiers = modifiers; - } + return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; } function parseParameter() { var node = createNode(142 /* Parameter */); - if (token === 97 /* ThisKeyword */) { + if (token() === 97 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { // in cases like // 'use strict' // function foo(static) @@ -9837,10 +14362,10 @@ var ts; } fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token !== 19 /* OpenBracketToken */) { + if (token() !== 19 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -9863,10 +14388,10 @@ var ts; // [] // nextToken(); - if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { + if (token() === 22 /* DotDotDotToken */ || token() === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { nextToken(); if (isIdentifier()) { return true; @@ -9882,23 +14407,23 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */) { + if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token !== 53 /* QuestionToken */) { + if (token() !== 53 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; + return token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || token() === 20 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153 /* IndexSignature */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); @@ -9907,69 +14432,70 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { var method = createNode(146 /* MethodSignature */, fullStart); - setModifiers(method, modifiers); + method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); parseTypeMemberSemicolon(); - return finishNode(method); + return addJSDocComment(finishNode(method)); } else { var property = createNode(144 /* PropertySignature */, fullStart); - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56 /* EqualsToken */) { + if (token() === 56 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } } function isTypeMemberStart() { var idToken; // Return true if we have the start of a signature member - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); nextToken(); } // Index signatures and computed property names are type members - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token === 17 /* OpenParenToken */ || - token === 25 /* LessThanToken */ || - token === 53 /* QuestionToken */ || - token === 54 /* ColonToken */ || + return token() === 17 /* OpenParenToken */ || + token() === 25 /* LessThanToken */ || + token() === 53 /* QuestionToken */ || + token() === 54 /* ColonToken */ || + token() === 24 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return parseSignatureMember(151 /* CallSignature */); } - if (token === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + if (token() === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152 /* ConstructSignature */); } var fullStart = getNodePos(); @@ -9981,7 +14507,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; + return token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */; } function parseTypeLiteral() { var node = createNode(159 /* TypeLiteral */); @@ -10021,10 +14547,19 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token === 21 /* DotToken */ ? undefined : node; + return token() === 21 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(166 /* LiteralType */); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8 /* NumericLiteral */; } function parseNonArrayType() { - switch (token) { + switch (token()) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10036,13 +14571,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9 /* StringLiteral */: - return parseStringLiteralTypeNode(); + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 36 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); case 103 /* VoidKeyword */: case 93 /* NullKeyword */: return parseTokenNode(); case 97 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -10062,7 +14602,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10079,7 +14619,12 @@ var ts; case 25 /* LessThanToken */: case 92 /* NewKeyword */: case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: return true; + case 36 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral); case 17 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. @@ -10090,7 +14635,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10104,9 +14649,8 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { - var types = [type]; - types.pos = type.pos; + if (token() === operator) { + var types = createNodeArray([type], type.pos); while (parseOptional(operator)) { types.push(parseConstituentType()); } @@ -10124,21 +14668,21 @@ var ts; return parseUnionOrIntersectionType(162 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); } function isStartOfFunctionType() { - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { return true; } - return token === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token)) { + if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token === 97 /* ThisKeyword */) { + if (isIdentifier() || token() === 97 /* ThisKeyword */) { nextToken(); return true; } - if (token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */) { + if (token() === 19 /* OpenBracketToken */ || token() === 15 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -10148,7 +14692,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { + if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -10156,17 +14700,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || - token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */) { + if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || + token() === 53 /* QuestionToken */ || token() === 56 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token === 18 /* CloseParenToken */) { + if (token() === 18 /* CloseParenToken */) { nextToken(); - if (token === 34 /* EqualsGreaterThanToken */) { + if (token() === 34 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -10189,7 +14733,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10197,13 +14741,13 @@ var ts; function parseType() { // The rules about 'yield' only apply to actual code/expression contexts. They don't // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(41943040 /* TypeExcludesFlags */, parseTypeWorker); + return doOutsideOfContext(327680 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156 /* FunctionType */); } - if (token === 92 /* NewKeyword */) { + if (token() === 92 /* NewKeyword */) { return parseFunctionOrConstructorType(157 /* ConstructorType */); } return parseUnionTypeOrHigher(); @@ -10213,7 +14757,7 @@ var ts; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: case 93 /* NullKeyword */: @@ -10241,7 +14785,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10271,10 +14815,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token !== 15 /* OpenBraceToken */ && - token !== 87 /* FunctionKeyword */ && - token !== 73 /* ClassKeyword */ && - token !== 55 /* AtToken */ && + return token() !== 15 /* OpenBraceToken */ && + token() !== 87 /* FunctionKeyword */ && + token() !== 73 /* ClassKeyword */ && + token() !== 55 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -10297,7 +14841,7 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token !== 56 /* EqualsToken */) { + if (token() !== 56 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse // this as an equals-value clause with a missing equals. @@ -10306,7 +14850,7 @@ var ts; // it's more likely that a { would be a allowed (as an object literal). While this // is also allowed for parameters, the risk is that we consume the { as an object // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15 /* OpenBraceToken */) || !isStartOfExpression()) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15 /* OpenBraceToken */) || !isStartOfExpression()) { // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - // do not try to parse initializer return undefined; @@ -10328,7 +14872,7 @@ var ts; // // Note: for ease of implementation we treat productions '2' and '3' as the same thing. // (i.e. they're both BinaryExpressions with an assignment operator in it). - // First, do the simple check if we have a YieldExpression (production '5'). + // First, do the simple check if we have a YieldExpression (production '6'). if (isYieldExpression()) { return parseYieldExpression(); } @@ -10360,7 +14904,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { + if (expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -10376,7 +14920,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114 /* YieldKeyword */) { + if (token() === 114 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -10412,7 +14956,7 @@ var ts; // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token === 37 /* AsteriskToken */ || isStartOfExpression())) { + (token() === 37 /* AsteriskToken */ || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -10424,11 +14968,11 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180 /* ArrowFunction */, asyncModifier.pos); - setModifiers(node, asyncModifier); + node.modifiers = asyncModifier; } else { node = createNode(180 /* ArrowFunction */, identifier.pos); @@ -10436,12 +14980,11 @@ var ts; var parameter = createNode(142 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = [parameter]; - node.parameters.pos = parameter.pos; + node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function tryParseParenthesizedArrowFunctionExpression() { var triState = isParenthesizedArrowFunctionExpression(); @@ -10460,25 +15003,25 @@ var ts; // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = !!(arrowFunction.flags & 256 /* Async */); + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. - var lastToken = token; + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 /* EqualsGreaterThanToken */ || lastToken === 15 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return finishNode(arrowFunction); + return addJSDocComment(finishNode(arrowFunction)); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */ || token === 118 /* AsyncKeyword */) { + if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */ || token() === 118 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token === 34 /* EqualsGreaterThanToken */) { + if (token() === 34 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -10488,16 +15031,16 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token !== 17 /* OpenParenToken */ && token !== 25 /* LessThanToken */) { + if (token() !== 17 /* OpenParenToken */ && token() !== 25 /* LessThanToken */) { return 0 /* False */; } } - var first = token; + var first = token(); var second = nextToken(); if (first === 17 /* OpenParenToken */) { if (second === 18 /* CloseParenToken */) { @@ -10586,7 +15129,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); @@ -10600,16 +15143,16 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token === 34 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 34 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { return 1 /* True */; } } @@ -10617,8 +15160,8 @@ var ts; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(180 /* ArrowFunction */); - setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 256 /* Async */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -10639,19 +15182,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token !== 34 /* EqualsGreaterThanToken */ && token !== 15 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 34 /* EqualsGreaterThanToken */ && token() !== 15 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); } - if (token !== 23 /* SemicolonToken */ && - token !== 87 /* FunctionKeyword */ && - token !== 73 /* ClassKeyword */ && + if (token() !== 23 /* SemicolonToken */ && + token() !== 87 /* FunctionKeyword */ && + token() !== 73 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -10724,16 +15267,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token === 38 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 38 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token === 90 /* InKeyword */ && inDisallowInContext()) { + if (token() === 90 /* InKeyword */ && inDisallowInContext()) { break; } - if (token === 116 /* AsKeyword */) { + if (token() === 116 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -10754,13 +15297,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token === 90 /* InKeyword */) { + if (inDisallowInContext() && token() === 90 /* InKeyword */) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token) { + switch (token()) { case 52 /* BarBarToken */: return 1; case 51 /* AmpersandAmpersandToken */: @@ -10817,7 +15360,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -10841,7 +15384,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119 /* AwaitKeyword */) { + if (token() === 119 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -10857,25 +15400,42 @@ var ts; return finishNode(node); } /** - * Parse ES7 unary expression and await expression + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] * - * ES7 UnaryExpression: - * 1) SimpleUnaryExpression[?yield] - * 2) IncrementExpression[?yield] ** UnaryExpression[?yield] */ function parseUnaryExpressionOrHigher() { - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - if (isIncrementExpression()) { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token === 38 /* AsteriskAsteriskToken */ ? + return token() === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token; + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token === 38 /* AsteriskAsteriskToken */) { + if (token() === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -10889,8 +15449,8 @@ var ts; /** * Parse ES7 simple-unary expression or higher: * - * ES7 SimpleUnaryExpression: - * 1) IncrementExpression[?yield] + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] * 2) delete UnaryExpression[?yield] * 3) void UnaryExpression[?yield] * 4) typeof UnaryExpression[?yield] @@ -10898,9 +15458,10 @@ var ts; * 6) - UnaryExpression[?yield] * 7) ~ UnaryExpression[?yield] * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] */ function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10917,6 +15478,10 @@ var ts; // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); + case 119 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } @@ -10924,17 +15489,17 @@ var ts; /** * Check if the current token can possibly be an ES7 increment expression. * - * ES7 IncrementExpression: + * ES7 UpdateExpression: * LeftHandSideExpression[?Yield] * LeftHandSideExpression[?Yield][no LineTerminator here]++ * LeftHandSideExpression[?Yield][no LineTerminator here]-- * ++LeftHandSideExpression[?Yield] * --LeftHandSideExpression[?Yield] */ - function isIncrementExpression() { + function isUpdateExpression() { // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10942,6 +15507,7 @@ var ts; case 78 /* DeleteKeyword */: case 101 /* TypeOfKeyword */: case 103 /* VoidKeyword */: + case 119 /* AwaitKeyword */: return false; case 25 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression @@ -10966,23 +15532,23 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseIncrementExpression() { - if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { + if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; - node.operator = token; + node.operator = token(); nextToken(); return finishNode(node); } @@ -11019,7 +15585,7 @@ var ts; // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - var expression = token === 95 /* SuperKeyword */ + var expression = token() === 95 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); // Now, we *may* be complete. However, we might have consumed the start of a @@ -11079,7 +15645,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token === 17 /* OpenParenToken */ || token === 21 /* DotToken */ || token === 19 /* OpenBracketToken */) { + if (token() === 17 /* OpenParenToken */ || token() === 21 /* DotToken */ || token() === 19 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. @@ -11131,7 +15697,7 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token === 25 /* LessThanToken */) { + if (inExpressionContext && token() === 25 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -11148,11 +15714,11 @@ var ts; } function parseJsxText() { var node = createNode(244 /* JsxText */, scanner.getStartPos()); - token = scanner.scanJsxToken(); + currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token) { + switch (token()) { case 244 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: @@ -11160,20 +15726,19 @@ var ts; case 25 /* LessThanToken */: return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); } - ts.Debug.fail("Unknown JSX child kind " + token); + ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = []; - result.pos = scanner.getStartPos(); + var result = createNodeArray(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - token = scanner.reScanJsxToken(); - if (token === 26 /* LessThanSlashToken */) { + currentToken = scanner.reScanJsxToken(); + if (token() === 26 /* LessThanSlashToken */) { // Closing tag break; } - else if (token === 1 /* EndOfFileToken */) { + else if (token() === 1 /* EndOfFileToken */) { // If we hit EOF, issue the error at the tag that lacks the closing element // rather than at the end of the file (which is useless) parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); @@ -11191,7 +15756,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute); var node; - if (token === 27 /* GreaterThanToken */) { + if (token() === 27 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors @@ -11220,7 +15785,7 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token === 97 /* ThisKeyword */ ? + var expression = token() === 97 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21 /* DotToken */)) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); @@ -11233,7 +15798,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); - if (token !== 16 /* CloseBraceToken */) { + if (token() !== 16 /* CloseBraceToken */) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -11246,14 +15811,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246 /* JsxAttribute */); node.name = parseIdentifierName(); - if (parseOptional(56 /* EqualsToken */)) { - switch (token) { + if (token() === 56 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); break; @@ -11303,7 +15868,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; @@ -11316,7 +15881,7 @@ var ts; indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. - if (token !== 20 /* CloseBracketToken */) { + if (token() !== 20 /* CloseBracketToken */) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { var literal = indexedAccess.argumentExpression; @@ -11327,10 +15892,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { + if (token() === 11 /* NoSubstitutionTemplateLiteral */ || token() === 12 /* TemplateHead */) { var tagExpression = createNode(176 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; - tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -11342,7 +15907,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -11358,7 +15923,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token === 17 /* OpenParenToken */) { + else if (token() === 17 /* OpenParenToken */) { var callExpr = createNode(174 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -11390,7 +15955,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17 /* OpenParenToken */: // foo( // this case are the only case where this token can legally follow a type argument // list. So we definitely want to treat this as a type arg list. @@ -11426,7 +15991,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: @@ -11482,8 +16047,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : + return token() === 22 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -11501,7 +16066,7 @@ var ts; } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123 /* GetKeyword */)) { - return addJSDocComment(parseAccessorDeclaration(149 /* GetAccessor */, fullStart, decorators, modifiers)); + return parseAccessorDeclaration(149 /* GetAccessor */, fullStart, decorators, modifiers); } else if (parseContextualModifier(131 /* SetKeyword */)) { return parseAccessorDeclaration(150 /* SetAccessor */, fullStart, decorators, modifiers); @@ -11521,7 +16086,7 @@ var ts; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } // check if it is short-hand property assignment or normal property assignment @@ -11529,7 +16094,7 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 /* CommaToken */ || token === 16 /* CloseBraceToken */ || token === 56 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 /* CommaToken */ || token() === 16 /* CloseBraceToken */ || token() === 56 /* EqualsToken */); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; @@ -11572,11 +16137,11 @@ var ts; setDecoratorContext(/*val*/ false); } var node = createNode(179 /* FunctionExpression */); - setModifiers(node, parseModifiers()); + node.modifiers = parseModifiers(); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256 /* Async */); + var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -11597,7 +16162,7 @@ var ts; parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token === 17 /* OpenParenToken */) { + if (node.typeArguments || token() === 17 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -11606,6 +16171,9 @@ var ts; function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var node = createNode(199 /* Block */); if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); } @@ -11677,8 +16245,8 @@ var ts; parseExpected(86 /* ForKeyword */); parseExpected(17 /* OpenParenToken */); var initializer = undefined; - if (token !== 23 /* SemicolonToken */) { - if (token === 102 /* VarKeyword */ || token === 108 /* LetKeyword */ || token === 74 /* ConstKeyword */) { + if (token() !== 23 /* SemicolonToken */) { + if (token() === 102 /* VarKeyword */ || token() === 108 /* LetKeyword */ || token() === 74 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -11704,11 +16272,11 @@ var ts; var forStatement = createNode(206 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); - if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { + if (token() !== 23 /* SemicolonToken */ && token() !== 18 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23 /* SemicolonToken */); - if (token !== 18 /* CloseParenToken */) { + if (token() !== 18 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18 /* CloseParenToken */); @@ -11760,7 +16328,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213 /* SwitchStatement */); @@ -11794,10 +16362,10 @@ var ts; var node = createNode(216 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token === 85 /* FinallyKeyword */) { + if (!node.catchClause || token() === 85 /* FinallyKeyword */) { parseExpected(85 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } @@ -11840,19 +16408,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token) || token === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token) { + switch (token()) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -11902,16 +16470,16 @@ var ts; continue; case 137 /* GlobalKeyword */: nextToken(); - return token === 15 /* OpenBraceToken */ || token === 69 /* Identifier */ || token === 82 /* ExportKeyword */; + return token() === 15 /* OpenBraceToken */ || token() === 69 /* Identifier */ || token() === 82 /* ExportKeyword */; case 89 /* ImportKeyword */: nextToken(); - return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || - token === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token); + return token() === 9 /* StringLiteral */ || token() === 37 /* AsteriskToken */ || + token() === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); case 82 /* ExportKeyword */: nextToken(); - if (token === 56 /* EqualsToken */ || token === 37 /* AsteriskToken */ || - token === 15 /* OpenBraceToken */ || token === 77 /* DefaultKeyword */ || - token === 116 /* AsKeyword */) { + if (token() === 56 /* EqualsToken */ || token() === 37 /* AsteriskToken */ || + token() === 15 /* OpenBraceToken */ || token() === 77 /* DefaultKeyword */ || + token() === 116 /* AsKeyword */) { return true; } continue; @@ -11927,7 +16495,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55 /* AtToken */: case 23 /* SemicolonToken */: case 15 /* OpenBraceToken */: @@ -11980,7 +16548,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */; + return isIdentifier() || token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -11988,7 +16556,7 @@ var ts; return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token) { + switch (token()) { case 23 /* SemicolonToken */: return parseEmptyStatement(); case 15 /* OpenBraceToken */: @@ -12061,7 +16629,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -12084,7 +16652,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82 /* ExportKeyword */: nextToken(); - switch (token) { + switch (token()) { case 77 /* DefaultKeyword */: case 56 /* EqualsToken */: return parseExportAssignment(fullStart, decorators, modifiers); @@ -12100,17 +16668,17 @@ var ts; var node = createMissingNode(239 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; return finishNode(node); } } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token !== 15 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 15 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -12118,7 +16686,7 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { return createNode(193 /* OmittedExpression */); } var node = createNode(169 /* BindingElement */); @@ -12131,7 +16699,7 @@ var ts; var node = createNode(169 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token !== 54 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 54 /* ColonToken */) { node.name = propertyName; } else { @@ -12157,13 +16725,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */ || isIdentifier(); + return token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -12172,21 +16740,21 @@ var ts; var node = createNode(218 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token)) { + if (!isInOrOfKeyword(token())) { node.initializer = parseInitializer(/*inParameter*/ false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219 /* VariableDeclarationList */); - switch (token) { + switch (token()) { case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: - node.flags |= 1024 /* Let */; + node.flags |= 1 /* Let */; break; case 74 /* ConstKeyword */: - node.flags |= 2048 /* Const */; + node.flags |= 2 /* Const */; break; default: ts.Debug.fail(); @@ -12201,7 +16769,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -12218,7 +16786,7 @@ var ts; function parseVariableStatement(fullStart, decorators, modifiers) { var node = createNode(200 /* VariableStatement */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return addJSDocComment(finishNode(node)); @@ -12226,12 +16794,12 @@ var ts; function parseFunctionDeclaration(fullStart, decorators, modifiers) { var node = createNode(220 /* FunctionDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); - node.name = node.flags & 512 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 256 /* Async */); + var isAsync = ts.hasModifier(node, 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); @@ -12239,7 +16807,7 @@ var ts; function parseConstructorDeclaration(pos, decorators, modifiers) { var node = createNode(148 /* Constructor */, pos); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(121 /* ConstructorKeyword */); fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); @@ -12248,12 +16816,12 @@ var ts; function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { var method = createNode(147 /* MethodDeclaration */, fullStart); method.decorators = decorators; - setModifiers(method, modifiers); + method.modifiers = modifiers; method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 256 /* Async */); + var isAsync = ts.hasModifier(method, 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); @@ -12261,7 +16829,7 @@ var ts; function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { var property = createNode(145 /* PropertyDeclaration */, fullStart); property.decorators = decorators; - setModifiers(property, modifiers); + property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -12274,11 +16842,11 @@ var ts; // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = modifiers && modifiers.flags & 32 /* Static */ + property.initializer = ts.hasModifier(property, 32 /* Static */) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(8388608 /* YieldContext */ | 4194304 /* DisallowInContext */, parseNonParameterInitializer); + : doOutsideOfContext(65536 /* YieldContext */ | 32768 /* DisallowInContext */, parseNonParameterInitializer); parseSemicolon(); - return finishNode(property); + return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); @@ -12286,7 +16854,7 @@ var ts; // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -12299,11 +16867,11 @@ var ts; function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.name = parsePropertyName(); fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -12319,12 +16887,12 @@ var ts; } function isClassMemberStart() { var idToken; - if (token === 55 /* AtToken */) { + if (token() === 55 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifierKind(token)) { - idToken = token; + while (ts.isModifierKind(token())) { + idToken = token(); // If the idToken is a class modifier (protected, private, public, and static), it is // certain that we are starting to parse class member. This allows better error recovery // Example: @@ -12336,17 +16904,17 @@ var ts; } nextToken(); } - if (token === 37 /* AsteriskToken */) { + if (token() === 37 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. // This can either be an identifier or the 'get' or 'set' keywords. if (isLiteralPropertyName()) { - idToken = token; + idToken = token(); nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... @@ -12357,7 +16925,7 @@ var ts; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. - switch (token) { + switch (token()) { case 17 /* OpenParenToken */: // Method declaration case 25 /* LessThanToken */: // Generic Method declaration case 54 /* ColonToken */: // Type Annotation for declaration @@ -12382,13 +16950,15 @@ var ts; if (!parseOptional(55 /* AtToken */)) { break; } - if (!decorators) { - decorators = []; - decorators.pos = decoratorStart; - } var decorator = createNode(143 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - decorators.push(finishNode(decorator)); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } } if (decorators) { decorators.end = getNodeEnd(); @@ -12403,12 +16973,11 @@ var ts; * In such situations, 'permitInvalidConstAsModifier' should be set to true. */ function parseModifiers(permitInvalidConstAsModifier) { - var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; - if (token === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + var modifierKind = token(); + if (token() === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { // We need to ensure that any subsequent modifiers appear on the same line // so that when 'const' is a standalone declaration, we don't issue an error. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { @@ -12420,37 +16989,33 @@ var ts; break; } } + var modifier = finishNode(createNode(modifierKind, modifierStart)); if (!modifiers) { - modifiers = []; - modifiers.pos = modifierStart; + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); } - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); } if (modifiers) { - modifiers.flags = flags; modifiers.end = scanner.getStartPos(); } return modifiers; } function parseModifiersForArrowFunction() { - var flags = 0; var modifiers; - if (token === 118 /* AsyncKeyword */) { + if (token() === 118 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); - var modifierKind = token; + var modifierKind = token(); nextToken(); - modifiers = []; - modifiers.pos = modifierStart; - flags |= ts.modifierToFlag(modifierKind); - modifiers.push(finishNode(createNode(modifierKind, modifierStart))); - modifiers.flags = flags; + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); modifiers.end = scanner.getStartPos(); } return modifiers; } function parseClassElement() { - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { var result = createNode(198 /* SemicolonClassElement */); nextToken(); return finishNode(result); @@ -12462,7 +17027,7 @@ var ts; if (accessor) { return accessor; } - if (token === 121 /* ConstructorKeyword */) { + if (token() === 121 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -12470,17 +17035,17 @@ var ts; } // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name - if (ts.tokenIsIdentifierOrKeyword(token) || - token === 9 /* StringLiteral */ || - token === 8 /* NumericLiteral */ || - token === 37 /* AsteriskToken */ || - token === 19 /* OpenBracketToken */) { + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 37 /* AsteriskToken */ || + token() === 19 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { // treat this as a property declaration with a missing name. - var name_7 = createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, /*questionToken*/ undefined); + var name_10 = createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, /*questionToken*/ undefined); } // 'isClassMemberStart' should have hinted not to attempt parsing. ts.Debug.fail("Should not have attempted to parse class member declaration."); @@ -12497,7 +17062,7 @@ var ts; function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(73 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -12511,7 +17076,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseNameOfClassDeclarationOrExpression() { // implements is a future reserved word so @@ -12524,7 +17089,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -12535,9 +17100,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { + if (token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */) { var node = createNode(251 /* HeritageClause */); - node.token = token; + node.token = token(); nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); @@ -12547,13 +17112,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); } function isHeritageClause() { - return token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + return token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); @@ -12561,18 +17126,18 @@ var ts; function parseInterfaceDeclaration(fullStart, decorators, modifiers) { var node = createNode(222 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(107 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ false); node.members = parseObjectTypeMembers(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { var node = createNode(223 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(134 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -12589,12 +17154,12 @@ var ts; var node = createNode(255 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { var node = createNode(224 /* EnumDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; parseExpected(81 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(15 /* OpenBraceToken */)) { @@ -12604,7 +17169,7 @@ var ts; else { node.members = createMissingList(); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseModuleBlock() { var node = createNode(226 /* ModuleBlock */, scanner.getStartPos()); @@ -12621,29 +17186,29 @@ var ts; var node = createNode(225 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 4096 /* Namespace */; + var namespaceFlag = flags & 16 /* Namespace */; node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 1 /* Export */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { var node = createNode(225 /* ModuleDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); - if (token === 137 /* GlobalKeyword */) { + node.modifiers = modifiers; + if (token() === 137 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); - node.flags |= 131072 /* GlobalAugmentation */; + node.flags |= 512 /* GlobalAugmentation */; } else { node.name = parseLiteralNode(/*internName*/ true); } - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -12652,24 +17217,24 @@ var ts; return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = modifiers ? modifiers.flags : 0; - if (token === 137 /* GlobalKeyword */) { + var flags = 0; + if (token() === 137 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126 /* NamespaceKeyword */)) { - flags |= 4096 /* Namespace */; + flags |= 16 /* Namespace */; } else { parseExpected(125 /* ModuleKeyword */); - if (token === 9 /* StringLiteral */) { + if (token() === 9 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 129 /* RequireKeyword */ && + return token() === 129 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -12694,30 +17259,30 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 /* CommaToken */ && token !== 136 /* FromKeyword */) { + if (token() !== 24 /* CommaToken */ && token() !== 136 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; var importEqualsDeclaration = createNode(229 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; - setModifiers(importEqualsDeclaration, modifiers); + importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; parseExpected(56 /* EqualsToken */); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); - return finishNode(importEqualsDeclaration); + return addJSDocComment(finishNode(importEqualsDeclaration)); } } // Import statement var importDeclaration = createNode(230 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; - setModifiers(importDeclaration, modifiers); + importDeclaration.modifiers = modifiers; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || - token === 37 /* AsteriskToken */ || - token === 15 /* OpenBraceToken */) { + token() === 37 /* AsteriskToken */ || + token() === 15 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136 /* FromKeyword */); } @@ -12742,7 +17307,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); + importClause.namedBindings = token() === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); } return finishNode(importClause); } @@ -12760,7 +17325,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9 /* StringLiteral */) { + if (token() === 9 /* StringLiteral */) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -12807,14 +17372,14 @@ var ts; // ExportSpecifier: // IdentifierName // IdentifierName as IdentifierName - var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token === 116 /* AsKeyword */) { + if (token() === 116 /* AsKeyword */) { node.propertyName = identifierName; parseExpected(116 /* AsKeyword */); - checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -12831,7 +17396,7 @@ var ts; function parseExportDeclaration(fullStart, decorators, modifiers) { var node = createNode(236 /* ExportDeclaration */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(37 /* AsteriskToken */)) { parseExpected(136 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); @@ -12841,7 +17406,7 @@ var ts; // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token === 136 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { parseExpected(136 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } @@ -12852,7 +17417,7 @@ var ts; function parseExportAssignment(fullStart, decorators, modifiers) { var node = createNode(235 /* ExportAssignment */, fullStart); node.decorators = decorators; - setModifiers(node, modifiers); + node.modifiers = modifiers; if (parseOptional(56 /* EqualsToken */)) { node.isExportEquals = true; } @@ -12931,7 +17496,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 /* Export */ + return ts.hasModifier(node, 1 /* Export */) || node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 240 /* ExternalModuleReference */ || node.kind === 230 /* ImportDeclaration */ || node.kind === 235 /* ExportAssignment */ @@ -12979,7 +17544,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: case 53 /* QuestionToken */: case 17 /* OpenParenToken */: @@ -12992,13 +17557,14 @@ var ts; case 97 /* ThisKeyword */: return true; } - return ts.tokenIsIdentifierOrKeyword(token); + return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 2 /* Latest */, 1 /* JS */); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -13018,12 +17584,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token === 47 /* BarToken */) { + if (token() === 47 /* BarToken */) { var unionType = createNode(261 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token === 56 /* EqualsToken */) { + if (token() === 56 /* EqualsToken */) { var optionalType = createNode(268 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; @@ -13034,20 +17600,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token === 19 /* OpenBracketToken */) { + if (token() === 19 /* OpenBracketToken */) { var arrayType = createNode(260 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } - else if (token === 53 /* QuestionToken */) { + else if (token() === 53 /* QuestionToken */) { var nullableType = createNode(263 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token === 49 /* ExclamationToken */) { + else if (token() === 49 /* ExclamationToken */) { var nonNullableType = createNode(264 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); @@ -13060,7 +17626,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: return parseJSDocAllType(); case 53 /* QuestionToken */: @@ -13087,9 +17653,16 @@ var ts; case 120 /* BooleanKeyword */: case 133 /* SymbolKeyword */: case 103 /* VoidKeyword */: + case 93 /* NullKeyword */: + case 135 /* UndefinedKeyword */: + case 127 /* NeverKeyword */: return parseTokenNode(); + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return parseJSDocLiteralType(); } - // TODO (drosen): Parse string literal types in JSDoc as well. return parseJSDocTypeReference(); } function parseJSDocThisType() { @@ -13119,7 +17692,7 @@ var ts; result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18 /* CloseParenToken */); - if (token === 54 /* ColonToken */) { + if (token() === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13136,12 +17709,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21 /* DotToken */)) { - if (token === 25 /* LessThanToken */) { + if (token() === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); break; } @@ -13176,19 +17749,7 @@ var ts; } function parseJSDocRecordType() { var result = createNode(265 /* JSDocRecordType */); - nextToken(); - result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); - checkForTrailingComma(result.members); - parseExpected(16 /* CloseBraceToken */); - return finishNode(result); - } - function parseJSDocRecordMember() { - var result = createNode(266 /* JSDocRecordMember */); - result.name = parseSimplePropertyName(); - if (token === 54 /* ColonToken */) { - nextToken(); - result.type = parseJSDocType(); - } + result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { @@ -13220,9 +17781,7 @@ var ts; } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); - var types = []; - types.pos = firstType.pos; - types.push(firstType); + var types = createNodeArray([firstType], firstType.pos); while (parseOptional(47 /* BarToken */)) { types.push(parseJSDocType()); } @@ -13234,6 +17793,11 @@ var ts; nextToken(); return finishNode(result); } + function parseJSDocLiteralType() { + var result = createNode(282 /* JSDocLiteralType */); + result.literal = parseLiteralTypeNode(); + return finishNode(result); + } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); // skip the ? @@ -13247,12 +17811,12 @@ var ts; // Foo // Foo(?= // (?| - if (token === 24 /* CommaToken */ || - token === 16 /* CloseBraceToken */ || - token === 18 /* CloseParenToken */ || - token === 27 /* GreaterThanToken */ || - token === 56 /* EqualsToken */ || - token === 47 /* BarToken */) { + if (token() === 24 /* CommaToken */ || + token() === 16 /* CloseBraceToken */ || + token() === 18 /* CloseParenToken */ || + token() === 27 /* GreaterThanToken */ || + token() === 56 /* EqualsToken */ || + token() === 47 /* BarToken */) { var result = createNode(259 /* JSDocUnknownType */, pos); return finishNode(result); } @@ -13265,26 +17829,32 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); sourceFile = { languageVariant: 0 /* Standard */, text: content }; - var jsDocComment = parseJSDocCommentWorker(start, length); + var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); - return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; + var JSDocState; + (function (JSDocState) { + JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; + })(JSDocState || (JSDocState = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -13294,123 +17864,260 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var comments = []; var result; // Check for /** (JSDoc opening part) - if (content.charCodeAt(start) === 47 /* slash */ && - content.charCodeAt(start + 1) === 42 /* asterisk */ && - content.charCodeAt(start + 2) === 42 /* asterisk */ && - content.charCodeAt(start + 3) !== 42 /* asterisk */) { - // + 3 for leading /**, - 5 in total for /** */ - scanner.scanRange(start + 3, length - 5, function () { - // Initially we can parse out a tag. We also have seen a starting asterisk. - // This is so that /** * @type */ doesn't parse. - var canParseTag = true; - var seenAsterisk = true; + if (!isJsDocStart(content, start)) { + return result; + } + // + 3 for leading /**, - 5 in total for /** */ + scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var advanceToken = true; + var state = 1 /* SawAsterisk */; + var margin = undefined; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5 /* WhitespaceTrivia */) { nextJSDocToken(); - while (token !== 1 /* EndOfFileToken */) { - switch (token) { - case 55 /* AtToken */: - if (canParseTag) { - parseTag(); - } - // This will take us to the end of the line, so it's OK to parse a tag on the next pass through the loop - seenAsterisk = false; - break; - case 4 /* NewLineTrivia */: - // After a line break, we can parse a tag, and we haven't seen an asterisk on the next line yet - canParseTag = true; - seenAsterisk = false; - break; - case 37 /* AsteriskToken */: - if (seenAsterisk) { - // If we've already seen an asterisk, then we can no longer parse a tag on this line - canParseTag = false; - } + } + if (token() === 4 /* NewLineTrivia */) { + state = 0 /* BeginningOfLine */; + nextJSDocToken(); + } + while (token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 55 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingNewlines(comments); + parseTag(indent); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 37 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { // Ignore the first asterisk on a line - seenAsterisk = true; - break; - case 69 /* Identifier */: - // Anything else is doc comment text. We can't do anything with it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - canParseTag = false; - break; - case 1 /* EndOfFileToken */: - break; - } + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 69 /* Identifier */: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + pushComment(scanner.getTokenText()); + state = 2 /* SavingComments */; + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */ || margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break; + default: + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { nextJSDocToken(); } - result = createJSDocComment(); - }); - } - return result; - function createJSDocComment() { - if (!tags) { - return undefined; + else { + advanceToken = true; + } } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */; + } + function createJSDocComment() { var result = createNode(273 /* JSDocComment */, start); result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 /* WhitespaceTrivia */ || token === 4 /* NewLineTrivia */) { + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } } - function parseTag() { - ts.Debug.assert(token === 55 /* AtToken */); + function parseTag(indent) { + ts.Debug.assert(token() === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return; } - var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); - addTag(tag); - } - function handleTag(atToken, tagName) { + var tag; if (tagName) { switch (tagName.text) { case "param": - return handleParamTag(atToken, tagName); + tag = parseParamTag(atToken, tagName); + break; case "return": case "returns": - return handleReturnTag(atToken, tagName); + tag = parseReturnTag(atToken, tagName); + break; case "template": - return handleTemplateTag(atToken, tagName); + tag = parseTemplateTag(atToken, tagName); + break; case "type": - return handleTypeTag(atToken, tagName); + tag = parseTypeTag(atToken, tagName); + break; case "typedef": - return handleTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; } } - return undefined; + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + // a badly malformed tag should not be added to the list of tags + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); } - function handleUnknownTag(atToken, tagName) { + function parseTagComments(indent) { + var comments = []; + var state = 1 /* SawAsterisk */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 55 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 55 /* AtToken */: + // Done + break; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 37 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += scanner.getTokenText().length; + break; + } + // FALLTHROUGH otherwise to record the * as a comment + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + if (token() === 55 /* AtToken */) { + // Done + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { var result = createNode(274 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } - function addTag(tag) { - if (tag) { - if (!tags) { - tags = []; - tags.pos = tag.pos; - } - tags.push(tag); - tags.end = tag.end; + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); } + else { + tags.push(tag); + } + tags.end = tag.end; } function tryParseTypeExpression() { - if (token !== 15 /* OpenBraceToken */) { - return undefined; - } - var typeExpression = parseJSDocTypeExpression(); - return typeExpression; + return tryParse(function () { + skipWhitespace(); + if (token() !== 15 /* OpenBraceToken */) { + return undefined; + } + return parseJSDocTypeExpression(); + }); } - function handleParamTag(atToken, tagName) { + function parseParamTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name; @@ -13418,6 +18125,7 @@ var ts; // Looking for something like '[foo]' or 'foo' if (parseOptionalToken(19 /* OpenBracketToken */)) { name = parseJSDocIdentifierName(); + skipWhitespace(); isBracketed = true; // May have an optional default, e.g. '[foo = 42]' if (parseOptionalToken(56 /* EqualsToken */)) { @@ -13425,7 +18133,7 @@ var ts; } parseExpected(20 /* CloseBracketToken */); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -13448,10 +18156,11 @@ var ts; result.preParameterName = preName; result.typeExpression = typeExpression; result.postParameterName = postName; + result.parameterName = postName || preName; result.isBracketed = isBracketed; return finishNode(result); } - function handleReturnTag(atToken, tagName) { + function parseReturnTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 276 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -13461,7 +18170,7 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handleTypeTag(atToken, tagName) { + function parseTypeTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 277 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } @@ -13471,10 +18180,11 @@ var ts; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function handlePropertyTag(atToken, tagName) { + function parsePropertyTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var name = parseJSDocIdentifierName(); + skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, ts.Diagnostics.Identifier_expected); return undefined; @@ -13486,7 +18196,7 @@ var ts; result.typeExpression = typeExpression; return finishNode(result); } - function handleTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); var typedefTag = createNode(279 /* JSDocTypedefTag */, atToken.pos); @@ -13494,12 +18204,13 @@ var ts; typedefTag.tagName = tagName; typedefTag.name = parseJSDocIdentifierName(); typedefTag.typeExpression = typeExpression; + skipWhitespace(); if (typeExpression) { if (typeExpression.type.kind === 267 /* JSDocTypeReference */) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69 /* Identifier */) { - var name_8 = jsDocTypeReference.name; - if (name_8.text === "Object") { + var name_11 = jsDocTypeReference.name; + if (name_11.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -13518,12 +18229,15 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token !== 1 /* EndOfFileToken */ && !parentTagTerminated) { + while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { nextJSDocToken(); - switch (token) { + switch (token()) { case 55 /* AtToken */: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); + if (!parentTagTerminated) { + resumePos = scanner.getStartPos(); + } } seenAsterisk = false; break; @@ -13549,11 +18263,12 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token === 55 /* AtToken */); + ts.Debug.assert(token() === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); + skipWhitespace(); if (!tagName) { return false; } @@ -13563,38 +18278,39 @@ var ts; // already has a @type tag, terminate the parent tag now. return false; } - parentTag.jsDocTypeTag = handleTypeTag(atToken, tagName); + parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); return true; case "prop": case "property": if (!parentTag.jsDocPropertyTags) { parentTag.jsDocPropertyTags = []; } - var propertyTag = handlePropertyTag(atToken, tagName); + var propertyTag = parsePropertyTag(atToken, tagName); parentTag.jsDocPropertyTags.push(propertyTag); return true; } return false; } - function handleTemplateTag(atToken, tagName) { + function parseTemplateTag(atToken, tagName) { if (ts.forEach(tags, function (t) { return t.kind === 278 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } // Type parameter list looks like '@template T,U,V' - var typeParameters = []; - typeParameters.pos = scanner.getStartPos(); + var typeParameters = createNodeArray(); while (true) { - var name_9 = parseJSDocIdentifierName(); - if (!name_9) { + var name_12 = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name_12) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141 /* TypeParameter */, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(141 /* TypeParameter */, name_12.pos); + typeParameter.name = name_12; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { nextJSDocToken(); + skipWhitespace(); } else { break; @@ -13609,10 +18325,10 @@ var ts; return result; } function nextJSDocToken() { - return token = scanner.scanJSDocToken(); + return currentToken = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -14111,7 +18827,6 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.bindTime = 0; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; @@ -14127,7 +18842,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } else if (node.kind === 226 /* ModuleBlock */) { @@ -14183,9 +18898,10 @@ var ts; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { - var start = new Date().getTime(); + ts.performance.mark("beforeBind"); binder(file, options); - ts.bindTime += new Date().getTime() - start; + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -14218,13 +18934,17 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; function bindSourceFile(f, opts) { file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; + skipTransformFlagAggregation = ts.isDeclarationFile(file); Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { bind(file); @@ -14248,6 +18968,7 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; } return bindSourceFile; function createSymbol(flags, name) { @@ -14262,10 +18983,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = {}; + symbol.exports = ts.createMap(); } if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = {}; + symbol.members = ts.createMap(); } if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; @@ -14326,7 +19047,7 @@ var ts; break; case 220 /* FunctionDeclaration */: case 221 /* ClassDeclaration */: - return node.flags & 512 /* Default */ ? "default" : undefined; + return ts.hasModifier(node, 512 /* Default */) ? "default" : undefined; case 269 /* JSDocFunctionType */: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; case 142 /* Parameter */: @@ -14335,7 +19056,7 @@ var ts; ts.Debug.assert(node.parent.kind === 269 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); - return "p" + index; + return "arg" + index; case 279 /* JSDocTypedefTag */: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; @@ -14363,11 +19084,14 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512 /* Default */; + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name !== undefined) { + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing"); + } + else { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict @@ -14379,6 +19103,11 @@ var ts; // declaration we have for this symbol, and then create a new symbol for this // declaration. // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. @@ -14386,42 +19115,44 @@ var ts; // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. - symbol = ts.hasProperty(symbolTable, name) - ? symbolTable[name] - : (symbolTable[name] = createSymbol(0 /* None */, name)); + symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0 /* None */, name)); if (name && (includes & 788448 /* Classifiable */)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (node.name) { - node.name.parent = node; + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbol = symbolTable[name] = createSymbol(0 /* None */, name); } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512 /* Default */) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + else { + if (node.name) { + node.name.parent = node; } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (ts.hasModifier(declaration, 512 /* Default */)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); + } } } - else { - symbol = createSymbol(0 /* None */, "__missing"); - } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 8388608 /* Alias */) { if (node.kind === 238 /* ExportSpecifier */ || (node.kind === 229 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -14446,10 +19177,10 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192 /* ExportContext */)) { + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); + (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | + (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -14489,7 +19220,7 @@ var ts; if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -14524,11 +19255,11 @@ var ts; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) // Reset all emit helper flags on node (for incremental scenarios) - node.flags &= ~4030464 /* ReachabilityAndEmitFlags */; + node.flags &= ~32128 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { - node.flags |= 32768 /* HasImplicitReturn */; + node.flags |= 128 /* HasImplicitReturn */; if (hasExplicitReturn) - node.flags |= 65536 /* HasExplicitReturn */; + node.flags |= 256 /* HasExplicitReturn */; } if (node.kind === 256 /* SourceFile */) { node.flags |= emitFlags; @@ -14549,7 +19280,7 @@ var ts; else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 16384 /* ContainsThis */ : node.flags & ~16384 /* ContainsThis */; + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; } else { bindChildren(node); @@ -14558,14 +19289,27 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindChildrenWorker(node) { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - bind(jsDocComment); - } + ts.forEach(node.jsDocComments, bind); } if (checkUnreachable(node)) { ts.forEachChild(node, bind); @@ -14614,6 +19358,9 @@ var ts; case 185 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; + case 186 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; case 187 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; @@ -14671,15 +19418,9 @@ var ts; } return false; } - function isNarrowingNullCheckOperands(expr1, expr2) { - return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); - } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } - function isNarrowingDiscriminant(expr) { - return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -14688,9 +19429,8 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || - isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 91 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); case 24 /* CommaToken */: @@ -14712,10 +19452,6 @@ var ts; } return isNarrowableReference(expr); } - function isNarrowingSwitchStatement(switchStatement) { - var expr = switchStatement.expression; - return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -14760,7 +19496,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -15104,6 +19840,15 @@ var ts; } else { ts.forEachChild(node, bind); + if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + ts.forEachChild(node, bind); + if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { @@ -15145,7 +19890,7 @@ var ts; currentFlow = finishFlowLabel(postExpressionLabel); } function bindInitializedVariableFlow(node) { - var name = node.name; + var name = !ts.isOmittedExpression(node) ? node.name : undefined; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var child = _a[_i]; @@ -15304,7 +20049,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 32 /* Static */ + return ts.hasModifier(node, 32 /* Static */) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -15329,16 +20074,16 @@ var ts; // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular // declarations with export modifiers) is an export context in which declarations are implicitly exported. if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 8192 /* ExportContext */; + node.flags |= 32 /* ExportContext */; } else { - node.flags &= ~8192 /* ExportContext */; + node.flags &= ~32 /* ExportContext */; } } function bindModuleDeclaration(node) { setExportContextFlag(node); if (ts.isAmbientModule(node)) { - if (node.flags & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (ts.isExternalModuleAugmentation(node)) { @@ -15398,8 +20143,8 @@ var ts; addDeclarationToSymbol(symbol, node, 131072 /* Signature */); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; + typeLiteralSymbol.members = ts.createMap(); + typeLiteralSymbol.members[symbol.name] = symbol; } function bindObjectLiteralExpression(node) { var ElementKind; @@ -15408,7 +20153,7 @@ var ts; ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; })(ElementKind || (ElementKind = {})); if (inStrictMode) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69 /* Identifier */) { @@ -15432,8 +20177,8 @@ var ts; continue; } if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } @@ -15456,7 +20201,7 @@ var ts; // fall through. default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -15509,8 +20254,8 @@ var ts; if (inStrictMode && node.expression.kind === 69 /* Identifier */) { // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its // UnaryExpression is a direct reference to a variable, function argument, or function name - var span = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { @@ -15523,8 +20268,8 @@ var ts; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. - var span = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } } } @@ -15638,6 +20383,9 @@ var ts; } parent = saveParent; } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } inStrictMode = saveInStrictMode; } function updateStrictModeStatementList(statements) { @@ -15717,7 +20465,7 @@ var ts; case 154 /* TypePredicate */: return checkTypePredicate(node); case 141 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); case 142 /* Parameter */: return bindParameter(node); case 218 /* VariableDeclaration */: @@ -15733,9 +20481,9 @@ var ts; case 254 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 255 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); case 247 /* JsxSpreadAttribute */: - emitFlags |= 1073741824 /* HasJsxSpreadAttribute */; + emitFlags |= 16384 /* HasJsxSpreadAttributes */; return; case 151 /* CallSignature */: case 152 /* ConstructSignature */: @@ -15781,10 +20529,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); case 279 /* JSDocTypedefTag */: case 223 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); case 224 /* EnumDeclaration */: return bindEnumDeclaration(node); case 225 /* ModuleDeclaration */: @@ -15835,18 +20583,15 @@ var ts; bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 235 /* ExportAssignment */ ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { // Export assignment in some sort of block construct bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } - else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 235 /* ExportAssignment */) { - // An export default clause with an identifier exports all meanings of that identifier - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); - } else { - // An export default clause with an expression exports a value - declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + ? 8388608 /* Alias */ + : 4 /* Property */; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } } function bindNamespaceExportDeclaration(node) { @@ -15868,7 +20613,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || {}; + file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); } function bindExportDeclaration(node) { @@ -15904,20 +20649,25 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 7340032 /* Export */ | 512 /* ValueModule */, 0 /* None */); } function bindThisPropertyAssignment(node) { - // Declare a 'member' in case it turns out the container was an ES5 class or ES6 constructor - var assignee; - if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 220 /* FunctionDeclaration */) { - assignee = container; + ts.Debug.assert(ts.isInJavaScriptFile(node)); + // Declare a 'member' if the container is an ES5 class or ES6 constructor + if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 179 /* FunctionExpression */) { + container.symbol.members = container.symbol.members || ts.createMap(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } else if (container.kind === 148 /* Constructor */) { - assignee = container.parent; + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var saveContainer = container; + container = container.parent; + var symbol = bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* None */); + if (symbol) { + // constructor-declared symbols can be overwritten by subsequent method declarations + symbol.isReplaceableByMethod = true; + } + container = saveContainer; } - else { - return; - } - assignee.symbol.members = assignee.symbol.members || {}; - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(assignee.symbol.members, assignee.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } function bindPrototypePropertyAssignment(node) { // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. @@ -15936,7 +20686,7 @@ var ts; } // Set up the members collection if it doesn't exist already if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } // Declare the method/property declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 0 /* PropertyExcludes */); @@ -15951,10 +20701,10 @@ var ts; function bindClassLikeDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 262144 /* HasClassExtends */; + emitFlags |= 1024 /* HasClassExtends */; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288 /* HasDecorators */; + emitFlags |= 2048 /* HasDecorators */; } } if (node.kind === 221 /* ClassDeclaration */) { @@ -15979,7 +20729,7 @@ var ts; // module might have an exported variable called 'prototype'. We can't allow that as // that would clash with the built-in 'prototype' for the class. var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (symbol.exports[prototypeSymbol.name]) { if (node.name) { node.name.parent = node; } @@ -16022,7 +20772,7 @@ var ts; if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node) && ts.nodeIsDecorated(node)) { - emitFlags |= (524288 /* HasDecorators */ | 1048576 /* HasParamDecorators */); + emitFlags |= (2048 /* HasDecorators */ | 4096 /* HasParamDecorators */); } if (inStrictMode) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a @@ -16045,7 +20795,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152 /* HasAsyncFunctions */; + emitFlags |= 8192 /* HasAsyncFunctions */; } } checkStrictModeFunctionName(node); @@ -16060,7 +20810,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152 /* HasAsyncFunctions */; + emitFlags |= 8192 /* HasAsyncFunctions */; } } if (currentFlow) { @@ -16073,10 +20823,10 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 2097152 /* HasAsyncFunctions */; + emitFlags |= 8192 /* HasAsyncFunctions */; } if (ts.nodeIsDecorated(node)) { - emitFlags |= 524288 /* HasDecorators */; + emitFlags |= 2048 /* HasDecorators */; } } return ts.hasDynamicName(node) @@ -16098,7 +20848,7 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatement(node) && node.kind !== 201 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 201 /* EmptyStatement */) || // report error on class declarations node.kind === 221 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set @@ -16119,7 +20869,7 @@ var ts; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && (node.kind !== 200 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3072 /* BlockScoped */ || + ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); @@ -16129,11 +20879,632 @@ var ts; return true; } } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 174 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 225 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 178 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 187 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 202 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 142 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 180 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 179 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 220 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 218 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 219 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 200 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 214 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 221 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 192 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 251 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 194 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 148 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 145 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 147 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 229 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 172 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */ + || isSuperOrSuperProperty(expression, expressionKind)) { + // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES6 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537133909 /* ArrayLiteralOrCallOrNewExcludes */; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 95 /* SuperKeyword */: + return true; + case 172 /* PropertyAccessExpression */: + case 173 /* ElementAccessExpression */: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 95 /* SuperKeyword */; + } + return false; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 56 /* EqualsToken */ + && (leftKind === 171 /* ObjectLiteralExpression */ + || leftKind === 170 /* ArrayLiteralExpression */)) { + // Destructuring assignments are ES6 syntax. + transformFlags |= 192 /* AssertES6 */ | 256 /* DestructuringAssignment */; + } + else if (operatorTokenKind === 38 /* AsteriskAsteriskToken */ + || operatorTokenKind === 60 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES7 syntax. + transformFlags |= 48 /* AssertES7 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // If the parameter has a question token, then it is TypeScript syntax. + if (node.questionToken) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the parameter's name is 'this', then it is TypeScript syntax. + if (subtreeFlags & 2048 /* ContainsDecorators */ + || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (modifierFlags & 92 /* ParameterPropertyModifier */) { + transformFlags |= 3 /* AssertTypeScript */ | 131072 /* ContainsParameterPropertyAssignments */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES6 */ | 65536 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~538968917 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 195 /* AsExpression */ + || expressionKind === 177 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 256 /* DestructuringAssignment */) { + transformFlags |= 256 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2 /* Ambient */) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES6 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax. + if ((subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) + || (modifierFlags & 1 /* Export */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537590613 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537590613 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 83 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES6 */; + break; + case 106 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var body = node.body; + if (body === undefined) { + // An overload constructor is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550593365 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var typeParameters = node.typeParameters; + var asteriskToken = node.asteriskToken; + // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // generic, or has a decorator. + if (!body + || typeParameters + || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) + || (subtreeFlags & 2048 /* ContainsDecorators */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // Currently, we only support generators that were originally async function bodies. + if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + transformFlags |= 1536 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // generic, or has a decorator. + if (!body + || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) + || (subtreeFlags & 2048 /* ContainsDecorators */)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer) { + transformFlags |= 4096 /* ContainsPropertyInitializer */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + var asteriskToken = node.asteriskToken; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. + if (modifierFlags & 1 /* Export */) { + transformFlags |= 3 /* AssertTypeScript */ | 192 /* AssertES6 */; + } + // If a FunctionDeclaration is async, then it is TypeScript syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES6 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + transformFlags |= 1536 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550726485 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var asteriskToken = node.asteriskToken; + // An async function expression is TypeScript syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES6 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + transformFlags |= 1536 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550726485 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var modifierFlags = ts.getModifierFlags(node); + // An async arrow function is TypeScript syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~550710101 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionKind === 95 /* SuperKeyword */) { + transformFlags |= 8192 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var nameKind = node.name.kind; + // A VariableDeclaration with a binding pattern is ES6 syntax. + if (nameKind === 167 /* ObjectBindingPattern */ || nameKind === 168 /* ArrayBindingPattern */) { + transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (modifierFlags & 2 /* Ambient */) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. + if (modifierFlags & 1 /* Export */) { + transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; + } + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES6 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES6 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 256 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES6 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536871765 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~546335573 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES6 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES6 */ | 1048576 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~538968917 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 536871765 /* NodeExcludes */; + switch (kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 115 /* AbstractKeyword */: + case 122 /* DeclareKeyword */: + case 118 /* AsyncKeyword */: + case 74 /* ConstKeyword */: + case 184 /* AwaitExpression */: + case 224 /* EnumDeclaration */: + case 255 /* EnumMember */: + case 177 /* TypeAssertionExpression */: + case 195 /* AsExpression */: + case 196 /* NonNullExpression */: + case 128 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 241 /* JsxElement */: + case 242 /* JsxSelfClosingElement */: + case 243 /* JsxOpeningElement */: + case 244 /* JsxText */: + case 245 /* JsxClosingElement */: + case 246 /* JsxAttribute */: + case 247 /* JsxSpreadAttribute */: + case 248 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 12 /* AssertJsx */; + break; + case 82 /* ExportKeyword */: + // This node is both ES6 and TypeScript syntax. + transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; + break; + case 77 /* DefaultKeyword */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* TemplateHead */: + case 13 /* TemplateMiddle */: + case 14 /* TemplateTail */: + case 189 /* TemplateExpression */: + case 176 /* TaggedTemplateExpression */: + case 254 /* ShorthandPropertyAssignment */: + case 208 /* ForOfStatement */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES6 */; + break; + case 190 /* YieldExpression */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES6 */ | 4194304 /* ContainsYield */; + break; + case 117 /* AnyKeyword */: + case 130 /* NumberKeyword */: + case 127 /* NeverKeyword */: + case 132 /* StringKeyword */: + case 120 /* BooleanKeyword */: + case 133 /* SymbolKeyword */: + case 103 /* VoidKeyword */: + case 141 /* TypeParameter */: + case 144 /* PropertySignature */: + case 146 /* MethodSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 153 /* IndexSignature */: + case 154 /* TypePredicate */: + case 155 /* TypeReference */: + case 156 /* FunctionType */: + case 157 /* ConstructorType */: + case 158 /* TypeQuery */: + case 159 /* TypeLiteral */: + case 160 /* ArrayType */: + case 161 /* TupleType */: + case 162 /* UnionType */: + case 163 /* IntersectionType */: + case 164 /* ParenthesizedType */: + case 222 /* InterfaceDeclaration */: + case 223 /* TypeAliasDeclaration */: + case 165 /* ThisType */: + case 166 /* LiteralType */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 140 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 191 /* SpreadElementExpression */: + // This node is ES6 syntax, but is handled by a containing node. + transformFlags |= 262144 /* ContainsSpreadElementExpression */; + break; + case 95 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES6 */; + break; + case 97 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 8192 /* ContainsLexicalThis */; + break; + case 167 /* ObjectBindingPattern */: + case 168 /* ArrayBindingPattern */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + break; + case 143 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 2048 /* ContainsDecorators */; + break; + case 171 /* ObjectLiteralExpression */: + excludeFlags = 537430869 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES6 */; + } + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 8192 /* ContainsLexicalThis */; + } + break; + case 170 /* ArrayLiteralExpression */: + case 175 /* NewExpression */: + excludeFlags = 537133909 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */) { + // If the this node contains a SpreadElementExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES6 */; + } + break; + case 204 /* DoStatement */: + case 205 /* WhileStatement */: + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES6 */; + } + break; + case 256 /* SourceFile */: + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES6 */; + } + break; + case 211 /* ReturnStatement */: + case 209 /* ContinueStatement */: + case 210 /* BreakStatement */: + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -16146,7 +21517,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -16172,7 +21542,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = {}; + var emptySymbols = ts.createMap(); var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -16224,36 +21594,47 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, + getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var stringLiteralTypes = ts.createMap(); + var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(4096 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 33554432 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); - var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); - var esSymbolType = createIntrinsicType(16777216 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(16 /* Void */, "void"); - var undefinedType = createIntrinsicType(32 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(64 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 /* Null */ | 2097152 /* ContainsWideningType */, "null"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var neverType = createIntrinsicType(134217728 /* Never */, "never"); + var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); + var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(1024 /* Void */, "void"); + var neverType = createIntrinsicType(8192 /* Never */, "never"); + var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = {}; + emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 134217728 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var globals = {}; + var globals = ts.createMap(); /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -16262,6 +21643,7 @@ var ts; var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; + var tryGetGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; @@ -16297,10 +21679,8 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var tupleTypes = {}; - var unionTypes = {}; - var intersectionTypes = {}; - var stringLiteralTypes = {}; + var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); + var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -16341,26 +21721,45 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; + TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; + TypeFacts[TypeFacts["All"] = 8388607] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. + TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; + TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; + TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; + TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; + TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; + TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; + TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; + TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; + TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; + TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; + TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; + TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; + TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; + TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; + TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; + TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; + TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; + TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1 /* TypeofEQString */, "number": 2 /* TypeofEQNumber */, "boolean": 4 /* TypeofEQBoolean */, @@ -16368,8 +21767,8 @@ var ts; "undefined": 16384 /* EQUndefined */, "object": 16 /* TypeofEQObject */, "function": 32 /* TypeofEQFunction */ - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128 /* TypeofNEString */, "number": 256 /* TypeofNENumber */, "boolean": 512 /* TypeofNEBoolean */, @@ -16377,17 +21776,17 @@ var ts; "undefined": 131072 /* NEUndefined */, "object": 2048 /* TypeofNEObject */, "function": 4096 /* TypeofNEFunction */ - }; - var typeofTypesByName = { + }); + var typeofTypesByName = ts.createMap({ "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }; + }); var jsxElementType; /** Things we lazy load from the JSX namespace */ - var jsxTypes = {}; + var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -16397,10 +21796,11 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = {}; - var assignableRelation = {}; - var comparableRelation = {}; - var identityRelation = {}; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; var TypeSystemPropertyName; @@ -16410,10 +21810,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -16441,13 +21839,13 @@ var ts; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) - result |= 107455 /* EnumMemberExcludes */; + result |= 900095 /* EnumMemberExcludes */; if (flags & 16 /* Function */) result |= 106927 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 899519 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 792960 /* InterfaceExcludes */; + result |= 792968 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) @@ -16461,9 +21859,9 @@ var ts; if (flags & 65536 /* SetAccessor */) result |= 74687 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 530912 /* TypeParameterExcludes */; + result |= 530920 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 793056 /* TypeAliasExcludes */; + result |= 793064 /* TypeAliasExcludes */; if (flags & 8388608 /* Alias */) result |= 8388608 /* AliasExcludes */; return result; @@ -16484,9 +21882,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = cloneSymbolTable(symbol.members); + result.members = ts.cloneMap(symbol.members); if (symbol.exports) - result.exports = cloneSymbolTable(symbol.exports); + result.exports = ts.cloneMap(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -16508,12 +21906,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = {}; + target.members = ts.createMap(); mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = {}; + target.exports = ts.createMap(); mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -16529,28 +21927,17 @@ var ts; }); } } - function cloneSymbolTable(symbolTable) { - var result = {}; - for (var id in symbolTable) { - if (ts.hasProperty(symbolTable, id)) { - result[id] = symbolTable[id]; - } - } - return result; - } function mergeSymbolTable(target, source) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (!ts.hasProperty(target, id)) { - target[id] = source[id]; - } - else { - var symbol = target[id]; - if (!(symbol.flags & 33554432 /* Merged */)) { - target[id] = symbol = cloneSymbol(symbol); - } - mergeSymbol(symbol, source[id]); + var targetSymbol = target[id]; + if (!targetSymbol) { + target[id] = source[id]; + } + else { + if (!(targetSymbol.flags & 33554432 /* Merged */)) { + target[id] = targetSymbol = cloneSymbol(targetSymbol); } + mergeSymbol(targetSymbol, source[id]); } } } @@ -16578,7 +21965,7 @@ var ts; } // obtain item referenced by 'export=' mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1536 /* Namespace */) { + if (mainModule.flags & 1920 /* Namespace */) { // if module symbol has already been merged - it is safe to use it. // otherwise clone it mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); @@ -16591,14 +21978,12 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (ts.hasProperty(source, id)) { - if (ts.hasProperty(target, id)) { - // Error on redeclarations - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; - } + if (target[id]) { + // Error on redeclarations + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; } } function addDeclarationDiagnostic(id, message) { @@ -16613,24 +21998,26 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { return node.kind === 256 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning && ts.hasProperty(symbols, name)) { + if (meaning) { var symbol = symbols[name]; - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608 /* Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + if (symbol) { + ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { return symbol; } + if (symbol.flags & 8388608 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } } } // return undefined if we can't find a symbol. @@ -16707,7 +22094,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 145 /* PropertyDeclaration */ && - (current.parent.flags & 32 /* Static */) === 0 && + (ts.getModifierFlags(current.parent) & 32 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -16739,7 +22126,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793056 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 142 /* Parameter */ || @@ -16793,7 +22180,7 @@ var ts; // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, // which is not the desired behavior. - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 /* Alias */ && ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) { break; @@ -16816,7 +22203,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(location.flags & 32 /* Static */)) { + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -16829,8 +22216,8 @@ var ts; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 222 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { - if (lastLocation && lastLocation.flags & 32 /* Static */) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -16859,7 +22246,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -16924,8 +22311,10 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16957,8 +22346,8 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - // If we're in an external module, we can't reference symbols created from UMD export declarations - if (result && isInExternalModule) { + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -16968,7 +22357,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if (!errorLocation || (errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); @@ -16987,7 +22376,7 @@ var ts; } // No static member is present. // Check if we're in an instance method and look for a relevant instance member. - if (location === container && !(location.flags & 32 /* Static */)) { + if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); @@ -17000,25 +22389,36 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var parentClassExpression = errorLocation; - while (parentClassExpression) { - var kind = parentClassExpression.kind; - if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { - parentClassExpression = parentClassExpression.parent; - continue; - } - if (kind === 194 /* ExpressionWithTypeArguments */) { - break; - } - return false; - } - if (!parentClassExpression) { - return false; - } - var expression = parentClassExpression.expression; - if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); + if (isError) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - return true; + } + return isError; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 69 /* Identifier */: + case 172 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 194 /* ExpressionWithTypeArguments */: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } } return false; } @@ -17027,7 +22427,7 @@ var ts; // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -17069,7 +22469,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -17106,7 +22506,7 @@ var ts; // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' // property with the type/namespace side interface 'Point'. function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793056 /* Type */ | 1536 /* Namespace */)) { + if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -17122,9 +22522,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536 /* Module */) { - var exports = getExportsOfSymbol(symbol); - if (ts.hasProperty(exports, name)) { - return resolveSymbol(exports[name]); + var exportedSymbol = getExportsOfSymbol(symbol)[name]; + if (exportedSymbol) { + return resolveSymbol(exportedSymbol); } } } @@ -17140,27 +22540,31 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { - if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + var name_13 = specifier.propertyName || specifier.name; + if (name_13.text) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); } // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); } return symbol; } @@ -17175,10 +22579,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); + return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -17199,7 +22603,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); @@ -17207,6 +22611,7 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -17239,6 +22644,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); @@ -17266,27 +22672,27 @@ var ts; } // Check for case 1 and 3 in the above example if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { - return resolveEntityName(entityName, 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); } // Resolves a qualified name and any involved aliases - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias) { + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } var symbol; if (name.kind === 69 /* Identifier */) { - var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); + var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } @@ -17294,7 +22700,7 @@ var ts; else if (name.kind === 139 /* QualifiedName */ || name.kind === 172 /* PropertyAccessExpression */) { var left = name.kind === 139 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 139 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); + var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -17304,7 +22710,7 @@ var ts; symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); } return undefined; } @@ -17323,9 +22729,12 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. - var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); + var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } @@ -17337,7 +22746,7 @@ var ts; return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { @@ -17346,7 +22755,7 @@ var ts; } if (moduleNotFoundError) { // report errors only if it was requested - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return undefined; } @@ -17358,7 +22767,14 @@ var ts; } if (moduleNotFoundError) { // report errors only if it was requested - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } return undefined; } @@ -17397,7 +22813,7 @@ var ts; */ function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !ts.hasProperty(target, id)) { + if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -17405,7 +22821,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -17425,12 +22841,12 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = cloneSymbolTable(symbol.exports); + var symbols = ts.cloneMap(symbol.exports); // All export * declarations are collected in an __export symbol by the binder var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = {}; - var lookupTable = {}; + var nestedSymbols = ts.createMap(); + var lookupTable = ts.createMap(); for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -17440,7 +22856,7 @@ var ts; for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -17495,8 +22911,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount; typeCount++; + result.id = typeCount; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -17504,6 +22920,12 @@ var ts; type.intrinsicName = intrinsicName; return type; } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -17522,14 +22944,12 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (ts.hasProperty(members, id)) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); } } } @@ -17547,7 +22967,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(2097152 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -17574,7 +22994,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1536 /* Namespace */; + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -17597,11 +23017,11 @@ var ts; } } // If symbol is directly available by its name in the symbol table - if (isAccessible(ts.lookUp(symbols, symbol.name))) { + if (isAccessible(symbols[symbol.name])) { return [symbol]; } // Check if symbol is any of the alias - return ts.forEachValue(symbols, function (symbolFromSymbolTable) { + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) { @@ -17632,12 +23052,12 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - if (!ts.hasProperty(symbolTable, symbol.name)) { + var symbolFromSymbolTable = symbolTable[symbol.name]; + if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; } // If the symbol with this name is present it should refer to the symbol - var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { // No need to qualify return true; @@ -17671,7 +23091,15 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { var initialSymbol = symbol; var meaningToLook = meaning; @@ -17679,12 +23107,12 @@ var ts; // Symbol is accessible if it by itself is accessible var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536 /* Namespace */) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined }; } return hasAccessibleDeclarations; @@ -17736,7 +23164,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -17748,16 +23176,21 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1 /* Export */) && + !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -17778,16 +23211,16 @@ var ts; entityName.parent.kind === 229 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration - meaning = 1536 /* Namespace */; + meaning = 1920 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 793056 /* Type */; + meaning = 793064 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* NotAccessible */, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -17834,6 +23267,31 @@ var ts; ts.releaseStringWriter(writer); return result; } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144 /* Nullable */)) { + if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; + var count = baseType.types.length; + if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + result.push(baseType); + i += count - 1; + continue; + } + } + result.push(t); + } + } + if (flags & 4096 /* Null */) + result.push(nullType); + if (flags & 2048 /* Undefined */) + result.push(undefinedType); + return result || types; + } function visibilityToString(flags) { if (flags === 8 /* Private */) { return "private"; @@ -17860,6 +23318,9 @@ var ts; node.parent.kind === 226 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } + function literalTypeToString(type) { + return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text; + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -17932,7 +23393,7 @@ var ts; } parentSymbol = symbol; } - // const the writer know we just wrote out a symbol. The declaration emitter writer uses + // Let the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // @@ -17940,32 +23401,32 @@ var ts; // up front (for example, during checking) could determine if we need to emit the imports // and we could then access that data during declaration emit. writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning) { - if (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_7) { + walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else { - // If we didn't find accessible symbol chain for this symbol, break if this is external module - if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { - return; - } - // if this is anonymous type break - if (symbol.flags & 2048 /* TypeLiteral */ || symbol.flags & 4096 /* ObjectLiteral */) { - return; - } - appendParentTypeArgumentsAndSymbolName(symbol); + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } + else if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } } // Get qualified name if the symbol is not a type parameter // and there is an enclosing declaration or we specifically @@ -17973,47 +23434,57 @@ var ts; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; var typeFormatFlag = 128 /* UseFullyQualifiedType */ & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning); - return; + walkSymbol(symbol, meaning, /*endOfChain*/ true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); } - return appendParentTypeArgumentsAndSymbolName(symbol); } function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16 /* WriteOwnNameForAnyLike */; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { + var nextFlags = flags & ~512 /* InTypeAlias */; // Write undefined/null type as any - if (type.flags & 150995071 /* Intrinsic */) { + if (type.flags & 16015 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 33554432 /* ThisType */) { + else if (type.flags & 268435456 /* ThisType */) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 4096 /* Reference */) { - writeTypeReference(type, flags); + else if (type.flags & 131072 /* Reference */) { + writeTypeReference(type, nextFlags); } - else if (type.flags & (1024 /* Class */ | 2048 /* Interface */ | 128 /* Enum */ | 512 /* TypeParameter */)) { + else if (type.flags & 256 /* EnumLiteral */) { + buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + writePunctuation(writer, 21 /* DotToken */); + appendSymbolNameOnly(type.symbol, writer); + } + else if (type.flags & (32768 /* Class */ | 65536 /* Interface */ | 16 /* Enum */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (type.flags & 8192 /* Tuple */) { - writeTupleType(type); + else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + // Only write out inferred type with its corresponding type-alias if type-alias is visible + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } - else if (type.flags & 49152 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, flags); + else if (type.flags & 1572864 /* UnionOrIntersection */) { + writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & 65536 /* Anonymous */) { - writeAnonymousType(type, flags); + else if (type.flags & 2097152 /* Anonymous */) { + writeAnonymousType(type, nextFlags); } - else if (type.flags & 256 /* StringLiteral */) { - writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); + else if (type.flags & 96 /* StringOrNumberLiteral */) { + writer.writeStringLiteral(literalTypeToString(type)); } else { // Should never get here @@ -18040,7 +23511,7 @@ var ts; function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); @@ -18062,6 +23533,11 @@ var ts; writePunctuation(writer, 19 /* OpenBracketToken */); writePunctuation(writer, 20 /* CloseBracketToken */); } + else if (type.target.flags & 262144 /* Tuple */) { + writePunctuation(writer, 19 /* OpenBracketToken */); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24 /* CommaToken */); + writePunctuation(writer, 20 /* CloseBracketToken */); + } else { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those @@ -18073,14 +23549,14 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_7 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_7); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_7, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -18089,16 +23565,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } - function writeTupleType(type) { - writePunctuation(writer, 19 /* OpenBracketToken */); - writeTypeList(type.elementTypes, 24 /* CommaToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); - } function writeUnionOrIntersectionType(type, flags) { if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - writeTypeList(type.types, type.flags & 16384 /* Union */ ? 47 /* BarToken */ : 46 /* AmpersandToken */); + if (type.flags & 524288 /* Union */) { + writeTypeList(formatUnionTypes(type.types), 47 /* BarToken */); + } + else { + writeTypeList(type.types, 46 /* AmpersandToken */); + } if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -18118,7 +23594,7 @@ var ts; var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } else { // Recursive usage, use any @@ -18142,7 +23618,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32 /* Static */; })); + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -18331,7 +23807,7 @@ var ts; } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingElement.kind === 193 /* OmittedExpression */) { + if (ts.isOmittedExpression(bindingElement)) { return; } ts.Debug.assert(bindingElement.kind === 169 /* BindingElement */); @@ -18484,21 +23960,21 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_8 = getDeclarationContainer(node); + var parent_9 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_8.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_8))) { - return isGlobalSourceFile(parent_8); + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { + return isGlobalSourceFile(parent_9); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_8); + return isDeclarationVisible(parent_9); case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.flags & (8 /* Private */ | 16 /* Protected */)) { + if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } @@ -18527,8 +24003,9 @@ var ts; return false; // Type parameters are always visible case 141 /* TypeParameter */: - // Source file is always visible + // Source file and namespace export are always visible case 256 /* SourceFile */: + case 228 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module case 235 /* ExportAssignment */: @@ -18541,13 +24018,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -18565,7 +24042,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -18618,7 +24095,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - ts.Debug.assert(!!(target.flags & 1024 /* Class */)); + ts.Debug.assert(!!(target.flags & 32768 /* Class */)); return target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { @@ -18667,7 +24144,7 @@ var ts; return type && (type.flags & 1 /* Any */) !== 0; } function isTypeNever(type) { - return type && (type.flags & 134217728 /* Never */) !== 0; + return type && (type.flags & 8192 /* Never */) !== 0; } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. @@ -18705,15 +24182,15 @@ var ts; // undefined or any type of the parent. if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { - return checkExpressionCached(declaration.initializer); + return checkDeclarationInitializer(declaration); } return parentType; } var type; if (pattern.kind === 167 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + var name_14 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_14)) { // computed properties with non-literal names are treated as 'any' return anyType; } @@ -18722,12 +24199,12 @@ var ts; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_14); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); return unknownType; } } @@ -18744,7 +24221,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -18759,10 +24236,12 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } - return type; + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -18796,11 +24275,11 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? addTypeKind(type, 32 /* Undefined */) : type; + return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 134217728 /* JavaScriptFile */) { + if (declaration.flags & 1048576 /* JavaScriptFile */) { // If this is a variable in a JavaScript file, then use the JSDoc type (if it has // one as its type), otherwise fallback to the below standard TS codepaths to // try to figure it out. @@ -18844,16 +24323,22 @@ var ts; } } // Use contextual parameter type if one is available - var type = declaration.symbol.name === "this" - ? getContextuallyTypedThisType(func) - : getContextuallyTypedParameterType(declaration); + var type = void 0; + if (declaration.symbol.name === "this") { + var thisParameter = getContextualThisParameter(func); + type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + } + else { + type = getContextuallyTypedParameterType(declaration); + } if (type) { return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ declaration.questionToken && includeOptionality); + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } // If it is a short-hand property assignment, use the type of the identifier if (declaration.kind === 254 /* ShorthandPropertyAssignment */) { @@ -18861,7 +24346,7 @@ var ts; } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); } // No type specified and nothing can be inferred return undefined; @@ -18869,23 +24354,21 @@ var ts; // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. - function getTypeFromBindingElement(element, includePatternInType) { + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - var type = checkExpressionCached(element.initializer); - reportErrorsFromWidening(element, type); - return getWidenedType(type); + return checkDeclarationInitializer(element); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType); + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } // Return the type implied by an object binding pattern - function getTypeFromObjectBindingPattern(pattern, includePatternInType) { - var members = {}; + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createMap(); var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -18897,7 +24380,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -18906,24 +24389,25 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */; + result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; } return result; } // Return the type implied by an array binding pattern - function getTypeFromArrayBindingPattern(pattern, includePatternInType) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; - if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); if (includePatternInType) { - var result = createNewTupleType(elementTypes); + result = cloneTypeReference(result); result.pattern = pattern; - return result; } - return createTupleType(elementTypes); + return result; } // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself // and without regard to its context (i.e. without regard any type annotation or initializer associated with the @@ -18932,10 +24416,10 @@ var ts; // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. - function getTypeFromBindingPattern(pattern, includePatternInType) { + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { return pattern.kind === 167 /* ObjectBindingPattern */ - ? getTypeFromObjectBindingPattern(pattern, includePatternInType) - : getTypeFromArrayBindingPattern(pattern, includePatternInType); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it @@ -18991,24 +24475,34 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } + if (declaration.flags & 1048576 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = undefined; - // Handle module.exports = expr or this.p = expr - if (declaration.kind === 187 /* BinaryExpression */) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - else if (declaration.kind === 172 /* PropertyAccessExpression */) { - // Declarations only exist for property access expressions for certain - // special assignment kinds - if (declaration.parent.kind === 187 /* BinaryExpression */) { - // Handle exports.p = expr or className.prototype.method = expr - type = checkExpressionCached(declaration.parent.right); + var type = void 0; + // Handle certain special assignment kinds, which happen to union across multiple declarations: + // * module.exports = expr + // * exports.p = expr + // * this.p = expr + // * className.prototype.method = expr + if (declaration.kind === 187 /* BinaryExpression */ || + declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { + // Use JS Doc type if present on parent expression statement + if (declaration.flags & 1048576 /* JavaScriptFile */) { + var typeTag = ts.getJSDocTypeTag(declaration.parent); + if (typeTag && typeTag.typeExpression) { + return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + } } + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? + checkExpressionCached(decl.right) : + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, /*subtypeReduction*/ true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { @@ -19053,7 +24547,7 @@ var ts; if (!links.type) { var getter = ts.getDeclarationOfKind(symbol, 149 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 150 /* SetAccessor */); - if (getter && getter.flags & 134217728 /* JavaScriptFile */) { + if (getter && getter.flags & 1048576 /* JavaScriptFile */) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -19081,7 +24575,13 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } type = anyType; } @@ -19101,13 +24601,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(65536 /* Anonymous */, symbol); + var type = createObjectType(2097152 /* Anonymous */, symbol); links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - addTypeKind(type, 32 /* Undefined */) : type; + includeFalsyTypes(type, 2048 /* Undefined */) : type; } } return links.type; @@ -19115,7 +24615,7 @@ var ts; function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.type = getDeclaredTypeOfEnumMember(symbol); } return links.type; } @@ -19163,7 +24663,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 4096 /* Reference */ ? type.target : type; + return type.flags & 131072 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -19234,7 +24734,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -19246,7 +24746,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -19266,7 +24766,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896 /* ObjectType */) { + if (baseConstructorType.flags & 2588672 /* ObjectType */) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -19284,25 +24784,28 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { - var isClass = type.symbol.flags & 32 /* Class */; - var isInterface = type.symbol.flags & 64 /* Interface */; if (!type.resolvedBaseTypes) { - if (!isClass && !isInterface) { + if (type.flags & 262144 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { ts.Debug.fail("type must be class or interface"); } - if (isClass) { - resolveBaseTypesOfClass(type); - } - if (isInterface) { - resolveBaseTypesOfInterface(type); - } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 80896 /* ObjectType */)) { + if (!(baseConstructorType.flags & 2588672 /* ObjectType */)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -19329,7 +24832,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */))) { + if (!(getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -19364,7 +24867,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { + if (getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -19392,15 +24895,15 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 222 /* InterfaceDeclaration */) { - if (declaration.flags & 16384 /* ContainsThis */) { + if (declaration.flags & 64 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isSupportedExpressionWithTypeArguments(node)) { - var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -19414,7 +24917,7 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 1024 /* Class */ : 2048 /* Interface */; + var kind = symbol.flags & 32 /* Class */ ? 32768 /* Class */ : 65536 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -19423,16 +24926,16 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 1024 /* Class */ || !isIndependentInterface(symbol)) { - type.flags |= 4096 /* Reference */; + if (outerTypeParameters || localTypeParameters || kind === 32768 /* Class */ || !isIndependentInterface(symbol)) { + type.flags |= 131072 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = {}; + type.instantiations = ts.createMap(); type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -19447,8 +24950,9 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var type = void 0; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); + var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -19459,14 +24963,14 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type); + type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); } if (popTypeResolution()) { - links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (links.typeParameters) { + links.typeParameters = typeParameters; + if (typeParameters) { // Initialize the instantiation cache for generic type aliases. The declared type corresponds to // an instantiation of the type alias with the type parameters supplied as type arguments. - links.instantiations = {}; + links.instantiations = ts.createMap(); links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -19478,19 +24982,84 @@ var ts; } return links.declaredType; } + function isLiteralEnumMember(symbol, member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + return expr.kind === 8 /* NumericLiteral */ || + expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */ || + expr.kind === 69 /* Identifier */ && !!symbol.exports[expr.text]; + } + function enumHasLiteralMembers(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (!isLiteralEnumMember(symbol, member)) { + return false; + } + } + } + } + return true; + } + function createEnumLiteralType(symbol, baseType, text) { + var type = createType(256 /* EnumLiteral */); + type.symbol = symbol; + type.baseType = baseType; + type.text = text; + return type; + } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(128 /* Enum */); - type.symbol = symbol; - links.declaredType = type; + var enumType = links.declaredType = createType(16 /* Enum */); + enumType.symbol = symbol; + if (enumHasLiteralMembers(symbol)) { + var memberTypeList = []; + var memberTypes = ts.createMap(); + for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 224 /* EnumDeclaration */) { + computeEnumMemberValues(declaration); + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var memberSymbol = getSymbolOfNode(member); + var value = getEnumMemberValue(member); + if (!memberTypes[value]) { + var memberType = memberTypes[value] = createEnumLiteralType(memberSymbol, enumType, "" + value); + memberTypeList.push(memberType); + } + } + } + } + enumType.memberTypes = memberTypes; + if (memberTypeList.length > 1) { + enumType.flags |= 524288 /* Union */; + enumType.types = memberTypeList; + unionTypes[getTypeListId(memberTypeList)] = enumType; + } + } + } + return links.declaredType; + } + function getDeclaredTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.declaredType = enumType.flags & 524288 /* Union */ ? + enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : + enumType; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(512 /* TypeParameter */); + var type = createType(16384 /* TypeParameter */); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */).constraint) { type.constraint = noConstraintType; @@ -19514,11 +25083,14 @@ var ts; if (symbol.flags & 524288 /* TypeAlias */) { return getDeclaredTypeOfTypeAlias(symbol); } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } if (symbol.flags & 384 /* Enum */) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 262144 /* TypeParameter */) { - return getDeclaredTypeOfTypeParameter(symbol); + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); } if (symbol.flags & 8388608 /* Alias */) { return getDeclaredTypeOfAlias(symbol); @@ -19551,7 +25123,7 @@ var ts; case 135 /* UndefinedKeyword */: case 93 /* NullKeyword */: case 127 /* NeverKeyword */: - case 166 /* StringLiteralType */: + case 166 /* LiteralType */: return true; case 160 /* ArrayType */: return isIndependentType(node.elementType); @@ -19602,7 +25174,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -19612,7 +25184,7 @@ var ts; // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = {}; + var result = ts.createMap(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -19622,7 +25194,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!ts.hasProperty(symbols, s.name)) { + if (!symbols[s.name]) { symbols[s.name] = s; } } @@ -19639,19 +25211,27 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 4096 /* Reference */) { + if (type.flags & 131072 /* Reference */) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper = identityMapper; - var members = source.symbol.members; - var callSignatures = source.declaredCallSignatures; - var constructSignatures = source.declaredConstructSignatures; - var stringIndexInfo = source.declaredStringIndexInfo; - var numberIndexInfo = source.declaredNumberIndexInfo; - if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -19661,7 +25241,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (members === source.symbol.members) { + if (source.symbol && members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -19687,7 +25267,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -19697,20 +25277,20 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasStringLiterals = hasStringLiterals; + sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { @@ -19725,23 +25305,6 @@ var ts; } return result; } - function createTupleTypeMemberSymbols(memberTypes) { - var members = {}; - for (var i = 0; i < memberTypes.length; i++) { - var symbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); - symbol.type = memberTypes[i]; - members[i] = symbol; - } - return members; - } - function resolveTupleTypeMembers(type) { - var arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); - // Make the tuple type itself the 'this' type by including an extra type argument - var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); - var members = createTupleTypeMemberSymbols(type.elementTypes); - addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); - } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -19796,7 +25359,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature @@ -19822,7 +25385,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union @@ -19887,7 +25450,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 80896 /* ObjectType */) { + if (baseConstructorType.flags & 2588672 /* ObjectType */) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -19905,22 +25468,19 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 4096 /* Reference */) { + if (type.flags & 131072 /* Reference */) { resolveTypeReferenceMembers(type); } - else if (type.flags & (1024 /* Class */ | 2048 /* Interface */)) { + else if (type.flags & (32768 /* Class */ | 65536 /* Interface */)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 65536 /* Anonymous */) { + else if (type.flags & 2097152 /* Anonymous */) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 8192 /* Tuple */) { - resolveTupleTypeMembers(type); - } - else if (type.flags & 16384 /* Union */) { + else if (type.flags & 524288 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 32768 /* Intersection */) { + else if (type.flags & 1048576 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -19928,7 +25488,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; @@ -19936,13 +25496,11 @@ var ts; /** If the given type is an object type and that type has a property by the given name, * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } } } @@ -19955,7 +25513,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { break; } } @@ -19963,7 +25521,7 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 1572864 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } /** * The apparent type of a type parameter is the base constraint instantiated with the type parameter @@ -19972,7 +25530,7 @@ var ts; function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 512 /* TypeParameter */) { + while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -19985,19 +25543,19 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - if (type.flags & 512 /* TypeParameter */) { + if (type.flags & 16384 /* TypeParameter */) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 258 /* StringLike */) { + if (type.flags & 34 /* StringLike */) { type = globalStringType; } - else if (type.flags & 132 /* NumberLike */) { + else if (type.flags & 340 /* NumberLike */) { type = globalNumberType; } - else if (type.flags & 8 /* Boolean */) { + else if (type.flags & 136 /* BooleanLike */) { type = globalBooleanType; } - else if (type.flags & 16777216 /* ESSymbol */) { + else if (type.flags & 512 /* ESSymbol */) { type = getGlobalESSymbolType(); } return type; @@ -20006,14 +25564,14 @@ var ts; var types = containingType.types; var props; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 32768 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; + var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))) { + if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -20025,7 +25583,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384 /* Union */) { + else if (containingType.flags & 524288 /* Union */) { // A union type requires the property to be present in all constituent types return undefined; } @@ -20039,11 +25597,20 @@ var ts; } var propTypes = []; var declarations = []; + var commonType = undefined; + var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + hasCommonType = false; + } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 /* Property */ | @@ -20051,50 +25618,54 @@ var ts; 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; + result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = {}); - if (ts.hasProperty(properties, name)) { - return properties[name]; - } - var property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; + var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); + var property = properties[name]; + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; + } } return property; } - // Return the symbol for the property with the given name in the given type. Creates synthetic union properties when - // necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from - // Object and Function as appropriate. + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - if (ts.hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; - if (symbolIsValue(symbol)) { - return symbol; - } + var symbol = resolved.members[name]; + if (symbol && symbolIsValue(symbol)) { + return symbol; } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol = getPropertyOfObjectType(globalFunctionType, name); - if (symbol) { - return symbol; + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 49152 /* UnionOrIntersection */) { + if (type.flags & 1572864 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 130048 /* StructuredType */) { + if (type.flags & 4161536 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -20108,7 +25679,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 130048 /* StructuredType */) { + if (type.flags & 4161536 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -20137,13 +25708,13 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, /*subtypeReduction*/ true); } } return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 134217728 /* JavaScriptFile */) { + if (declaration.flags & 1048576 /* JavaScriptFile */) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -20173,7 +25744,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 134217728 /* JavaScriptFile */) { + if (node.flags & 1048576 /* JavaScriptFile */) { if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { return true; } @@ -20222,7 +25793,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasStringLiterals = false; + var hasLiteralTypes = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -20245,8 +25816,8 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166 /* StringLiteralType */) { - hasStringLiterals = true; + if (param.type && param.type.kind === 166 /* LiteralType */) { + hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -20274,6 +25845,9 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } + if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { + thisParameter = getContextualThisParameter(declaration); + } var classType = declaration.kind === 148 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -20284,7 +25858,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } @@ -20298,7 +25872,7 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 134217728 /* JavaScriptFile */) { + if (declaration.flags & 1048576 /* JavaScriptFile */) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -20374,7 +25948,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } else { type = getReturnTypeFromBody(signature.declaration); @@ -20398,7 +25972,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { + if (type.flags & 131072 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -20422,7 +25996,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 /* Constructor */ || signature.declaration.kind === 152 /* ConstructSignature */; - var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); + var type = createObjectType(2097152 /* Anonymous */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -20457,7 +26031,7 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64 /* Readonly */) !== 0, declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); } return undefined; } @@ -20466,7 +26040,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 33554432 /* ThisType */) && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -20498,24 +26072,27 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141 /* TypeParameter */).parent); } function getTypeListId(types) { + var result = ""; if (types) { - switch (types.length) { - case 1: - return "" + types[0].id; - case 2: - return types[0].id + "," + types[1].id; - default: - var result = ""; - for (var i = 0; i < types.length; i++) { - if (i > 0) { - result += ","; - } - result += types[i].id; - } - return result; + var length_3 = types.length; + var i = 0; + while (i < length_3) { + var startId = types[i].id; + var count = 1; + while (i + count < length_3 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; } } - return ""; + return result; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type @@ -20529,20 +26106,29 @@ var ts; result |= type.flags; } } - return result & 14680064 /* PropagatingFlags */; + return result & 234881024 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - var flags = 4096 /* Reference */ | propagatedFlags; + var flags = 131072 /* Reference */ | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } + function cloneTypeReference(source) { + var type = createObjectType(source.flags, source.symbol); + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return type.target.typeParameters ? type.target.typeParameters.length : 0; + } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); @@ -20555,7 +26141,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -20575,7 +26161,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); var id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } @@ -20602,8 +26188,9 @@ var ts; case 194 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. - if (ts.isSupportedExpressionWithTypeArguments(node)) { - return node.expression; + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; } } return undefined; @@ -20612,7 +26199,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056 /* Type */) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -20641,15 +26228,15 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); - links.resolvedSymbol = symbol; - links.resolvedType = type; } else { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 155 /* TypeReference */ ? node.typeName : - ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : - undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 /* TypeReference */ + ? node.typeName + : ts.isEntityNameExpression(node.expression) + ? node.expression + : undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : @@ -20690,7 +26277,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 80896 /* ObjectType */)) { + if (!(type.flags & 2588672 /* ObjectType */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -20704,7 +26291,7 @@ var ts; return getGlobalSymbol(name, 107455 /* Value */, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793056 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793064 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -20718,8 +26305,8 @@ var ts; * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type */ function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056 /* Type */); + var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } /** @@ -20753,49 +26340,124 @@ var ts; } return links.resolvedType; } - function createTupleType(elementTypes) { - var id = getTypeListId(elementTypes); - return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); - } - function createNewTupleType(elementTypes) { - var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, /*excludeKinds*/ 0); - var type = createObjectType(8192 /* Tuple */ | propagatedFlags); - type.elementTypes = elementTypes; + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384 /* TypeParameter */); + typeParameters.push(typeParameter); + var property = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(262144 /* Tuple */ | 131072 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; return type; } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); } return links.resolvedType; } - function addTypeToSet(typeSet, type, typeSetKind) { - if (type.flags & typeSetKind) { - addTypesToSet(typeSet, type.types, typeSetKind); + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } } - else if (type.flags & (1 /* Any */ | 32 /* Undefined */ | 64 /* Null */)) { - if (type.flags & 1 /* Any */) - typeSet.containsAny = true; - if (type.flags & 32 /* Undefined */) + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 524288 /* Union */) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144 /* Nullable */) { + if (flags & 2048 /* Undefined */) typeSet.containsUndefined = true; - if (type.flags & 64 /* Null */) + if (flags & 4096 /* Null */) typeSet.containsNull = true; - if (!(type.flags & 2097152 /* ContainsWideningType */)) + if (!(flags & 33554432 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(flags & 8192 /* Never */)) { + if (flags & 2 /* String */) + typeSet.containsString = true; + if (flags & 4 /* Number */) + typeSet.containsNumber = true; + if (flags & 96 /* StringOrNumberLiteral */) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } } } // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToSet(typeSet, types, typeSetKind) { + function addTypesToUnion(typeSet, types) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToSet(typeSet, type, typeSetKind); + addTypeToUnion(typeSet, type); } } + function containsIdenticalType(types, type) { + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -20809,18 +26471,31 @@ var ts; while (i > 0) { i--; if (isSubtypeOfAny(types[i], types)) { - types.splice(i, 1); + ts.orderedRemoveItemAt(types, i); } } } - // We reduce the constituent type set to only include types that aren't subtypes of other types, unless - // the noSubtypeReduction flag is specified, in which case we perform a simple deduplication based on - // object identity. Subtype reduction is possible only when union types are known not to circularly - // reference themselves (as is the case with union types created by expression constructs such as array - // literals and the || and ?: operators). Named types can circularly reference themselves and therefore - // cannot be deduplicated during their declaration. For example, "type Item = string | (() => Item" is - // a named type that circularly references itself. - function getUnionType(types, noSubtypeReduction) { + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 /* StringLiteral */ && types.containsString || + t.flags & 64 /* NumberLiteral */ && types.containsNumber || + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 16777216 /* FreshLiteral */ && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -20828,102 +26503,141 @@ var ts; return types[0]; } var typeSet = []; - addTypesToSet(typeSet, types, 16384 /* Union */); + addTypesToUnion(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } - if (!noSubtypeReduction) { + if (subtypeReduction) { removeSubtypes(typeSet); } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - else if (typeSet.length === 1) { - return typeSet[0]; + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; } - var id = getTypeListId(typeSet); + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); - type = unionTypes[id] = createObjectType(16384 /* Union */ | propagatedFlags); - type.types = typeSet; + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); + type = unionTypes[id] = createObjectType(524288 /* Union */ | propagatedFlags); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node) { + function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); } return links.resolvedType; } + function addTypeToIntersection(typeSet, type) { + if (type.flags & 1048576 /* Intersection */) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; + addTypeToIntersection(typeSet, type); + } + } // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToSet(typeSet, types, 32768 /* Intersection */); + addTypesToIntersection(typeSet, types); if (typeSet.containsAny) { return anyType; } - if (strictNullChecks) { - if (typeSet.containsNull) - typeSet.push(nullType); - if (typeSet.containsUndefined) - typeSet.push(undefinedType); - } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); - type = intersectionTypes[id] = createObjectType(32768 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); + type = intersectionTypes[id] = createObjectType(1048576 /* Intersection */ | propagatedFlags); type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node) { + function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { var links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers - links.resolvedType = createObjectType(65536 /* Anonymous */, node.symbol); + var type = createObjectType(2097152 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + links.resolvedType = type; } return links.resolvedType; } - function getStringLiteralTypeForText(text) { - if (ts.hasProperty(stringLiteralTypes, text)) { - return stringLiteralTypes[text]; - } - var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */); + function createLiteralType(flags, text) { + var type = createType(flags); type.text = text; return type; } - function getTypeFromStringLiteralTypeNode(node) { + function getFreshTypeOfLiteralType(type) { + if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 16777216 /* FreshLiteral */)) { + if (!type.freshType) { + var freshType = createLiteralType(type.flags | 16777216 /* FreshLiteral */, type.text); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? type.regularType : type; + } + function getLiteralTypeForText(flags, text) { + var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; + return map[text] || (map[text] = createLiteralType(flags, text)); + } + function getTypeFromLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); } return links.resolvedType; } @@ -20938,7 +26652,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); + var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -20947,8 +26661,8 @@ var ts; var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 222 /* InterfaceDeclaration */)) { - if (!(container.flags & 32 /* Static */) && - (container.kind !== 148 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { + if (!(ts.getModifierFlags(container) & 32 /* Static */) && + (container.kind !== 148 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -20962,7 +26676,10 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNodeNoAlias(type) { + return getTypeFromTypeNode(type, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined); + } + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117 /* AnyKeyword */: case 258 /* JSDocAllType */: @@ -20984,11 +26701,19 @@ var ts; return nullType; case 127 /* NeverKeyword */: return neverType; + case 283 /* JSDocNullKeyword */: + return nullType; + case 284 /* JSDocUndefinedKeyword */: + return undefinedType; + case 285 /* JSDocNeverKeyword */: + return neverType; case 165 /* ThisType */: case 97 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 166 /* StringLiteralType */: - return getTypeFromStringLiteralTypeNode(node); + case 166 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 282 /* JSDocLiteralType */: + return getTypeFromLiteralTypeNode(node.literal); case 155 /* TypeReference */: case 267 /* JSDocTypeReference */: return getTypeFromTypeReference(node); @@ -21005,9 +26730,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162 /* UnionType */: case 261 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node); + return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); case 163 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node); + return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); case 164 /* ParenthesizedType */: case 263 /* JSDocNullableType */: case 264 /* JSDocNonNullableType */: @@ -21015,13 +26740,14 @@ var ts; case 272 /* JSDocThisType */: case 268 /* JSDocOptionalType */: return getTypeFromTypeNode(node.type); + case 265 /* JSDocRecordType */: + return getTypeFromTypeNode(node.literal); case 156 /* FunctionType */: case 157 /* ConstructorType */: case 159 /* TypeLiteral */: case 281 /* JSDocTypeLiteral */: case 269 /* JSDocFunctionType */: - case 265 /* JSDocRecordType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 69 /* Identifier */: @@ -21069,6 +26795,7 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; + mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -21077,7 +26804,7 @@ var ts; function getInferenceMapper(context) { if (!context.mapper) { var mapper = function (t) { - var typeParameters = context.typeParameters; + var typeParameters = context.signature.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (t === typeParameters[i]) { context.inferences[i].isFixed = true; @@ -21086,7 +26813,7 @@ var ts; } return t; }; - mapper.mappedTypes = context.typeParameters; + mapper.mappedTypes = context.signature.typeParameters; mapper.context = context; context.mapper = mapper; } @@ -21101,7 +26828,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(512 /* TypeParameter */); + var result = createType(16384 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -21139,7 +26866,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -21176,9 +26903,11 @@ var ts; mapper.instantiations = []; } // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - var result = createObjectType(65536 /* Anonymous */ | 131072 /* Instantiated */, type.symbol); + var result = createObjectType(2097152 /* Anonymous */ | 4194304 /* Instantiated */, type.symbol); result.target = type; result.mapper = mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -21233,10 +26962,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 512 /* TypeParameter */) { + if (type.flags & 16384 /* TypeParameter */) { return mapper(type); } - if (type.flags & 65536 /* Anonymous */) { + if (type.flags & 2097152 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. We skip instantiation @@ -21245,20 +26974,17 @@ var ts; // instantiation. return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.flags & 131072 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 4194304 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 4096 /* Reference */) { + if (type.flags & 131072 /* Reference */) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 8192 /* Tuple */) { - return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); + if (type.flags & 524288 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); } - if (type.flags & 16384 /* Union */) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), /*noSubtypeReduction*/ true); - } - if (type.flags & 32768 /* Intersection */) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); + if (type.flags & 1048576 /* Intersection */) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); } } return type; @@ -21303,10 +27029,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(65536 /* Anonymous */, type.symbol); + var result = createObjectType(2097152 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -21318,26 +27044,32 @@ var ts; } // TYPE CHECKING function isTypeIdenticalTo(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, identityRelation); } function compareTypesIdentical(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; } function compareTypesAssignable(source, target) { - return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } function isTypeSubtypeOf(source, target) { - return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, subtypeRelation); } function isTypeAssignableTo(source, target) { - return checkTypeAssignableTo(source, target, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, assignableRelation); + } + // A type S is considered to be an instance of a type T if S and T are the same type or if S is a + // subtype of T but not structurally identical to T. This specifically means that two distinct but + // structurally identical types (such as two classes) are not considered instances of each other. + function isTypeInstanceOf(source, target) { + return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); } /** * This is *not* a bi-directional relationship. * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. */ function isTypeComparableTo(source, target) { - return checkTypeComparableTo(source, target, /*errorNode*/ undefined); + return isTypeRelatedTo(source, target, comparableRelation); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -21463,8 +27195,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) - || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); } return false; @@ -21493,6 +27225,94 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + var id = source.id + "," + target.id; + if (enumRelation[id] !== undefined) { + return enumRelation[id]; + } + if (source.symbol.name !== target.symbol.name || + !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || + (source.flags & 524288 /* Union */) !== (target.flags & 524288 /* Union */)) { + return enumRelation[id] = false; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + } + return enumRelation[id] = false; + } + } + } + return enumRelation[id] = true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + if (target.flags & 8192 /* Never */) + return false; + if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) + return true; + if (source.flags & 34 /* StringLike */ && target.flags & 2 /* String */) + return true; + if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) + return true; + if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) + return true; + if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) + return true; + if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) + return true; + if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) + return true; + if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1 /* Any */) + return true; + if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) + return true; + if (source.flags & 256 /* EnumLiteral */ && + target.flags & 256 /* EnumLiteral */ && + source.text === target.text && + isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { + return true; + } + if (source.flags & 256 /* EnumLiteral */ && + target.flags & 16 /* Enum */ && + isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { + return true; + } + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation[id]; + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 4177920 /* StructuredOrTypeParameter */ || target.flags & 4177920 /* StructuredOrTypeParameter */) { + return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + } + return false; + } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -21541,49 +27361,37 @@ var ts; } reportError(message, sourceType, targetType); } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType() === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or // Ternary.False if they are not related. function isRelatedTo(source, target, reportErrors, headMessage) { var result; + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + target = target.regularType; + } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) return -1 /* True */; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (!(target.flags & 134217728 /* Never */)) { - if (target.flags & 1 /* Any */ || source.flags & 134217728 /* Never */) - return -1 /* True */; - if (source.flags & 32 /* Undefined */) { - if (!strictNullChecks || target.flags & (32 /* Undefined */ | 16 /* Void */)) - return -1 /* True */; - } - if (source.flags & 64 /* Null */) { - if (!strictNullChecks || target.flags & 64 /* Null */) - return -1 /* True */; - } - if (source.flags & 128 /* Enum */ && target === numberType) - return -1 /* True */; - if (source.flags & 128 /* Enum */ && target.flags & 128 /* Enum */) { - if (result = enumRelatedTo(source, target, reportErrors)) { - return result; - } - } - if (source.flags & 256 /* StringLiteral */ && target === stringType) - return -1 /* True */; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) - return -1 /* True */; - if (source === numberType && target.flags & 128 /* Enum */) - return -1 /* True */; - } - if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { - return -1 /* True */; - } - } - if (source.flags & 1048576 /* FreshObjectLiteral */) { + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + if (source.flags & 8388608 /* ObjectLiteral */ && source.flags & 16777216 /* FreshLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -21594,24 +27402,24 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 49152 /* UnionOrIntersection */) { + if (target.flags & 1572864 /* UnionOrIntersection */) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; // Note that these checks are specifically ordered to produce correct results. - if (source.flags & 16384 /* Union */) { + if (source.flags & 524288 /* Union */) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors); + result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); } else { - result = eachTypeRelatedToType(source, target, reportErrors); + result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); } if (result) { return result; } } - else if (target.flags & 32768 /* Intersection */) { + else if (target.flags & 1048576 /* Intersection */) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; @@ -21621,7 +27429,7 @@ var ts; // It is necessary to try these "some" checks on both sides because there may be nested "each" checks // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). - if (source.flags & 32768 /* Intersection */) { + if (source.flags & 1048576 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -21639,13 +27447,13 @@ var ts; return result; } } - if (target.flags & 16384 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726 /* Primitive */))) { + if (target.flags & 524288 /* Union */) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { return result; } } } - if (source.flags & 512 /* TypeParameter */) { + if (source.flags & 16384 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1 /* Any */) { constraint = emptyObjectType; @@ -21660,7 +27468,7 @@ var ts; } } else { - if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; @@ -21672,9 +27480,9 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentSource.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { + if (apparentSource.flags & (2588672 /* ObjectType */ | 1048576 /* Intersection */) && target.flags & 2588672 /* ObjectType */) { // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726 /* Primitive */); + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190 /* Primitive */); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -21682,14 +27490,20 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 2588672 /* ObjectType */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } reportRelationError(headMessage, source, target); } return 0 /* False */; } function isIdenticalTo(source, target) { var result; - if (source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */) { - if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { + if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; @@ -21697,8 +27511,8 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || - source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ || + source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { if (result &= eachTypeRelatedToSomeType(target, source, /*reportErrors*/ false)) { return result; @@ -21712,7 +27526,7 @@ var ts; // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type, name) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -21721,7 +27535,7 @@ var ts; return true; } } - else if (type.flags & 49152 /* UnionOrIntersection */) { + else if (type.flags & 1572864 /* UnionOrIntersection */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -21739,7 +27553,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 80896 /* ObjectType */)) { + if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -21772,18 +27586,10 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - var len = targetTypes.length; - // The null and undefined types are guaranteed to be at the end of the constituent type list. In order - // to produce the best possible errors we first check the nullable types, such that the last type we - // check and report errors from is a non-nullable type if one is present. - while (len >= 2 && targetTypes[len - 1].flags & 96 /* Nullable */) { - var related = isRelatedTo(source, targetTypes[len - 1], /*reportErrors*/ false); - if (related) { - return related; - } - len--; + if (target.flags & 524288 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; } - // Now check the non-nullable types and report errors on the last one. + var len = targetTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -21807,18 +27613,10 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - var len = sourceTypes.length; - // The null and undefined types are guaranteed to be at the end of the constituent type list. In order - // to produce the best possible errors we first check the nullable types, such that the last type we - // check and report errors from is a non-nullable type if one is present. - while (len >= 2 && sourceTypes[len - 1].flags & 96 /* Nullable */) { - var related = isRelatedTo(sourceTypes[len - 1], target, /*reportErrors*/ false); - if (related) { - return related; - } - len--; + if (source.flags & 524288 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; } - // Now check the non-nullable types and report errors on the last one. + var len = sourceTypes.length; for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -21898,7 +27696,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; @@ -21931,7 +27729,7 @@ var ts; var maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyMap(maybeCache, destinationCache); + ts.copyProperties(maybeCache, destinationCache); } else { // A false result goes straight into global cache (when something is false under assumptions it @@ -21946,9 +27744,9 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); - for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { - var targetProp = properties_1[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -21960,8 +27758,8 @@ var ts; } } else if (!(targetProp.flags & 134217728 /* Prototype */)) { - var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -22019,7 +27817,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */)) { + if (!(source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -22140,7 +27938,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */))) { + if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 8190 /* Primitive */))) { // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } @@ -22178,33 +27976,12 @@ var ts; } return 0 /* False */; } - function enumRelatedTo(source, target, reportErrors) { - if (source.symbol.name !== target.symbol.name || - source.symbol.flags & 128 /* ConstEnum */ || - target.symbol.flags & 128 /* ConstEnum */) { - return 0 /* False */; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8 /* EnumMember */) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); - } - return 0 /* False */; - } - } - } - return -1 /* True */; - } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = sourceSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); - var targetAccessibility = targetSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; // A public, protected and private signature is assignable to a private signature. if (targetAccessibility === 8 /* Private */) { return true; @@ -22225,11 +28002,11 @@ var ts; } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { - if (type.flags & 65536 /* Anonymous */) { + if (type.flags & 2097152 /* Anonymous */) { var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && declaration.flags & 128 /* Abstract */) { + if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { return true; } } @@ -22243,12 +28020,12 @@ var ts; // some level beyond that. function isDeeplyNestedGeneric(type, stack, depth) { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) - if (type.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && depth >= 5) { + if (type.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && t.symbol === symbol) { + if (t.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -22267,8 +28044,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 /* Private */ | 16 /* Protected */); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 /* Private */ | 16 /* Protected */); + var sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -22298,8 +28075,10 @@ var ts; // A source signature partially matches a target signature if the target signature has no fewer required // parameters and no more overall parameters than the source signature (where a signature with a rest // parameter is always considered to have more overall parameters than one without). - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || - source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -22360,31 +28139,43 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } - function getCombinedFlagsOfTypes(types) { - var flags = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - flags |= t.flags; + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } } - return flags; + return true; + } + // When the candidate types are all literal types with the same base type, the common + // supertype is a union of those literal types. Otherwise, the common supertype is the + // first type that is a supertype of each of the other types. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } function getCommonSupertype(types) { if (!strictNullChecks) { - return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); if (!primaryTypes.length) { - return getUnionType(types); + return getUnionType(types, /*subtypeReduction*/ true); } - var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96 /* Nullable */); + var supertype = getSupertypeOrUnion(primaryTypes); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -22420,50 +28211,89 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 4096 /* Reference */ && type.target === globalArrayType; + return type.flags & 131072 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return type.flags & 4096 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 96 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 131072 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralUnionType(type) { - return type.flags & 256 /* StringLiteral */ ? true : - type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : - false; + function isUnitType(type) { + return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 /* Boolean */ ? true : + type.flags & 524288 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* EnumLiteral */ ? type.baseType : + type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type; + } + function getWidenedLiteralType(type) { + return type.flags & 32 /* StringLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* EnumLiteral */ ? type.baseType : + type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type; } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(type.flags & 8192 /* Tuple */); + return !!(type.flags & 131072 /* Reference */ && type.target.flags & 262144 /* Tuple */); } - function getCombinedTypeFlags(type) { - return type.flags & 16384 /* Union */ ? getCombinedFlagsOfTypes(type.types) : type.flags; + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + result |= getFalsyFlags(t); + } + return result; } - function addTypeKind(type, kind) { - if ((getCombinedTypeFlags(type) & kind) === kind) { + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). + function getFalsyFlags(type) { + return type.flags & 524288 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : + type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : + type.flags & 7406 /* PossiblyFalsy */; + } + function includeFalsyTypes(type, flags) { + if ((getFalsyFlags(type) & flags) === flags) { return type; } var types = [type]; - if (kind & 2 /* String */) - types.push(stringType); - if (kind & 4 /* Number */) - types.push(numberType); - if (kind & 8 /* Boolean */) - types.push(booleanType); - if (kind & 16 /* Void */) + if (flags & 34 /* StringLike */) + types.push(emptyStringType); + if (flags & 340 /* NumberLike */) + types.push(zeroType); + if (flags & 136 /* BooleanLike */) + types.push(falseType); + if (flags & 1024 /* Void */) types.push(voidType); - if (kind & 32 /* Undefined */) + if (flags & 2048 /* Undefined */) types.push(undefinedType); - if (kind & 64 /* Null */) + if (flags & 4096 /* Null */) types.push(nullType); - return getUnionType(types); + return getUnionType(types, /*subtypeReduction*/ true); + } + function removeDefinitelyFalsyTypes(type) { + return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : + type; } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; @@ -22489,7 +28319,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = {}; + var members = ts.createMap(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -22505,7 +28335,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576 /* FreshObjectLiteral */)) { + if (!(type.flags & 8388608 /* ObjectLiteral */ && type.flags & 16777216 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -22515,7 +28345,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576 /* FreshObjectLiteral */; + regularNew.flags = resolved.flags & ~16777216 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -22529,24 +28359,21 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 96 /* Nullable */ ? type : getWidenedType(type); + return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { - if (type.flags & 96 /* Nullable */) { + if (type.flags & 100663296 /* RequiresWidening */) { + if (type.flags & 6144 /* Nullable */) { return anyType; } - if (type.flags & 524288 /* ObjectLiteral */) { + if (type.flags & 8388608 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.map(type.types, getWidenedConstituentType), /*noSubtypeReduction*/ true); + if (type.flags & 524288 /* Union */) { + return getUnionType(ts.map(type.types, getWidenedConstituentType)); } - if (isArrayType(type)) { - return createArrayType(getWidenedType(type.typeArguments[0])); - } - if (isTupleType(type)) { - return createTupleType(ts.map(type.elementTypes, getWidenedType)); + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); } } return type; @@ -22564,7 +28391,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -22572,22 +28399,19 @@ var ts; } } } - if (isArrayType(type)) { - return reportWideningErrorsInType(type.typeArguments[0]); - } - if (isTupleType(type)) { - for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 524288 /* ObjectLiteral */) { + if (type.flags & 8388608 /* ObjectLiteral */) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 2097152 /* ContainsWideningType */) { + if (t.flags & 33554432 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -22632,7 +28456,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -22659,29 +28483,49 @@ var ts; callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } } - function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = ts.map(typeParameters, createTypeInferencesObject); + function createInferenceContext(signature, inferUnionTypes) { + var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); return { - typeParameters: typeParameters, + signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length) }; } function createTypeInferencesObject() { return { primary: undefined, secondary: undefined, + topLevel: true, isFixed: false }; } - function inferTypes(context, source, target) { + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeParameters(type) { + return !!(type.flags & 16384 /* TypeParameter */ || + type.flags & 131072 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeParameters) || + type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + type.flags & 1572864 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeParameters(type)); + } + function couldUnionOrIntersectionContainTypeParameters(type) { + if (type.couldContainTypeParameters === undefined) { + type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + } + return type.couldContainTypeParameters; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 1572864 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypes(context, originalSource, originalTarget) { + var typeParameters = context.signature.typeParameters; var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; - inferFromTypes(source, target); + var visited = ts.createMap(); + inferFromTypes(originalSource, originalTarget); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { if (source === sourceStack[i] && target === targetStack[i]) { @@ -22691,20 +28535,39 @@ var ts; return false; } function inferFromTypes(source, target) { - if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || - source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { - // Source and target are both unions or both intersections. First, find each - // target constituent type that has an identically matching source constituent - // type, and for each such target constituent type infer from the type to itself. - // When inferring from a type to itself we effectively find all type parameter - // occurrences within that type and infer themselves as their type arguments. + if (!couldContainTypeParameters(target)) { + return; + } + if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. var matchingTypes = void 0; - for (var _i = 0, _a = target.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (typeIdenticalToSomeType(t, source.types)) { + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } + else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } } // Next, to improve the quality of inferences, reduce the source and target types by // removing the identically matched constituents. For example, when inferring from @@ -22714,17 +28577,16 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 512 /* TypeParameter */) { + if (target.flags & 16384 /* TypeParameter */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round // of inference. - if (source.flags & 8388608 /* ContainsAnyFunctionType */) { + if (source.flags & 134217728 /* ContainsAnyFunctionType */) { return; } - var typeParameters = context.typeParameters; for (var i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { var inferences = context.inferences[i]; @@ -22741,12 +28603,15 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } + if (!isTypeParameterAtTopLevel(originalTarget, target)) { + inferences.topLevel = false; + } } return; } } } - else if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + else if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; @@ -22755,22 +28620,14 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (source.flags & 8192 /* Tuple */ && target.flags & 8192 /* Tuple */ && source.elementTypes.length === target.elementTypes.length) { - // If source and target are tuples of the same size, infer from element types - var sourceTypes = source.elementTypes; - var targetTypes = target.elementTypes; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 49152 /* UnionOrIntersection */) { + else if (target.flags & 1572864 /* UnionOrIntersection */) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; // First infer to each type in union or intersection that isn't a type parameter - for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { - var t = targetTypes_2[_b]; - if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { + for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { + var t = targetTypes_2[_d]; + if (t.flags & 16384 /* TypeParameter */ && ts.contains(typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -22787,21 +28644,17 @@ var ts; inferiority--; } } - else if (source.flags & 49152 /* UnionOrIntersection */) { + else if (source.flags & 1572864 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { - var sourceType = sourceTypes_3[_c]; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 /* ObjectType */ && (target.flags & 4096 /* Reference */ && target.typeArguments || - target.flags & 8192 /* Tuple */ || - target.flags & 65536 /* Anonymous */ && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { - // If source is an object type, and target is a type reference with type arguments, a tuple type, - // the type of a method, or a type literal, infer from members + if (source.flags & 2588672 /* ObjectType */) { if (isInProcess(source, target)) { return; } @@ -22809,7 +28662,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -22830,8 +28683,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -22848,8 +28701,11 @@ var ts; inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } + function inferFromParameterTypes(source, target) { + return inferFromTypes(source, target); + } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromParameterTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -22878,8 +28734,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -22898,20 +28754,33 @@ var ts; reducedTypes.push(t); } } - return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + return type.flags & 524288 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */); + } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; var inferenceSucceeded; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { + // We widen inferred literal types if + // all inferences were made to top-level ocurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var signature = context.signature; + var widenLiteralTypes = context.inferences[index].topLevel && + !hasPrimitiveConstraint(signature.typeParameters[index]) && + (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); + var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; // Infer widened union or supertype, or the unknown type for no common supertype - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -22926,7 +28795,7 @@ var ts; context.inferredTypes[index] = inferredType; // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -22993,10 +28862,6 @@ var ts; } return undefined; } - function isNullOrUndefinedLiteral(node) { - return node.kind === 93 /* NullKeyword */ || - node.kind === 69 /* Identifier */ && getResolvedSymbol(node) === undefinedSymbol; - } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69 /* Identifier */: @@ -23008,16 +28873,17 @@ var ts; return undefined; } function isMatchingReference(source, target) { - if (source.kind === target.kind) { - switch (source.kind) { - case 69 /* Identifier */: - return getResolvedSymbol(source) === getResolvedSymbol(target); - case 97 /* ThisKeyword */: - return true; - case 172 /* PropertyAccessExpression */: - return source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } + switch (source.kind) { + case 69 /* Identifier */: + return target.kind === 69 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 218 /* VariableDeclaration */ || target.kind === 169 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 97 /* ThisKeyword */: + return target.kind === 97 /* ThisKeyword */; + case 172 /* PropertyAccessExpression */: + return target.kind === 172 /* PropertyAccessExpression */ && + source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); } return false; } @@ -23030,6 +28896,48 @@ var ts; } return false; } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 172 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 69 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 172 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.text); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 524288 /* Union */) { + var prop = getPropertyOfType(type, name); + if (!prop) { + // The type may be a union that includes nullable or primitive types. If filtering + // those out produces a different type, get the property from that type instead. + // Effectively, we're checking if this *could* be a discriminant property once nullable + // and primitive types are removed by other type guards. + var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); + if (filteredType !== type && filteredType.flags & 524288 /* Union */) { + prop = getPropertyOfType(filteredType, name); + } + } + if (prop && prop.flags & 268435456 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = !prop.hasCommonType && + isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -23056,7 +28964,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 16384 /* Union */)) { + if (!(source.flags & 524288 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -23071,70 +28979,84 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType && declaredType.flags & 16384 /* Union */) { - var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedTypes.length) { - return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); + if (declaredType !== assignedType) { + if (assignedType.flags & 8192 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192 /* Never */)) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); + } function getTypeFacts(type) { var flags = type.flags; - if (flags & 258 /* StringLike */) { + if (flags & 2 /* String */) { return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } - if (flags & 132 /* NumberLike */) { + if (flags & 32 /* StringLiteral */) { + return strictNullChecks ? + type.text === "" ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + type.text === "" ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; + } + if (flags & (4 /* Number */ | 16 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } + if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { + var isZero = type.text === "0"; + return strictNullChecks ? + isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : + isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + } if (flags & 8 /* Boolean */) { return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; } - if (flags & 80896 /* ObjectType */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + if (flags & 136 /* BooleanLike */) { + return strictNullChecks ? + type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & (16 /* Void */ | 32 /* Undefined */)) { + if (flags & 2588672 /* ObjectType */) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : + strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + } + if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 64 /* Null */) { + if (flags & 4096 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 16777216 /* ESSymbol */) { + if (flags & 512 /* ESSymbol */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 512 /* TypeParameter */) { + if (flags & 16384 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(type); - return constraint ? getTypeFacts(constraint) : 4194303 /* All */; + return getTypeFacts(constraint || emptyObjectType); } - if (flags & 32768 /* Intersection */) { - return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0 /* None */); + if (flags & 1572864 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); } - return 4194303 /* All */; + return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (!(type.flags & 16384 /* Union */)) { - return getTypeFacts(type) & include ? type : neverType; - } - var firstType; - var types; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (getTypeFacts(t) & include) { - if (!firstType) { - firstType = t; - } - else { - if (!types) { - types = [firstType]; - } - types.push(t); - } - } - } - return firstType ? types ? getUnionType(types, /*noSubtypeReduction*/ true) : firstType : neverType; + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -23231,26 +29153,31 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getReferenceFromExpression(node) { + function getInitialOrAssignedType(node) { + return node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node); + } + function getReferenceCandidate(node) { switch (node.kind) { case 178 /* ParenthesizedExpression */: - return getReferenceFromExpression(node.expression); + return getReferenceCandidate(node.expression); case 187 /* BinaryExpression */: switch (node.operatorToken.kind) { case 56 /* EqualsToken */: - return getReferenceFromExpression(node.left); + return getReferenceCandidate(node.left); case 24 /* CommaToken */: - return getReferenceFromExpression(node.right); + return getReferenceCandidate(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249 /* CaseClause */) { - var expr = clause.expression; - return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; } - return undefined; + return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); @@ -23258,28 +29185,58 @@ var ts; // If all case clauses specify expressions that have unit types, we return an array // of those unit types. Otherwise we return an empty array. var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; + links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 524288 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 524288 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 524288 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { + return true; + } + return containsType(target.types, source); } function filterType(type, f) { - return type.flags & 16384 /* Union */ ? - getUnionType(ts.filter(type.types, f)) : - f(type) ? type : neverType; + if (type.flags & 524288 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32 /* Undefined */); + var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; - var result = getTypeAtFlowNode(reference.flowNode); + var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */) === neverType) { + if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { return declaredType; } return result; @@ -23321,7 +29278,7 @@ var ts; else if (flow.flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && includeOuterFunctions) { + if (container && container !== flowContainer && reference.kind !== 172 /* PropertyAccessExpression */) { flow = container.flowNode; continue; } @@ -23346,19 +29303,10 @@ var ts; var node = flow.node; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. - if ((node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) && - reference.kind === 69 /* Identifier */ && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { - return declaredType.flags & 16384 /* Union */ ? - getAssignmentReducedType(declaredType, getInitialType(node)) : - declaredType; - } - // If the node is not a variable declaration or binding element, it is an identifier - // or a dotted name that is the target of an assignment. If we have a match, reduce - // the declared type by the assigned type. if (isMatchingReference(reference, node)) { - return declaredType.flags & 16384 /* Union */ ? - getAssignmentReducedType(declaredType, getAssignedType(node)) : + var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; + return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this @@ -23372,32 +29320,44 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - if (type !== neverType) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (!(type.flags & 8192 /* Never */)) { // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the nothing type, then - // we take the type guard as an indication that control could reach here in a - // manner not understood by the control flow analyzer (e.g. a function argument - // has an invalid type, or a nested function has possibly made an assignment to a - // captured variable). We proceed by reverting to the declared type and then - // narrow that. + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { - type = narrowType(declaredType, flow.expression, assumeTrue); + if (type.flags & 8192 /* Never */ && isIncomplete(flowType)) { + type = silentNeverType; } } - return type; + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtSwitchClause(flow) { - var type = getTypeAtFlowNode(flow.antecedent); - return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the // reference is known to always be assigned (i.e. when declared and initial types // are the same), there is no reason to process more antecedents since the only @@ -23408,14 +29368,23 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } } - return getUnionType(antecedentTypes); + return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at // this flow loop junction, return the cached type. var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); if (!key) { key = getFlowCacheKey(reference); } @@ -23423,25 +29392,31 @@ var ts; return cache[key]; } // If this flow loop junction and reference are already being processed, return - // the union of the types computed for each branch so far. We should never see - // an empty array here because the first antecedent of a loop junction is always - // the non-looping control flow path that leads to the top. + // the union of the types computed for each branch so far, marked as incomplete. + // We should never see an empty array here because the first antecedent of a loop + // junction is always the non-looping control flow path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return getUnionType(flowLoopTypes[i]); + return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze // each antecedent code path. var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var type = getTypeAtFlowNode(antecedent); + var flowType = getTypeAtFlowNode(antecedent); flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. @@ -23451,6 +29426,12 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } // If the type at a particular antecedent path is the declared type there is no // reason to process more antecedents since the only possible outcome is subtypes // that will be removed in the final union type anyway. @@ -23458,10 +29439,37 @@ var ts; break; } } - return cache[key] = getUnionType(antecedentTypes); + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + return cache[key] = result; + } + function isMatchingReferenceDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && + declaredType.flags & 524288 /* Union */ && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(declaredType, expr.name.text); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */) : type; + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -23471,26 +29479,29 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - var left = expr.left; - var operator = expr.operatorToken.kind; - var right = expr.right; - if (isNullOrUndefinedLiteral(right)) { - return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 182 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (isNullOrUndefinedLiteral(left)) { - return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + if (right_1.kind === 182 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } - if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } - if (left.kind === 172 /* PropertyAccessExpression */) { - return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + if (isMatchingReferenceDiscriminant(left_1)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (right.kind === 172 /* PropertyAccessExpression */) { - return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); + if (isMatchingReferenceDiscriminant(right_1)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; } break; case 91 /* InstanceOfKeyword */: @@ -23500,25 +29511,42 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { + var valueType = checkExpression(value); + if (valueType.flags & 6144 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : + value.kind === 93 /* NullKeyword */ ? + assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : + assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 2589191 /* NotUnionOrUnit */) { return type; } - var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; - var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - literal.kind === 93 /* NullKeyword */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; - return getTypeWithFacts(type, facts); + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands - var target = getReferenceFromExpression(typeOfExpr.expression); + var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. @@ -23530,72 +29558,38 @@ var ts; if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 16384 /* Union */)) { + if (assumeTrue && !(type.flags & 524288 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primtive type. For example, type 'any' can be narrowed + // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = ts.getProperty(typeofTypesByName, literal.text); + var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : - ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; + typeofEQFacts[literal.text] || 64 /* TypeofEQHostObject */ : + typeofNEFacts[literal.text] || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } - function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with property access as target - if (!isMatchingReference(reference, propAccess.expression)) { - return type; - } - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } - var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); - if (!isStringLiteralUnionType(discriminantType)) { - return type; - } - if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } - if (assumeTrue) { - return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); - } - if (discriminantType.flags & 256 /* StringLiteral */) { - return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); - } - return type; - } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - // We have switch statement with property access expression - if (!isMatchingReference(reference, switchStatement.expression.expression)) { - return type; - } - var propName = switchStatement.expression.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { - return type; - } + // We only narrow if all case expressions specify values with unit types var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); - var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; - var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; - var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); - return caseType ? getUnionType([caseType, defaultType]) : defaultType; + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left); + var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. @@ -23604,10 +29598,6 @@ var ts; } return type; } - // We never narrow type any in an instanceof guard - if (isTypeAny(type)) { - return type; - } // Check that right operand is a function type with a prototype property var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { @@ -23622,13 +29612,17 @@ var ts; targetType = prototypePropertyType; } } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (rightType.flags & 2048 /* Interface */) { + if (rightType.flags & 65536 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 65536 /* Anonymous */) { + else if (rightType.flags & 2097152 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -23642,28 +29636,29 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return type.flags & 16384 /* Union */ ? - getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : - type; + return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); } - // If the current type is a union type, remove all constituents that aren't assignable to + // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 16384 /* Union */) { - var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); - if (assignableConstituents.length) { - return getUnionType(assignableConstituents); + if (type.flags & 524288 /* Union */) { + var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (!(assignableType.flags & 8192 /* Never */)) { + return assignableType; } } - // If the candidate type is assignable to the target type, narrow to the candidate type. - // Otherwise, if the current type is assignable to the candidate, keep the current type. - // Otherwise, the types are completely unrelated, so narrow to the empty type. - var targetType = type.flags & 512 /* TypeParameter */ ? getApparentType(type) : type; - return isTypeAssignableTo(candidate, targetType) ? candidate : + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + var targetType = type.flags & 16384 /* TypeParameter */ ? getApparentType(type) : type; + return isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : - getIntersectionType([type, candidate]); + isTypeAssignableTo(candidate, targetType) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (type.flags & 1 /* Any */ || !hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -23671,6 +29666,10 @@ var ts; if (!predicate) { return type; } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -23739,7 +29738,7 @@ var ts; // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the - // hypotherical reference (control flow information is created and attached by the + // hypothetical reference (control flow information is created and attached by the // binder), we simply return the declared type of the symbol. return getTypeOfSymbol(symbol); } @@ -23752,20 +29751,49 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) || node.kind === 226 /* ModuleBlock */ || node.kind === 256 /* SourceFile */ || node.kind === 145 /* PropertyDeclaration */) { + if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 226 /* ModuleBlock */ || + node.kind === 256 /* SourceFile */ || + node.kind === 145 /* PropertyDeclaration */) { return node; } } } - function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { - var declarationContainer = getControlFlowContainer(declaration); - var container = getControlFlowContainer(reference); - while (container !== declarationContainer && - (container.kind === 179 /* FunctionExpression */ || container.kind === 180 /* ArrowFunction */) && - (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { - container = getControlFlowContainer(container); + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304 /* AssignmentsMarked */)) { + links.flags |= 4194304 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + while (true) { + node = node.parent; + if (!node) { + return false; + } + if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */) { + return true; + } + } + } + function markParameterAssignments(node) { + if (node.kind === 69 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); } - return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); @@ -23777,12 +29805,15 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 180 /* ArrowFunction */) { - if (languageVersion < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { + if (container.kind === 180 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } } - if (node.flags & 33554432 /* AwaitContext */) { + if (node.flags & 262144 /* AwaitContext */) { getNodeLinks(container).flags |= 8192 /* CaptureArguments */; } } @@ -23790,37 +29821,76 @@ var ts; markAliasSymbolAsReferenced(symbol); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - if (languageVersion === 2 /* ES6 */ - && localOrExportSymbol.flags & 32 /* Class */ - && localOrExportSymbol.valueDeclaration.kind === 221 /* ClassDeclaration */ - && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { - getNodeLinks(container).flags |= 524288 /* ClassWithBodyScopedClassBinding */; - getNodeLinks(node).flags |= 1048576 /* BodyScopedClassBinding */; - break; + if (localOrExportSymbol.flags & 32 /* Class */) { + var declaration_1 = localOrExportSymbol.valueDeclaration; + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (languageVersion === 2 /* ES6 */ + && declaration_1.kind === 221 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration_1)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration_1 && container.name !== node) { + getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration_1.kind === 192 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container !== undefined) { + if (container.parent === declaration_1) { + if (container.kind === 145 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); } - container = ts.getContainingClass(container); } } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node)) { + var declaration = localOrExportSymbol.valueDeclaration; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node) || !declaration) { return type; } - var declaration = localOrExportSymbol.valueDeclaration; - var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || !declaration || - ts.getRootDeclaration(declaration).kind === 142 /* Parameter */ || ts.isInAmbientContext(declaration) || - !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); - if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32 /* Undefined */) && getCombinedTypeFlags(flowType) & 32 /* Undefined */) { + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 142 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && + (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && + (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || + isOuterVariable || ts.isInAmbientContext(declaration); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. + if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -23999,7 +30069,7 @@ var ts; break; case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: - if (container.flags & 32 /* Static */) { + if (ts.getModifierFlags(container) & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -24028,10 +30098,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -24039,8 +30105,8 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - var type = container.flags & 32 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*includeOuterFunctions*/ true); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -24108,7 +30174,7 @@ var ts; } return unknownType; } - if ((container.flags & 32 /* Static */) || isCallExpression) { + if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } else { @@ -24171,8 +30237,8 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 147 /* MethodDeclaration */ && container.flags & 256 /* Async */) { - if (ts.isSuperPropertyOrElementAccess(node.parent) && ts.isAssignmentTarget(node.parent)) { + if (container.kind === 147 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } else { @@ -24229,7 +30295,7 @@ var ts; // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression if (ts.isClassLike(container.parent) || container.parent.kind === 171 /* ObjectLiteralExpression */) { - if (container.flags & 32 /* Static */) { + if (ts.getModifierFlags(container) & 32 /* Static */) { return container.kind === 147 /* MethodDeclaration */ || container.kind === 146 /* MethodSignature */ || container.kind === 149 /* GetAccessor */ || @@ -24249,11 +30315,11 @@ var ts; return false; } } - function getContextuallyTypedThisType(func) { + function getContextualThisParameter(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180 /* ArrowFunction */) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return getThisTypeOfSignature(contextualSignature); + return contextualSignature.thisParameter; } } return undefined; @@ -24269,14 +30335,14 @@ var ts; if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getTypeOfExpression(iife.arguments[i])); + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); } return createArrayType(getUnionType(restTypes)); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; links.resolvedSignature = anySignature; - var type = checkExpression(iife.arguments[indexOfParameter]); + var type = getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])); links.resolvedSignature = cached; return type; } @@ -24320,15 +30386,15 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_12 = declaration.propertyName || declaration.name; + var name_15 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_12)) { - var text = getTextOfPropertyName(name_12); + !ts.isBindingPattern(name_15)) { + var text = getTextOfPropertyName(name_15); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -24408,6 +30474,10 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + // Don't do this for special property assignments to avoid circularity + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { + return undefined; + } // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); @@ -24433,14 +30503,14 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union of the resulting // types is returned. function applyToContextualType(type, mapper) { - if (!(type.flags & 16384 /* Union */)) { + if (!(type.flags & 524288 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -24458,7 +30528,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 130048 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 4161536 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -24467,7 +30537,7 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 524288 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one @@ -24587,6 +30657,7 @@ var ts; case 187 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); case 253 /* PropertyAssignment */: + case 254 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); case 170 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); @@ -24641,13 +30712,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 16384 /* Union */)) { + if (!(type.flags & 524288 /* Union */)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -24734,7 +30805,7 @@ var ts; } } else { - var type = checkExpression(e, contextualMapper); + var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 191 /* SpreadElementExpression */; @@ -24743,7 +30814,7 @@ var ts; // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -24757,7 +30828,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.elementTypes[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { if (patternElement.kind !== 193 /* OmittedExpression */) { @@ -24772,7 +30843,9 @@ var ts; } } } - return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, /*subtypeReduction*/ true) : + strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); @@ -24780,11 +30853,14 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } function isNumericLiteralName(name) { // The intent of numeric names is that // - they are names with text in a numeric form, and that @@ -24815,7 +30891,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 34 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -24831,14 +30907,14 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = {}; + var propertiesTable = ts.createMap(); var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -24862,7 +30938,7 @@ var ts; } else { ts.Debug.assert(memberDecl.kind === 254 /* ShorthandPropertyAssignment */); - type = checkExpression(memberDecl.name, contextualMapper); + type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); @@ -24878,7 +30954,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -24925,7 +31001,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!ts.hasProperty(propertiesTable, prop.name)) { + if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -24937,8 +31013,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */; - result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -25005,10 +31081,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - // Maybe there's a string indexer? - var indexerType = getIndexTypeOfType(elementAttributesType, 0 /* String */); - if (indexerType) { - correspondingPropType = indexerType; + var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); + if (attributeType) { + correspondingPropType = attributeType; } else { // If there's no corresponding property with this name, error @@ -25099,7 +31174,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 16384 /* Union */)); + ts.Debug.assert(!(valueType.flags & 524288 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -25115,7 +31190,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature)); + return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -25124,9 +31199,9 @@ var ts; /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // JSX.ElementAttributesProperty [symbol] - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064 /* Type */); // JSX.ElementAttributesProperty [type] var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); // The properties of JSX.ElementAttributesProperty @@ -25157,17 +31232,17 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 16384 /* Union */) { + if (elemType.flags & 524288 /* Union */) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - })); + }), /*subtypeReduction*/ true); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type if (elemType.flags & 2 /* String */) { return anyType; } - else if (elemType.flags & 256 /* StringLiteral */) { + else if (elemType.flags & 32 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { @@ -25231,7 +31306,7 @@ var ts; // Props is of type 'any' or unknown return attributesType; } - else if (attributesType.flags & 16384 /* Union */) { + else if (attributesType.flags & 524288 /* Union */) { // Props cannot be a union type error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; @@ -25329,7 +31404,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = {}; + var nameTable = ts.createMap(); // Process this array in right-to-left order so we know which // attributes (mostly from spreads) are being overwritten and // thus should have their types ignored @@ -25352,7 +31427,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912 /* Optional */) && - nameTable[targetProperties[i].name] === undefined) { + !nameTable[targetProperties[i].name]) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -25371,8 +31446,11 @@ var ts; function getDeclarationKindFromSymbol(s) { return s.valueDeclaration ? s.valueDeclaration.kind : 145 /* PropertyDeclaration */; } - function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; + function getDeclarationModifierFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } /** * Check whether the requested property access is valid. @@ -25383,7 +31461,7 @@ var ts; * @param prop The symbol for the right hand side of the property access. */ function checkClassPropertyAccess(node, left, type, prop) { - var flags = getDeclarationFlagsFromSymbol(prop); + var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 172 /* PropertyAccessExpression */ || node.kind === 218 /* VariableDeclaration */ ? node.name : @@ -25412,7 +31490,7 @@ var ts; } } // Public properties are otherwise accessible. - if (!(flags & (8 /* Private */ | 16 /* Protected */))) { + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { return true; } // Property is known to be private or protected at this point @@ -25445,12 +31523,12 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 33554432 /* ThisType */) { + if (type.flags & 268435456 /* ThisType */) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } // TODO: why is the first part of this check here? - if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (32768 /* Class */ | 65536 /* Interface */) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -25459,9 +31537,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getCombinedTypeFlags(type) & 96 /* Nullable */; + var kind = getFalsyFlags(type) & 6144 /* Nullable */; if (kind) { - error(node, kind & 32 /* Undefined */ ? kind & 64 /* Null */ ? + error(node, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -25478,24 +31556,24 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); - if (isTypeAny(type)) { + if (isTypeAny(type) || type === silentNeverType) { return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 512 /* TypeParameter */ && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { // handle cases when type is Type parameter with invalid or any constraint return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); + reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); } return unknownType; } if (noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (prop.valueDeclaration.flags & 8 /* Private */)) { + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { if (prop.flags & 16777216 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -25513,10 +31591,24 @@ var ts; // accessor, or optional method. if (node.kind !== 172 /* PropertyAccessExpression */ || ts.isAssignmentTarget(node) || !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 16384 /* Union */)) { + !(prop.flags & 8192 /* Method */ && propType.flags & 524288 /* Union */)) { return propType; } - return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*includeOuterFunctions*/ false); + return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 524288 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 /* PropertyAccessExpression */ @@ -25596,8 +31688,8 @@ var ts; // Obtain base constraint such that we can bail out if the constraint is an unknown type var objectType = getApparentType(checkNonNullExpression(node.expression)); var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; - if (objectType === unknownType) { - return unknownType; + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; } var isConstEnum = isConstEnumObjectType(objectType); if (isConstEnum && @@ -25615,23 +31707,24 @@ var ts; // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. // See if we can index as a property. if (node.argumentExpression) { - var name_13 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_13 !== undefined) { - var prop = getPropertyOfType(objectType, name_13); + var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_16 !== undefined) { + var prop = getPropertyOfType(objectType, name_16); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_13, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_16, symbolToString(objectType.symbol)); return unknownType; } } } // Check for compatible indexer types. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { + var allowedNullableFlags = strictNullChecks ? 0 : 6144 /* Nullable */; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */ | allowedNullableFlags)) { // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -25695,7 +31788,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 16777216 /* ESSymbol */) === 0) { + if ((expressionType.flags & 512 /* ESSymbol */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -25755,13 +31848,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_9 = signature.declaration && signature.declaration.parent; + var parent_10 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_9 === lastParent) { + if (lastParent && parent_10 === lastParent) { index++; } else { - lastParent = parent_9; + lastParent = parent_10; index = cutoffIndex; } } @@ -25769,12 +31862,12 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_9; + lastParent = parent_10; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -25867,7 +31960,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 80896 /* ObjectType */) { + if (type.flags & 2588672 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -25878,7 +31971,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); + var context = createInferenceContext(signature, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context, instantiateType(source, contextualMapper), target); @@ -26001,9 +32094,7 @@ var ts; // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { - argType = arg.kind === 9 /* StringLiteral */ && !reportErrors - ? getStringLiteralTypeForText(arg.text) - : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -26188,10 +32279,10 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getStringLiteralTypeForText(element.name.text); + return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); case 140 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 16777216 /* ESSymbol */)) { + if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { return nameType; } else { @@ -26410,7 +32501,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -26437,7 +32528,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); } return candidate; } @@ -26462,14 +32553,14 @@ var ts; var candidate = void 0; var typeArgumentsAreValid = void 0; var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate.typeParameters, /*inferUnionTypes*/ false) + ? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false) : undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -26531,6 +32622,9 @@ var ts; return resolveUntypedCall(node); } var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } var apparentType = getApparentType(funcType); if (apparentType === unknownType) { // Another error has already been reported @@ -26542,16 +32636,10 @@ var ts; // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - // TS 1.0 spec: 4.12 - // If FuncExpr is of type Any, or of an object type that has no call or construct signatures - // but is a subtype of the Function interface, the call is an untyped function call. In an - // untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (isTypeAny(funcType) || - (isTypeAny(apparentType) && funcType.flags & 512 /* TypeParameter */) || - (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { @@ -26567,12 +32655,34 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); } return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have + // no common signatures. + if (funcType.flags & 524288 /* Union */) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -26581,6 +32691,9 @@ var ts; } } var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } // If expressionType's apparent type(section 3.8.1) is an object type with one or // more construct signatures, the expression is processed in the same manner as a // function call, but using the construct signatures as the initial set of candidate @@ -26596,7 +32709,7 @@ var ts; // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 128 /* Abstract */) { + if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -26643,19 +32756,31 @@ var ts; return true; } var declaration = signature.declaration; - var flags = declaration.flags; + var modifiers = ts.getModifierFlags(declaration); // Public constructor is accessible. - if (!(flags & (8 /* Private */ | 16 /* Protected */))) { + if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { return true; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - // A private or protected constructor can only be instantiated within it's own class + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { - if (flags & 8 /* Private */) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 /* Protected */ && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } + if (modifiers & 8 /* Private */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (flags & 16 /* Protected */) { + if (modifiers & 16 /* Protected */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -26670,11 +32795,12 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -26707,13 +32833,14 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); return resolveErrorCall(node); @@ -26742,10 +32869,10 @@ var ts; // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work // to correctly fill the candidatesOutArray. var cached = links.resolvedSignature; - if (cached && cached !== anySignature && !candidatesOutArray) { + if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = anySignature; + links.resolvedSignature = resolvingSignature; var result = resolveSignature(node, candidatesOutArray); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary @@ -26756,12 +32883,12 @@ var ts; function getResolvedOrAnySignature(node) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. - return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); } return links.inferredClassType; } @@ -26811,7 +32938,7 @@ var ts; return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { @@ -26830,7 +32957,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32 /* Undefined */); + return includeFalsyTypes(type, 2048 /* Undefined */); } } return type; @@ -26842,6 +32969,12 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (context.thisParameter) { + if (!signature.thisParameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); + } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -26859,7 +32992,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193 /* OmittedExpression */) { + if (!ts.isOmittedExpression(element)) { if (element.name.kind === 69 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -26979,20 +33112,8 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - // When yield/return statements are contextually typed we allow the return type to be a union type. - // Otherwise we require the yield/return expressions to have a best common supertype. - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); - if (!type) { - if (funcIsGenerator) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); - return createIterableIteratorType(unknownType); - } - else { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); - } - } + // Return a union of the return expression types. + type = getUnionType(types, /*subtypeReduction*/ true); if (funcIsGenerator) { type = createIterableIteratorType(type); } @@ -27000,6 +33121,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } + if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } var widenedType = getWidenedType(type); // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the @@ -27024,27 +33148,21 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - var expr = node.expression; - if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { + if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(expr.expression); - if (!(type.flags & 16384 /* Union */)) { - return false; - } - var propName = expr.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - if (!propType || !isStringLiteralUnionType(propType)) { + var type = checkExpression(node.expression); + if (!isLiteralType(type)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(propType, switchTypes); + return eachTypeContainedIn(type, switchTypes); } function functionHasImplicitReturn(func) { - if (!(func.flags & 32768 /* HasImplicitReturn */)) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); @@ -27069,7 +33187,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type === neverType) { + if (type.flags & 8192 /* Never */) { hasReturnOfTypeNever = true; } else if (!ts.contains(aggregatedTypes, type)) { @@ -27105,7 +33223,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -27113,8 +33231,8 @@ var ts; if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !functionHasImplicitReturn(func)) { return; } - var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; - if (returnType === neverType) { + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 8192 /* Never */) { error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -27234,7 +33352,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -27248,8 +33366,8 @@ var ts; // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return symbol.isReadonly || - symbol.flags & 4 /* Property */ && (getDeclarationFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || - symbol.flags & 3 /* Variable */ && (getDeclarationFlagsFromSymbol(symbol) & 2048 /* Const */) !== 0 || + symbol.flags & 4 /* Property */ && (getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || + symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || (symbol.flags & 8 /* EnumMember */) !== 0; } @@ -27334,7 +33452,7 @@ var ts; function checkAwaitExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 33554432 /* AwaitContext */)) { + if (!(node.flags & 262144 /* AwaitContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -27346,16 +33464,25 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { + return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); + } switch (node.operator) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: - if (maybeTypeOfKind(operandType, 16777216 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49 /* ExclamationToken */: - return booleanType; + var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); + return facts === 1048576 /* Truthy */ ? falseType : + facts === 2097152 /* Falsy */ ? trueType : + booleanType; case 41 /* PlusPlusToken */: case 42 /* MinusMinusToken */: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -27369,6 +33496,9 @@ var ts; } function checkPostfixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors @@ -27382,10 +33512,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 49152 /* UnionOrIntersection */) { + if (type.flags & 1572864 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -27400,20 +33530,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { var types = type.types; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 32768 /* Intersection */) { + if (type.flags & 1048576 /* Intersection */) { var types = type.types; - for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { - var t = types_12[_a]; + for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { + var t = types_16[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -27422,18 +33552,21 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (80896 /* ObjectType */ | 65536 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (2588672 /* ObjectType */ | 2097152 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.15.4 // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, // and the right operand to be of type Any or a subtype of the 'Function' interface type. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 16777726 /* Primitive */)) { + if (isTypeOfKind(leftType, 8190 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -27443,36 +33576,39 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var p = properties_3[_i]; + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var p = properties_4[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); } return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 /* PropertyAssignment */ || property.kind === 254 /* ShorthandPropertyAssignment */) { - var name_14 = property.name; - if (name_14.kind === 140 /* ComputedPropertyName */) { - checkComputedPropertyName(name_14); + var name_17 = property.name; + if (name_17.kind === 140 /* ComputedPropertyName */) { + checkComputedPropertyName(name_17); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_17)) { return undefined; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_17); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -27488,7 +33624,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_14)); + error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); } } else { @@ -27521,8 +33657,11 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -27554,7 +33693,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32 /* Undefined */)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -27583,8 +33722,76 @@ var ts; } return sourceType; } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 69 /* Identifier */: + case 9 /* StringLiteral */: + case 10 /* RegularExpressionLiteral */: + case 176 /* TaggedTemplateExpression */: + case 189 /* TemplateExpression */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + case 93 /* NullKeyword */: + case 135 /* UndefinedKeyword */: + case 179 /* FunctionExpression */: + case 192 /* ClassExpression */: + case 180 /* ArrowFunction */: + case 170 /* ArrayLiteralExpression */: + case 171 /* ObjectLiteralExpression */: + case 182 /* TypeOfExpression */: + case 196 /* NonNullExpression */: + case 242 /* JsxSelfClosingElement */: + case 241 /* JsxElement */: + return true; + case 188 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 187 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 185 /* PrefixUnaryExpression */: + case 186 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 49 /* ExclamationToken */: + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 183 /* VoidExpression */: // Explicit opt-out + case 177 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 195 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 96 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], /*subtypeReduction*/ true); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -27619,23 +33826,26 @@ var ts; case 68 /* CaretEqualsToken */: case 46 /* AmpersandToken */: case 66 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.19.1 // These operators require their operands to be of type Any, the Number primitive type, // or an enum type. Operands of an enum type are treated // as having the primitive type Number. If one operand is the null or undefined value, // it is treated as having the type of the other operand. // The result is always of the Number primitive type. - if (leftType.flags & 96 /* Nullable */) + if (leftType.flags & 6144 /* Nullable */) leftType = rightType; - if (rightType.flags & 96 /* Nullable */) + if (rightType.flags & 6144 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion - if ((leftType.flags & 8 /* Boolean */) && - (rightType.flags & 8 /* Boolean */) && + if ((leftType.flags & 136 /* BooleanLike */) && + (rightType.flags & 136 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -27650,24 +33860,27 @@ var ts; return numberType; case 35 /* PlusToken */: case 57 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.19.2 // The binary + operator requires both operands to be of the Number primitive type or an enum type, // or at least one of the operands to be of type Any or the String primitive type. // If one operand is the null or undefined value, it is treated as having the type of the other operand. - if (leftType.flags & 96 /* Nullable */) + if (leftType.flags & 6144 /* Nullable */) leftType = rightType; - if (rightType.flags & 96 /* Nullable */) + if (rightType.flags & 6144 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { + if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { + if (isTypeOfKind(leftType, 34 /* StringLike */) || isTypeOfKind(rightType, 34 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -27703,6 +33916,12 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -27712,19 +33931,26 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; + return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : + leftType; case 52 /* BarBarToken */: - return getUnionType([getNonNullableType(leftType), rightType]); + return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; case 56 /* EqualsToken */: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); case 24 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } return rightType; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 16777216 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -27785,7 +34011,7 @@ var ts; function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 8388608 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 65536 /* YieldContext */) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -27824,14 +34050,22 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getUnionType([type1, type2]); + return getBestChoiceType(type1, type2); } - function checkStringLiteralExpression(node) { - var contextualType = getContextualType(node); - if (contextualType && isStringLiteralUnionType(contextualType)) { - return getStringLiteralTypeForText(node.text); + function checkLiteralExpression(node) { + if (node.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); + case 8 /* NumericLiteral */: + return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); + case 99 /* TrueKeyword */: + return trueType; + case 84 /* FalseKeyword */: + return falseType; } - return stringType; } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -27864,6 +34098,36 @@ var ts; } return links.resolvedType; } + function isTypeAssertion(node) { + node = skipParenthesizedNodes(node); + return node.kind === 177 /* TypeAssertionExpression */ || node.kind === 195 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var type = checkExpressionCached(declaration.initializer); + return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 16384 /* TypeParameter */) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + // If the type parameter is constrained to the base primitive type we're checking for, + // consider this a literal context. For example, given a type parameter 'T extends string', + // this causes us to infer string literal types for T. + if (apparentType.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { + return true; + } + contextualType = apparentType; + } + return maybeTypeOfKind(contextualType, 480 /* Literal */); + } + return false; + } + function checkExpressionForMutableLocation(node, contextualMapper) { + var type = checkExpression(node, contextualMapper); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } function checkPropertyAssignment(node, contextualMapper) { // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including @@ -27871,7 +34135,7 @@ var ts; if (node.name.kind === 140 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - return checkExpression(node.initializer, contextualMapper); + return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { // Grammar checking @@ -27930,11 +34194,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - // Grammar checking - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69 /* Identifier */: @@ -27945,15 +34204,13 @@ var ts; return checkSuperExpression(node); case 93 /* NullKeyword */: return nullWideningType; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: - return booleanType; - case 8 /* NumericLiteral */: - return checkNumericLiteral(node); + return checkLiteralExpression(node); case 189 /* TemplateExpression */: return checkTemplateExpression(node); - case 9 /* StringLiteral */: - return checkStringLiteralExpression(node); case 11 /* NoSubstitutionTemplateLiteral */: return stringType; case 10 /* RegularExpressionLiteral */: @@ -28037,7 +34294,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 92 /* ParameterPropertyModifier */) { + if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { func = ts.getContainingFunction(node); if (!(func.kind === 148 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -28109,9 +34366,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_15 = _a[_i].name; - if (ts.isBindingPattern(name_15) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, parameterName, typePredicate.parameterName)) { + var name_18 = _a[_i].name; + if (ts.isBindingPattern(name_18) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -28131,23 +34388,27 @@ var ts; case 156 /* FunctionType */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - var parent_10 = node.parent; - if (node === parent_10.type) { - return parent_10; + var parent_11 = node.parent; + if (node === parent_11.type) { + return parent_11; } } } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (name_16.kind === 69 /* Identifier */ && - name_16.text === predicateVariableName) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name_19 = element.name; + if (name_19.kind === 69 /* Identifier */ && + name_19.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_16.kind === 168 /* ArrayBindingPattern */ || - name_16.kind === 167 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, predicateVariableNode, predicateVariableName)) { + else if (name_19.kind === 168 /* ArrayBindingPattern */ || + name_19.kind === 167 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { return true; } } @@ -28202,22 +34463,27 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (!node.body) { + if (noUnusedIdentifiers && !node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var getter = 1, setter = 2, property = getter | setter; - var instanceNames = {}; - var staticNames = {}; + var Accessor; + (function (Accessor) { + Accessor[Accessor["Getter"] = 1] = "Getter"; + Accessor[Accessor["Setter"] = 2] = "Setter"; + Accessor[Accessor["Property"] = 3] = "Property"; + })(Accessor || (Accessor = {})); + var instanceNames = ts.createMap(); + var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, property); + addName(instanceNames, param.name, param.name.text, 3 /* Property */); } } } @@ -28228,21 +34494,21 @@ var ts; if (memberName) { switch (member.kind) { case 149 /* GetAccessor */: - addName(names, member.name, memberName, getter); + addName(names, member.name, memberName, 1 /* Getter */); break; case 150 /* SetAccessor */: - addName(names, member.name, memberName, setter); + addName(names, member.name, memberName, 2 /* Setter */); break; case 145 /* PropertyDeclaration */: - addName(names, member.name, memberName, property); + addName(names, member.name, memberName, 3 /* Property */); break; } } } } function addName(names, location, name, meaning) { - if (ts.hasProperty(names, name)) { - var prev = names[name]; + var prev = names[name]; + if (prev) { if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -28256,7 +34522,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = {}; + var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144 /* PropertySignature */) { @@ -28270,7 +34536,7 @@ var ts; default: continue; } - if (ts.hasProperty(names, memberName)) { + if (names[memberName]) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -28334,7 +34600,7 @@ var ts; checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (node.flags & 128 /* Abstract */ && node.body) { + if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -28383,7 +34649,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 145 /* PropertyDeclaration */ && - !(n.flags & 32 /* Static */) && + !(ts.getModifierFlags(n) & 32 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -28403,7 +34669,7 @@ var ts; // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & 92 /* ParameterPropertyModifier */; }); + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -28436,13 +34702,8 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); if (node.kind === 149 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768 /* HasImplicitReturn */)) { - if (node.flags & 65536 /* HasExplicitReturn */) { - if (compilerOptions.noImplicitReturns) { - error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -28459,10 +34720,10 @@ var ts; var otherKind = node.kind === 149 /* GetAccessor */ ? 150 /* SetAccessor */ : 149 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 28 /* AccessibilityModifier */) !== (otherAccessor.flags & 28 /* AccessibilityModifier */))) { + if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (((node.flags & 128 /* Abstract */) !== (otherAccessor.flags & 128 /* Abstract */))) { + if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } // TypeScript 1.0 spec (April 2014): 4.5 @@ -28471,7 +34732,10 @@ var ts; checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - getTypeOfAccessors(getSymbolOfNode(node)); + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 149 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171 /* ObjectLiteralExpression */) { checkSourceElement(node.body); @@ -28503,7 +34767,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -28525,6 +34789,9 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } + if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); + } } } function checkTypeQuery(node) { @@ -28554,10 +34821,10 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 8 /* Private */) && ts.isInAmbientContext(node); + return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedNodeFlags(n); + var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. if (n.parent.kind !== 222 /* InterfaceDeclaration */ && @@ -28620,7 +34887,7 @@ var ts; } } var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; - var someNodeFlags = 0; + var someNodeFlags = 0 /* None */; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; var allHaveQuestionToken = true; @@ -28651,13 +34918,13 @@ var ts; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { var reportError = (node.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) && - (node.flags & 32 /* Static */) !== (subsequentNode.flags & 32 /* Static */); + (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members // 2. something with the same name was defined before the set of overloads that prevents them from merging // here we'll report error only for the first case since for second we should already report error in binder if (reportError) { - var diagnostic = node.flags & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -28675,7 +34942,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (node.flags & 128 /* Abstract */) { + if (ts.getModifierFlags(node) & 128 /* Abstract */) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -28743,7 +35010,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -28832,10 +35099,10 @@ var ts; case 224 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; case 229 /* ImportEqualsDeclaration */: - var result_1 = 0; + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); - return result_1; + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; default: return 1048576 /* ExportValue */; } @@ -28872,7 +35139,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 4096 /* Reference */) { + if (promise.flags & 131072 /* Reference */) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -28898,7 +35165,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -28916,13 +35183,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types); + return getUnionType(types, /*subtypeReduction*/ true); } else { var promisedType = getPromisedType(type); @@ -29001,7 +35268,7 @@ var ts; * @param returnType The return type of a FunctionLikeDeclaration * @param location The node on which to report the error. */ - function checkCorrectPromiseType(returnType, location) { + function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { if (returnType === unknownType) { // The return type already had some other error, so we ignore and return // the unknown type. @@ -29018,7 +35285,7 @@ var ts; } // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(location, diagnostic, typeName); return unknownType; } /** @@ -29037,7 +35304,7 @@ var ts; function checkAsyncFunctionReturnType(node) { if (languageVersion >= 2 /* ES6 */) { var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type); + return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { @@ -29079,17 +35346,17 @@ var ts; } var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { + // try to fall back to global promise type. var typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - return unknownType; + return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); } // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. checkReturnTypeAnnotationAsExpression(node); // Validate the promise constructor type. var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } // Verify there is no local declaration that could collide with the promise constructor. @@ -29144,7 +35411,7 @@ var ts; // serialize the type metadata. if (node && node.kind === 155 /* TypeReference */) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = root.parent.kind === 155 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; // Resolve type so we know which symbol is referenced var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias @@ -29333,22 +35600,21 @@ var ts; } function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function(key) { - if (ts.hasProperty(node.locals, key)) { - var local_1 = node.locals[key]; - if (!local_1.isReferenced) { - if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142 /* Parameter */) { - var parameter = local_1.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); - } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); + var _loop_1 = function (key) { + var local = node.locals[key]; + if (!local.isReferenced) { + if (local.valueDeclaration && local.valueDeclaration.kind === 142 /* Parameter */) { + var parameter = local.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + } } }; for (var key in node.locals) { @@ -29356,6 +35622,9 @@ var ts; } } } + function parameterIsThisKeyword(parameter) { + return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; + } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -29365,15 +35634,15 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 147 /* MethodDeclaration */ || member.kind === 145 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && member.flags & 8 /* Private */) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } else if (member.kind === 148 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && parameter.flags & 8 /* Private */) { - error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -29384,9 +35653,16 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!typeParameter.symbol.isReferenced) { + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -29396,14 +35672,12 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - if (ts.hasProperty(node.locals, key)) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); - } + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } } @@ -29522,7 +35796,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152 /* HasAsyncFunctions */) { + if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -29551,7 +35825,7 @@ var ts; // const x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { return; } // skip variable declarations that don't have initializers @@ -29566,7 +35840,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072 /* BlockScoped */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219 /* VariableDeclarationList */); var container = varDeclList.parent.kind === 200 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent @@ -29583,8 +35857,8 @@ var ts; // otherwise if variable has an initializer - show error that initialization will fail // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - var name_17 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_17, name_17); + var name_20 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); } } } @@ -29637,7 +35911,7 @@ var ts; // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred if (current.parent.kind === 145 /* PropertyDeclaration */ && - !(current.parent.flags & 32 /* Static */) && + !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)) { return; } @@ -29672,12 +35946,12 @@ var ts; checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_11 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_11); - var name_18 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_18)); - if (parent_11.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); + var parent_12 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_12); + var name_21 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); + if (parent_12.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -29750,7 +36024,7 @@ var ts; 128 /* Abstract */ | 64 /* Readonly */ | 32 /* Static */; - return (left.flags & interestingFlags) === (right.flags & interestingFlags); + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); @@ -29892,7 +36166,7 @@ var ts; if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -29903,7 +36177,7 @@ var ts; var rightType = checkNonNullExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -29985,7 +36259,7 @@ var ts; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableType()) { + if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -30000,7 +36274,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true), errorNode); } } return typeAsIterable.iterableElementType; @@ -30026,7 +36300,7 @@ var ts; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. - if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIteratorType()) { + if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -30041,7 +36315,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -30063,7 +36337,7 @@ var ts; } // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), // then just grab its type argument. - if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, /*errorNode*/ undefined) || @@ -30091,10 +36365,10 @@ var ts; // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 16384 /* Union */) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); + if (arrayOrStringType.flags & 524288 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34 /* StringLike */); }), /*subtypeReduction*/ true); } - else if (arrayOrStringType.flags & 258 /* StringLike */) { + else if (arrayOrStringType.flags & 34 /* StringLike */) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -30106,7 +36380,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType === neverType) { + if (arrayType.flags & 8192 /* Never */) { return stringType; } } @@ -30126,10 +36400,10 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 258 /* StringLike */) { + if (arrayElementType.flags & 34 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType]); + return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); } return arrayElementType; } @@ -30143,7 +36417,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 /* Void */ | 1 /* Any */); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -30157,7 +36431,7 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType === neverType) { + if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (func.asteriskToken) { // A generator does not need its return expressions checked against its return type. @@ -30201,7 +36475,7 @@ var ts; function checkWithStatement(node) { // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 33554432 /* AwaitContext */) { + if (node.flags & 262144 /* AwaitContext */) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -30295,7 +36569,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals && ts.hasProperty(locals, identifierName)) { + if (locals) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -30320,14 +36594,14 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 1024 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 32768 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(member.flags & 32 /* Static */) && ts.hasDynamicName(member)) { + if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -30339,7 +36613,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (type.flags & 2048 /* Interface */)) { + if (!errorNode && (type.flags & 65536 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -30364,7 +36638,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 2048 /* Interface */) { + else if (containingType.flags & 65536 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -30436,7 +36710,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 512 /* Default */)) { + if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -30479,6 +36753,11 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { + error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); + } + } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type @@ -30496,15 +36775,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { + if (!ts.isEntityNameExpression(typeRefNode.expression)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; - if (declaredType.flags & (1024 /* Class */ | 2048 /* Interface */)) { + var declaredType = (t.flags & 131072 /* Reference */) ? t.target : t; + if (declaredType.flags & (32768 /* Class */ | 65536 /* Interface */)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -30523,7 +36802,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && declaration.flags & 8 /* Private */) { + if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); @@ -30562,7 +36841,7 @@ var ts; continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + var baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { // In order to resolve whether the inherited method was overridden in the base class or not, @@ -30574,7 +36853,7 @@ var ts; // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { if (derivedClassDecl.kind === 192 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -30585,7 +36864,7 @@ var ts; } else { // derived overrides base. - var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); if ((baseDeclarationFlags & 8 /* Private */) || (derivedDeclarationFlags & 8 /* Private */)) { // either base or derived property is private - not override, skip it continue; @@ -30658,19 +36937,19 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = {}; + var seen = ts.createMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; - if (!ts.hasProperty(seen, prop.name)) { + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var prop = properties_5[_a]; + var existing = seen[prop.name]; + if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; } else { - var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -30711,7 +36990,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -30719,7 +36998,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - checkUnusedTypeParameters(node); + registerForUnusedIdentifiersCheck(node); } } function checkTypeAliasDeclaration(node) { @@ -30743,7 +37022,7 @@ var ts; } else { var text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text)) { + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -31072,10 +37351,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - // Ambient shorthand module is an implicit any - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -31102,9 +37377,9 @@ var ts; break; case 169 /* BindingElement */: case 218 /* VariableDeclaration */: - var name_19 = node.name; - if (ts.isBindingPattern(name_19)) { - for (var _b = 0, _c = name_19.elements; _b < _c.length; _b++) { + var name_22 = node.name; + if (ts.isBindingPattern(name_22)) { + for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); @@ -31137,19 +37412,20 @@ var ts; } } function getFirstIdentifier(node) { - while (true) { - if (node.kind === 139 /* QualifiedName */) { - node = node.left; - } - else if (node.kind === 172 /* PropertyAccessExpression */) { - node = node.expression; - } - else { - break; - } + switch (node.kind) { + case 69 /* Identifier */: + return node; + case 139 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 69 /* Identifier */); + return node; + case 172 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 69 /* Identifier */); + return node; } - ts.Debug.assert(node.kind === 69 /* Identifier */); - return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -31189,8 +37465,8 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | - (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | - (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); + (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -31210,7 +37486,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -31238,7 +37514,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1 /* Export */) { + if (ts.getModifierFlags(node) & 1 /* Export */) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -31247,11 +37523,11 @@ var ts; if (target.flags & 107455 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1536 /* Namespace */).flags & 1536 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793056 /* Type */) { + if (target.flags & 793064 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -31269,7 +37545,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -31301,7 +37577,7 @@ var ts; if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, + var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); @@ -31322,7 +37598,7 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1023 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69 /* Identifier */) { @@ -31371,7 +37647,7 @@ var ts; var _a = exports[id], declarations = _a.declarations, flags = _a.flags; // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1536 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -31554,9 +37830,10 @@ var ts; } } function checkSourceFile(node) { - var start = new Date().getTime(); + ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); - ts.checkTime += new Date().getTime() - start; + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { @@ -31636,8 +37913,8 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; - var memberFlags = 0; + var symbols = ts.createMap(); + var memberFlags = 0 /* None */; if (isInsideWithStatementBody(location)) { // We cannot answer semantic questions within a with block, do not proceed any further return []; @@ -31674,7 +37951,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!(memberFlags & 32 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); + copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); } break; case 179 /* FunctionExpression */: @@ -31687,7 +37964,7 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - memberFlags = location.flags; + memberFlags = ts.getModifierFlags(location); location = location.parent; } copySymbols(globals, meaning); @@ -31705,7 +37982,7 @@ var ts; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array - if (!ts.hasProperty(symbols, id)) { + if (!symbols[id]) { symbols[id] = symbol; } } @@ -31794,17 +38071,15 @@ var ts; default: } } - if (entityName.parent.kind === 235 /* ExportAssignment */) { + if (entityName.parent.kind === 235 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 172 /* PropertyAccessExpression */) { - if (isInRightSideOfImportOrExportAssignment(entityName)) { - // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); - } + if (entityName.kind !== 172 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -31813,19 +38088,19 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 194 /* ExpressionWithTypeArguments */) { - meaning = 793056 /* Type */; + meaning = 793064 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455 /* Value */; } } else { - meaning = 1536 /* Namespace */; + meaning = 1920 /* Namespace */; } meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (ts.isExpression(entityName)) { + else if (ts.isPartOfExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { // Missing entity name. return undefined; @@ -31852,7 +38127,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 246 /* JsxAttribute */) { @@ -31908,7 +38183,7 @@ var ts; } // fallthrough case 95 /* SuperKeyword */: - var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case 165 /* ThisType */: return getTypeFromTypeNode(node).symbol; @@ -31956,17 +38231,17 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return unknownType; } - if (ts.isTypeNode(node)) { + if (ts.isPartOfTypeNode(node)) { return getTypeFromTypeNode(node); } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { return getTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -32051,7 +38326,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return checkExpression(expr); + return getRegularTypeOfLiteralType(checkExpression(expr)); } /** * Gets either the static or instance type of a class element, based on @@ -32059,7 +38334,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 32 /* Static */ + return ts.getModifierFlags(node) & 32 /* Static */ ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -32070,7 +38345,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!ts.hasProperty(propsByName, p.name)) { + if (!propsByName[p.name]) { propsByName[p.name] = p; } }); @@ -32080,9 +38355,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* SyntheticProperty */) { var symbols_3 = []; - var name_20 = symbol.name; + var name_23 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_20); + var symbol = getPropertyOfType(t, name_23); if (symbol) { symbols_3.push(symbol); } @@ -32103,12 +38378,18 @@ var ts; } // Emitter support function isArgumentsLocalBinding(node) { - return getReferencedValueSymbol(node) === argumentsSymbol; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + return getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol) { - // module not found - be conservative + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -32121,7 +38402,7 @@ var ts; // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455 /* Value */) - : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -32129,32 +38410,44 @@ var ts; return s && !!(s.flags & 107455 /* Value */); } } + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node) { - var symbol = getReferencedValueSymbol(node); - if (symbol) { - if (symbol.flags & 1048576 /* ExportValue */) { - // If we reference an exported entity within the same module declaration, then whether - // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the - // kinds that we do NOT prefix. - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (exportSymbol.flags & 944 /* ExportHasLocal */) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 256 /* SourceFile */) { - // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. - if (parentSymbol.valueDeclaration === ts.getSourceFileOfNode(node)) { - return parentSymbol.valueDeclaration; + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { + return undefined; } + symbol = exportSymbol; } - for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 225 /* ModuleDeclaration */ || n.kind === 224 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { - return n; + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 256 /* SourceFile */) { + var symbolFile = parentSymbol.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + for (var n = node.parent; n; n = n.parent) { + if (ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) { + return n; + } } } } @@ -32163,8 +38456,14 @@ var ts; // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. function getReferencedImportDeclaration(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined; + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && symbol.flags & 8388608 /* Alias */) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* BlockScoped */) { @@ -32211,32 +38510,56 @@ var ts; // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. function getReferencedDeclarationWithCollidingName(node) { - var symbol = getReferencedValueSymbol(node); - return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel function isDeclarationWithCollidingName(node) { - return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; } function isValueAliasDeclaration(node) { + node = ts.getParseTreeNode(node); + if (node === undefined) { + // A synthesized node comes from an emit transformation and is always a value. + return true; + } switch (node.kind) { case 229 /* ImportEqualsDeclaration */: case 231 /* ImportClause */: case 232 /* NamespaceImport */: case 234 /* ImportSpecifier */: case 238 /* ExportSpecifier */: - return isAliasResolvedToValue(getSymbolOfNode(node)); + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); case 235 /* ExportAssignment */: - return node.expression && node.expression.kind === 69 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; + return node.expression + && node.expression.kind === 69 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 256 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 256 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -32257,9 +38580,14 @@ var ts; return isConstEnumSymbol(s) || s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { + node = ts.getParseTreeNode(node); + // Purely synthesized nodes are always emitted. + if (node === undefined) { + return true; + } if (ts.isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (getSymbolLinks(symbol).referenced) { + if (symbol && getSymbolLinks(symbol).referenced) { return true; } } @@ -32289,7 +38617,8 @@ var ts; return false; } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + node = ts.getParseTreeNode(node); + return node ? getNodeLinks(node).flags : undefined; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -32309,17 +38638,21 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } - function getTypeReferenceSerializationKind(typeName) { + function getTypeReferenceSerializationKind(typeName, location) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true); + var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var globalPromiseSymbol = tryGetGlobalPromiseConstructorSymbol(); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } var constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 793056 /* Type */, /*ignoreErrors*/ true); + var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; @@ -32331,22 +38664,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16 /* Void */)) { - return ts.TypeReferenceSerializationKind.VoidType; + else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeOfKind(type, 8 /* Boolean */)) { + else if (isTypeOfKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 132 /* NumberLike */)) { + else if (isTypeOfKind(type, 340 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 258 /* StringLike */)) { + else if (isTypeOfKind(type, 34 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTypeOfKind(type, 8192 /* Tuple */)) { + else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 16777216 /* ESSymbol */)) { + else if (isTypeOfKind(type, 512 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -32363,7 +38696,7 @@ var ts; // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) - ? getTypeOfSymbol(symbol) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -32382,17 +38715,46 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return ts.hasProperty(globals, name); + return !!globals[name]; } - function getReferencedValueSymbol(reference) { - return getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, - /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent_13 = reference.parent; + if (ts.isDeclaration(parent_13) && reference === parent_13.name) { + location = getDeclarationContainer(parent_13); + } + } + return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); } function getReferencedValueDeclaration(reference) { - ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getReferencedValueSymbol(reference); - return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -32403,9 +38765,6 @@ var ts; // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { - if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { - continue; - } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; @@ -32441,7 +38800,9 @@ var ts; isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue }; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -32454,7 +38815,7 @@ var ts; // identifiers are treated as values only if they appear in type queries var meaning = (node.kind === 172 /* PropertyAccessExpression */) || (node.kind === 69 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793056 /* Type */ | 1536 /* Namespace */; + : 793064 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -32491,9 +38852,9 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_12 = getParentOfSymbol(current); - if (parent_12) { - current = parent_12; + var parent_14 = getParentOfSymbol(current); + if (parent_14) { + current = parent_14; } else { break; @@ -32523,12 +38884,16 @@ var ts; } function initializeTypeChecker() { // Bind all source files and propagate errors - ts.forEach(host.getSourceFiles(), function (file) { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); - }); - var augmentations; + } // Initialize global symbol table - ts.forEach(host.getSourceFiles(), function (file) { + var augmentations; + var requestedExternalEmitHelpers = 0; + var firstFileRequestingExternalHelpers; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -32539,16 +38904,31 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - mergeSymbolTable(globals, file.symbol.globalExports); + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + for (var id in source) { + if (!(id in globals)) { + globals[id] = source[id]; + } + } } - }); + if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { + var fileRequestedExternalEmitHelpers = file.flags & 31744 /* EmitHelperFlags */; + if (fileRequestedExternalEmitHelpers) { + requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; + if (firstFileRequestingExternalHelpers === undefined) { + firstFileRequestingExternalHelpers = file; + } + } + } + } if (augmentations) { // merge module augmentations. // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed - for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { - var list = augmentations_1[_i]; - for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { - var augmentation = list_2[_a]; + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; mergeModuleAugmentation(augmentation); } } @@ -32574,10 +38954,11 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", /*arity*/ 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", /*arity*/ 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", /*arity*/ 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); + tryGetGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalSymbol("Promise", 107455 /* Value */, /*diagnostic*/ undefined) && getGlobalPromiseConstructorSymbol(); }); getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); getGlobalThenableType = ts.memoize(createThenableType); getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); }); @@ -32594,9 +38975,48 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793056 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793064 /* Type */, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + // If we have specified that we are importing helpers, we should report global + // errors if we cannot resolve the helpers external module, or if it does not have + // the necessary helpers exported. + if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { + // Find the first reference to the helpers module. + var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, + /*errorNode*/ undefined); + // If we found the module, report errors if it does not have the necessary exports. + if (helpersModule) { + var exports = helpersModule.exports; + if (requestedExternalEmitHelpers & 1024 /* HasClassExtends */ && languageVersion < 2 /* ES6 */) { + verifyHelperSymbol(exports, "__extends", 107455 /* Value */); + } + if (requestedExternalEmitHelpers & 16384 /* HasJsxSpreadAttributes */ && compilerOptions.jsx !== 1 /* Preserve */) { + verifyHelperSymbol(exports, "__assign", 107455 /* Value */); + } + if (requestedExternalEmitHelpers & 2048 /* HasDecorators */) { + verifyHelperSymbol(exports, "__decorate", 107455 /* Value */); + if (compilerOptions.emitDecoratorMetadata) { + verifyHelperSymbol(exports, "__metadata", 107455 /* Value */); + } + } + if (requestedExternalEmitHelpers & 4096 /* HasParamDecorators */) { + verifyHelperSymbol(exports, "__param", 107455 /* Value */); + } + if (requestedExternalEmitHelpers & 8192 /* HasAsyncFunctions */) { + verifyHelperSymbol(exports, "__awaiter", 107455 /* Value */); + if (languageVersion < 2 /* ES6 */) { + verifyHelperSymbol(exports, "__generator", 107455 /* Value */); + } + } + } + } + } + function verifyHelperSymbol(symbols, name, meaning) { + var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); + if (!symbol) { + error(/*location*/ undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -32609,7 +39029,7 @@ var ts; // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(65536 /* Anonymous */); + var thenableType = createObjectType(2097152 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -32638,52 +39058,12 @@ var ts; return false; } function checkGrammarModifiers(node) { - switch (node.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 225 /* ModuleDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 142 /* Parameter */: - break; - case 220 /* FunctionDeclaration */: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && - node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 200 /* VariableStatement */: - case 223 /* TypeAliasDeclaration */: - if (node.modifiers && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 224 /* EnumDeclaration */: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && - node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - default: - return false; - } - if (!node.modifiers) { - return; + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; - var flags = 0; + var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 128 /* ReadonlyKeyword */) { @@ -32819,7 +39199,7 @@ var ts; node.kind !== 150 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { + if (!(node.parent.kind === 221 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -32874,10 +39254,61 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function checkGrammarAsyncModifier(node, asyncModifier) { - if (languageVersion < 2 /* ES6 */) { - return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 148 /* Constructor */: + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 153 /* IndexSignature */: + case 225 /* ModuleDeclaration */: + case 230 /* ImportDeclaration */: + case 229 /* ImportEqualsDeclaration */: + case 236 /* ExportDeclaration */: + case 235 /* ExportAssignment */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 142 /* Parameter */: + return false; + default: + if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 220 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 118 /* AsyncKeyword */); + case 221 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 115 /* AbstractKeyword */); + case 222 /* InterfaceDeclaration */: + case 200 /* VariableStatement */: + case 223 /* TypeAliasDeclaration */: + return true; + case 224 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 74 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { case 147 /* MethodDeclaration */: case 220 /* FunctionDeclaration */: @@ -32968,7 +39399,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1023 /* Modifier */) { + if (ts.getModifierFlags(parameter) !== 0) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -33006,8 +39437,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { - var arg = args_1[_i]; + for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { + var arg = args_2[_i]; if (arg.kind === 193 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -33111,29 +39542,33 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; - var _loop_2 = function(prop) { - var name_21 = prop.name; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var name_24 = prop.name; if (prop.kind === 193 /* OmittedExpression */ || - name_21.kind === 140 /* ComputedPropertyName */) { + name_24.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_21); + checkGrammarComputedPropertyName(name_24); } if (prop.kind === 254 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } // Modifiers are never allowed on properties except for 'async' on a method declaration - ts.forEach(prop.modifiers, function (mod) { - if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 147 /* MethodDeclaration */) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 147 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } } - }); + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -33146,8 +39581,8 @@ var ts; if (prop.kind === 253 /* PropertyAssignment */ || prop.kind === 254 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_21.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_21); + if (name_24.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_24); } currentKind = Property; } @@ -33163,51 +39598,46 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_21); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); if (effectiveName === undefined) { - return "continue"; + continue; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_21, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_21)); + grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } - }; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var state_3 = _loop_2(prop); - if (typeof state_3 === "object") return state_3.value; } } function checkGrammarJsxElement(node) { - var seen = {}; + var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { - seen[name_22.text] = true; + var name_25 = jsxAttr.name; + if (!seen[name_25.text]) { + seen[name_25.text] = true; } else { - return grammarErrorOnNode(name_22, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 /* JsxExpression */ && !initializer.expression) { @@ -33264,7 +39694,7 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(accessor.flags & 128 /* Abstract */)) { + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { @@ -33415,10 +39845,27 @@ var ts; } } } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 207 /* ForInStatement */ && node.parent.parent.kind !== 208 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + // Error on equals token which immediate precedes the initializer + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -33452,7 +39899,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 193 /* OmittedExpression */) { + if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -33498,8 +39945,8 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); return true; } } @@ -33553,7 +40000,7 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - // A declare modifier is required for any top level .d.ts declaration except export=, export default, + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace // interfaces and imports categories: // // DeclarationElement: @@ -33571,8 +40018,8 @@ var ts; node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 236 /* ExportDeclaration */ || node.kind === 235 /* ExportAssignment */ || - (node.flags & 2 /* Ambient */) || - (node.flags & (1 /* Export */ | 512 /* Default */))) { + node.kind === 228 /* NamespaceExportDeclaration */ || + ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -33626,20 +40073,11913 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); return true; } } - var _a; + function getAmbientModules() { + var result = []; + for (var sym in globals) { + if (ambientModuleSymbolRegex.test(sym)) { + result.push(globals[sym]); + } + } + return result; + } } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); +/// +/// +/// +/* @internal */ +var ts; +(function (ts) { + ; + /** + * This map contains information about the shape of each Node in "types.ts" pertaining to how + * each node should be traversed during a transformation. + * + * Each edge corresponds to a property in a Node subtype that should be traversed when visiting + * each child. The properties are assigned in the order in which traversal should occur. + * + * We only add entries for nodes that do not have a create/update pair defined in factory.ts + * + * NOTE: This needs to be kept up to date with changes to nodes in "types.ts". Currently, this + * map is not comprehensive. Only node edges relevant to tree transformation are + * currently defined. We may extend this to be more comprehensive, and eventually + * supplant the existing `forEachChild` implementation if performance is not + * significantly impacted. + */ + var nodeEdgeTraversalMap = ts.createMap((_a = {}, + _a[139 /* QualifiedName */] = [ + { name: "left", test: ts.isEntityName }, + { name: "right", test: ts.isIdentifier } + ], + _a[143 /* Decorator */] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[177 /* TypeAssertionExpression */] = [ + { name: "type", test: ts.isTypeNode }, + { name: "expression", test: ts.isUnaryExpression } + ], + _a[195 /* AsExpression */] = [ + { name: "expression", test: ts.isExpression }, + { name: "type", test: ts.isTypeNode } + ], + _a[196 /* NonNullExpression */] = [ + { name: "expression", test: ts.isLeftHandSideExpression } + ], + _a[224 /* EnumDeclaration */] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[225 /* ModuleDeclaration */] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[226 /* ModuleBlock */] = [ + { name: "statements", test: ts.isStatement } + ], + _a[229 /* ImportEqualsDeclaration */] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "moduleReference", test: ts.isModuleReference } + ], + _a[240 /* ExternalModuleReference */] = [ + { name: "expression", test: ts.isExpression, optional: true } + ], + _a[255 /* EnumMember */] = [ + { name: "name", test: ts.isPropertyName }, + { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } + ], + _a)); + function reduceNode(node, f, initial) { + return node ? f(initial, node) : initial; + } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the + * `nodeEdgeTraversalMap` above will be visited. + * + * @param node The node containing the children to reduce. + * @param f The callback function + * @param initial The initial value to supply to the reduction. + */ + function reduceEachChild(node, f, initial) { + if (node === undefined) { + return initial; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + return initial; + } + // We do not yet support types. + if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + return initial; + } + var result = initial; + switch (node.kind) { + // Leaf nodes + case 198 /* SemicolonClassElement */: + case 201 /* EmptyStatement */: + case 193 /* OmittedExpression */: + case 217 /* DebuggerStatement */: + case 287 /* NotEmittedStatement */: + // No need to visit nodes with no children. + break; + // Names + case 140 /* ComputedPropertyName */: + result = reduceNode(node.expression, f, result); + break; + // Signature elements + case 142 /* Parameter */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 143 /* Decorator */: + result = reduceNode(node.expression, f, result); + break; + // Type member + case 145 /* PropertyDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 147 /* MethodDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 148 /* Constructor */: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + case 149 /* GetAccessor */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 150 /* SetAccessor */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.body, f, result); + break; + // Binding patterns + case 167 /* ObjectBindingPattern */: + case 168 /* ArrayBindingPattern */: + result = ts.reduceLeft(node.elements, f, result); + break; + case 169 /* BindingElement */: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + // Expression + case 170 /* ArrayLiteralExpression */: + result = ts.reduceLeft(node.elements, f, result); + break; + case 171 /* ObjectLiteralExpression */: + result = ts.reduceLeft(node.properties, f, result); + break; + case 172 /* PropertyAccessExpression */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.name, f, result); + break; + case 173 /* ElementAccessExpression */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.argumentExpression, f, result); + break; + case 174 /* CallExpression */: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 175 /* NewExpression */: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + result = ts.reduceLeft(node.arguments, f, result); + break; + case 176 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, f, result); + result = reduceNode(node.template, f, result); + break; + case 179 /* FunctionExpression */: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 180 /* ArrowFunction */: + result = ts.reduceLeft(node.modifiers, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 178 /* ParenthesizedExpression */: + case 181 /* DeleteExpression */: + case 182 /* TypeOfExpression */: + case 183 /* VoidExpression */: + case 184 /* AwaitExpression */: + case 190 /* YieldExpression */: + case 191 /* SpreadElementExpression */: + case 196 /* NonNullExpression */: + result = reduceNode(node.expression, f, result); + break; + case 185 /* PrefixUnaryExpression */: + case 186 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, f, result); + break; + case 187 /* BinaryExpression */: + result = reduceNode(node.left, f, result); + result = reduceNode(node.right, f, result); + break; + case 188 /* ConditionalExpression */: + result = reduceNode(node.condition, f, result); + result = reduceNode(node.whenTrue, f, result); + result = reduceNode(node.whenFalse, f, result); + break; + case 189 /* TemplateExpression */: + result = reduceNode(node.head, f, result); + result = ts.reduceLeft(node.templateSpans, f, result); + break; + case 192 /* ClassExpression */: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 194 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, f, result); + result = ts.reduceLeft(node.typeArguments, f, result); + break; + // Misc + case 197 /* TemplateSpan */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.literal, f, result); + break; + // Element + case 199 /* Block */: + result = ts.reduceLeft(node.statements, f, result); + break; + case 200 /* VariableStatement */: + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.declarationList, f, result); + break; + case 202 /* ExpressionStatement */: + result = reduceNode(node.expression, f, result); + break; + case 203 /* IfStatement */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.thenStatement, f, result); + result = reduceNode(node.elseStatement, f, result); + break; + case 204 /* DoStatement */: + result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, f, result); + break; + case 205 /* WhileStatement */: + case 212 /* WithStatement */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 206 /* ForStatement */: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.condition, f, result); + result = reduceNode(node.incrementor, f, result); + result = reduceNode(node.statement, f, result); + break; + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, f, result); + result = reduceNode(node.statement, f, result); + break; + case 211 /* ReturnStatement */: + case 215 /* ThrowStatement */: + result = reduceNode(node.expression, f, result); + break; + case 213 /* SwitchStatement */: + result = reduceNode(node.expression, f, result); + result = reduceNode(node.caseBlock, f, result); + break; + case 214 /* LabeledStatement */: + result = reduceNode(node.label, f, result); + result = reduceNode(node.statement, f, result); + break; + case 216 /* TryStatement */: + result = reduceNode(node.tryBlock, f, result); + result = reduceNode(node.catchClause, f, result); + result = reduceNode(node.finallyBlock, f, result); + break; + case 218 /* VariableDeclaration */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 219 /* VariableDeclarationList */: + result = ts.reduceLeft(node.declarations, f, result); + break; + case 220 /* FunctionDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.parameters, f, result); + result = reduceNode(node.type, f, result); + result = reduceNode(node.body, f, result); + break; + case 221 /* ClassDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.name, f, result); + result = ts.reduceLeft(node.typeParameters, f, result); + result = ts.reduceLeft(node.heritageClauses, f, result); + result = ts.reduceLeft(node.members, f, result); + break; + case 227 /* CaseBlock */: + result = ts.reduceLeft(node.clauses, f, result); + break; + case 230 /* ImportDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.importClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + case 231 /* ImportClause */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.namedBindings, f, result); + break; + case 232 /* NamespaceImport */: + result = reduceNode(node.name, f, result); + break; + case 233 /* NamedImports */: + case 237 /* NamedExports */: + result = ts.reduceLeft(node.elements, f, result); + break; + case 234 /* ImportSpecifier */: + case 238 /* ExportSpecifier */: + result = reduceNode(node.propertyName, f, result); + result = reduceNode(node.name, f, result); + break; + case 235 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.expression, f, result); + break; + case 236 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, f, result); + result = ts.reduceLeft(node.modifiers, f, result); + result = reduceNode(node.exportClause, f, result); + result = reduceNode(node.moduleSpecifier, f, result); + break; + // JSX + case 241 /* JsxElement */: + result = reduceNode(node.openingElement, f, result); + result = ts.reduceLeft(node.children, f, result); + result = reduceNode(node.closingElement, f, result); + break; + case 242 /* JsxSelfClosingElement */: + case 243 /* JsxOpeningElement */: + result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.attributes, f, result); + break; + case 245 /* JsxClosingElement */: + result = reduceNode(node.tagName, f, result); + break; + case 246 /* JsxAttribute */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 247 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, f, result); + break; + case 248 /* JsxExpression */: + result = reduceNode(node.expression, f, result); + break; + // Clauses + case 249 /* CaseClause */: + result = reduceNode(node.expression, f, result); + // fall-through + case 250 /* DefaultClause */: + result = ts.reduceLeft(node.statements, f, result); + break; + case 251 /* HeritageClause */: + result = ts.reduceLeft(node.types, f, result); + break; + case 252 /* CatchClause */: + result = reduceNode(node.variableDeclaration, f, result); + result = reduceNode(node.block, f, result); + break; + // Property assignments + case 253 /* PropertyAssignment */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.initializer, f, result); + break; + case 254 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, f, result); + result = reduceNode(node.objectAssignmentInitializer, f, result); + break; + // Top-level nodes + case 256 /* SourceFile */: + result = ts.reduceLeft(node.statements, f, result); + break; + case 288 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, f, result); + break; + default: + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_1 = edgeTraversalPath; _i < edgeTraversalPath_1.length; _i++) { + var edge = edgeTraversalPath_1[_i]; + var value = node[edge.name]; + if (value !== undefined) { + result = ts.isArray(value) + ? ts.reduceLeft(value, f, result) + : f(result, value); + } + } + } + break; + } + return result; + } + ts.reduceEachChild = reduceEachChild; + function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { + if (node === undefined) { + return undefined; + } + var visited = visitor(node); + if (visited === node) { + return node; + } + var visitedNode; + if (visited === undefined) { + if (!optional) { + Debug.failNotOptional(); + } + return undefined; + } + else if (ts.isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } + else { + visitedNode = visited; + } + if (parenthesize !== undefined) { + visitedNode = parenthesize(visitedNode, parentNode); + } + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + return visitedNode; + } + ts.visitNode = visitNode; + function visitNodes(nodes, visitor, test, start, count, parenthesize, parentNode) { + if (nodes === undefined) { + return undefined; + } + var updated; + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*location*/ undefined, + /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); + } + // Visit each original node. + for (var i = 0; i < count; i++) { + var node = nodes[i + start]; + var visited = node !== undefined ? visitor(node) : undefined; + if (updated !== undefined || visited === undefined || visited !== node) { + if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. + updated = ts.createNodeArray(nodes.slice(0, i), /*location*/ nodes, nodes.hasTrailingComma); + } + if (visited) { + if (ts.isArray(visited)) { + for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) { + var visitedNode = visited_1[_i]; + visitedNode = parenthesize + ? parenthesize(visitedNode, parentNode) + : visitedNode; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + else { + var visitedNode = parenthesize + ? parenthesize(visited, parentNode) + : visited; + Debug.assertNode(visitedNode, test); + aggregateTransformFlags(visitedNode); + updated.push(visitedNode); + } + } + } + } + return updated || nodes; + } + ts.visitNodes = visitNodes; + function visitEachChild(node, visitor, context) { + if (node === undefined) { + return undefined; + } + var kind = node.kind; + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + return node; + } + // We do not yet support types. + if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + return node; + } + switch (node.kind) { + case 198 /* SemicolonClassElement */: + case 201 /* EmptyStatement */: + case 193 /* OmittedExpression */: + case 217 /* DebuggerStatement */: + // No need to visit nodes with no children. + return node; + // Names + case 140 /* ComputedPropertyName */: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + // Signature elements + case 142 /* Parameter */: + return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + // Type member + case 145 /* PropertyDeclaration */: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 147 /* MethodDeclaration */: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 148 /* Constructor */: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 149 /* GetAccessor */: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 150 /* SetAccessor */: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + // Binding patterns + case 167 /* ObjectBindingPattern */: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 168 /* ArrayBindingPattern */: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 169 /* BindingElement */: + return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, /*optional*/ true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + // Expression + case 170 /* ArrayLiteralExpression */: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 171 /* ObjectLiteralExpression */: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 172 /* PropertyAccessExpression */: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 173 /* ElementAccessExpression */: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 174 /* CallExpression */: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 175 /* NewExpression */: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 176 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + case 178 /* ParenthesizedExpression */: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 179 /* FunctionExpression */: + return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 180 /* ArrowFunction */: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, /*optional*/ true), context.endLexicalEnvironment())); + case 181 /* DeleteExpression */: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 182 /* TypeOfExpression */: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 183 /* VoidExpression */: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184 /* AwaitExpression */: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187 /* BinaryExpression */: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 185 /* PrefixUnaryExpression */: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 186 /* PostfixUnaryExpression */: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 188 /* ConditionalExpression */: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 189 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 190 /* YieldExpression */: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 191 /* SpreadElementExpression */: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192 /* ClassExpression */: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 194 /* ExpressionWithTypeArguments */: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + // Misc + case 197 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + // Element + case 199 /* Block */: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 200 /* VariableStatement */: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); + case 202 /* ExpressionStatement */: + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 203 /* IfStatement */: + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, /*optional*/ true, liftToBlock)); + case 204 /* DoStatement */: + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + case 205 /* WhileStatement */: + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 206 /* ForStatement */: + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 207 /* ForInStatement */: + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 208 /* ForOfStatement */: + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 209 /* ContinueStatement */: + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); + case 210 /* BreakStatement */: + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); + case 211 /* ReturnStatement */: + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true)); + case 212 /* WithStatement */: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 213 /* SwitchStatement */: + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + case 214 /* LabeledStatement */: + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); + case 215 /* ThrowStatement */: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 216 /* TryStatement */: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, /*optional*/ true), visitNode(node.finallyBlock, visitor, ts.isBlock, /*optional*/ true)); + case 218 /* VariableDeclaration */: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 219 /* VariableDeclarationList */: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 220 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 221 /* ClassDeclaration */: + return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 227 /* CaseBlock */: + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); + case 230 /* ImportDeclaration */: + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + case 231 /* ImportClause */: + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true)); + case 232 /* NamespaceImport */: + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 233 /* NamedImports */: + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 234 /* ImportSpecifier */: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); + case 235 /* ExportAssignment */: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + case 236 /* ExportDeclaration */: + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, /*optional*/ true)); + case 237 /* NamedExports */: + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + case 238 /* ExportSpecifier */: + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); + // JSX + case 241 /* JsxElement */: + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + case 242 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 243 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + case 245 /* JsxClosingElement */: + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 246 /* JsxAttribute */: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 247 /* JsxSpreadAttribute */: + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + case 248 /* JsxExpression */: + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + // Clauses + case 249 /* CaseClause */: + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + case 250 /* DefaultClause */: + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 251 /* HeritageClause */: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + case 252 /* CatchClause */: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + // Property assignments + case 253 /* PropertyAssignment */: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 254 /* ShorthandPropertyAssignment */: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + // Top-level nodes + case 256 /* SourceFile */: + context.startLexicalEnvironment(); + return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); + // Transformation nodes + case 288 /* PartiallyEmittedExpression */: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + default: + var updated = void 0; + var edgeTraversalPath = nodeEdgeTraversalMap[kind]; + if (edgeTraversalPath) { + for (var _i = 0, edgeTraversalPath_2 = edgeTraversalPath; _i < edgeTraversalPath_2.length; _i++) { + var edge = edgeTraversalPath_2[_i]; + var value = node[edge.name]; + if (value !== undefined) { + var visited = ts.isArray(value) + ? visitNodes(value, visitor, edge.test, 0, value.length, edge.parenthesize, node) + : visitNode(value, visitor, edge.test, edge.optional, edge.lift, edge.parenthesize, node); + if (updated !== undefined || visited !== value) { + if (updated === undefined) { + updated = ts.getMutableClone(node); + } + if (visited !== value) { + updated[edge.name] = visited; + } + } + } + } + } + return updated ? ts.updateNode(updated, node) : node; + } + // return node; + } + ts.visitEachChild = visitEachChild; + function mergeFunctionBodyLexicalEnvironment(body, declarations) { + if (body && declarations !== undefined && declarations.length > 0) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.createNodeArray(ts.concatenate(body.statements, declarations), body.statements)); + } + else { + return ts.createBlock(ts.createNodeArray([ts.createReturn(body, /*location*/ body)].concat(declarations), body), + /*location*/ body, + /*multiLine*/ true); + } + } + return body; + } + ts.mergeFunctionBodyLexicalEnvironment = mergeFunctionBodyLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ + function liftToBlock(nodes) { + Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); + return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); + } + ts.liftToBlock = liftToBlock; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ + function extractSingleNode(nodes) { + Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return ts.singleOrUndefined(nodes); + } + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ + function aggregateTransformFlags(node) { + aggregateTransformFlagsForNode(node); + return node; + } + ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ + function aggregateTransformFlagsForNode(node) { + if (node === undefined) { + return 0 /* None */; + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + } + /** + * Aggregates the transform flags for the subtree of a node. + */ + function aggregateTransformFlagsForSubtree(node) { + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || ts.isTypeNode(node)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0 /* None */); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ + function aggregateTransformFlagsForChildNode(transformFlags, child) { + return transformFlags | aggregateTransformFlagsForNode(child); + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 174 /* CallExpression */: + case 175 /* NewExpression */: + case 170 /* ArrayLiteralExpression */: + return 537133909 /* ArrayLiteralOrCallOrNewExcludes */; + case 225 /* ModuleDeclaration */: + return 546335573 /* ModuleExcludes */; + case 142 /* Parameter */: + return 538968917 /* ParameterExcludes */; + case 180 /* ArrowFunction */: + return 550710101 /* ArrowFunctionExcludes */; + case 179 /* FunctionExpression */: + case 220 /* FunctionDeclaration */: + return 550726485 /* FunctionExcludes */; + case 219 /* VariableDeclarationList */: + return 538968917 /* VariableDeclarationListExcludes */; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + return 537590613 /* ClassExcludes */; + case 148 /* Constructor */: + return 550593365 /* ConstructorExcludes */; + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return 550593365 /* MethodOrAccessorExcludes */; + case 117 /* AnyKeyword */: + case 130 /* NumberKeyword */: + case 127 /* NeverKeyword */: + case 132 /* StringKeyword */: + case 120 /* BooleanKeyword */: + case 133 /* SymbolKeyword */: + case 103 /* VoidKeyword */: + case 141 /* TypeParameter */: + case 144 /* PropertySignature */: + case 146 /* MethodSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 153 /* IndexSignature */: + case 222 /* InterfaceDeclaration */: + case 223 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 171 /* ObjectLiteralExpression */: + return 537430869 /* ObjectLiteralExcludes */; + default: + return 536871765 /* NodeExcludes */; + } + } + var Debug; + (function (Debug) { + Debug.failNotOptional = Debug.shouldAssert(1 /* Normal */) + ? function (message) { return Debug.assert(false, message || "Node not optional."); } + : function (message) { }; + Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + : function (node, message) { }; + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : function (node, test, message) { }; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + })(Debug = ts.Debug || (ts.Debug = {})); + var _a; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + /** + * Flattens a destructuring assignment expression. + * + * @param root The destructuring assignment expression. + * @param needsValue Indicates whether the value from the right-hand-side of the + * destructuring assignment is needed as part of a larger expression. + * @param recordTempVariable A callback used to record new temporary variables. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { + if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + var right = node.right; + if (ts.isDestructuringAssignment(right)) { + return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); + } + else { + return node.right; + } + } + var location = node; + var value = node.right; + var expressions = []; + if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignmen) is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); + if (needsValue) { + expressions.push(value); + } + var expression = ts.inlineExpressions(expressions); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location) { + var expression = ts.createAssignment(name, value, location); + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(expression); + expressions.push(expression); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + /** + * Flattens binding patterns in a parameter declaration. + * + * @param node The ParameterDeclaration to flatten. + * @param value The rhs value for the binding pattern. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenParameterDestructuring(context, node, value, visitor) { + var declarations = []; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location) { + var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.aggregateTransformFlags(declaration); + declarations.push(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(/*recordTempVariable*/ undefined); + emitAssignment(name, value, location); + return name; + } + } + ts.flattenParameterDestructuring = flattenParameterDestructuring; + /** + * Flattens binding patterns in a variable declaration. + * + * @param node The VariableDeclaration to flatten. + * @param value An optional rhs value for the binding pattern. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { + var declarations = []; + var pendingAssignments; + flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + return declarations; + function emitAssignment(name, value, location, original) { + if (pendingAssignments) { + pendingAssignments.push(value); + value = ts.inlineExpressions(pendingAssignments); + pendingAssignments = undefined; + } + var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); + declaration.original = original; + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + declarations.push(declaration); + ts.aggregateTransformFlags(declaration); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + if (recordTempVariable) { + var assignment = ts.createAssignment(name, value, location); + if (pendingAssignments) { + pendingAssignments.push(assignment); + } + else { + pendingAssignments = [assignment]; + } + } + else { + emitAssignment(name, value, location, /*original*/ undefined); + } + return name; + } + } + ts.flattenVariableDestructuring = flattenVariableDestructuring; + /** + * Flattens binding patterns in a variable declaration and transforms them into an expression. + * + * @param node The VariableDeclaration to flatten. + * @param recordTempVariable A callback used to record new temporary variables. + * @param nameSubstitution An optional callback used to substitute binding names. + * @param visitor An optional visitor to use to visit expressions. + */ + function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { + var pendingAssignments = []; + flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor); + var expression = ts.inlineExpressions(pendingAssignments); + ts.aggregateTransformFlags(expression); + return expression; + function emitAssignment(name, value, location, original) { + var left = nameSubstitution && nameSubstitution(name) || name; + emitPendingAssignment(left, value, location, original); + } + function emitTempVariableAssignment(value, location) { + var name = ts.createTempVariable(recordTempVariable); + emitPendingAssignment(name, value, location, /*original*/ undefined); + return name; + } + function emitPendingAssignment(name, value, location, original) { + var expression = ts.createAssignment(name, value, location); + expression.original = original; + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + pendingAssignments.push(expression); + return expression; + } + } + ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; + function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { + if (value && visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + if (ts.isBinaryExpression(root)) { + emitDestructuringAssignment(root.left, value, location); + } + else { + emitBindingElement(root, value); + } + function emitDestructuringAssignment(bindingTarget, value, location) { + // When emitting target = value use source map node to highlight, including any temporary assignments needed for this + var target; + if (ts.isShorthandPropertyAssignment(bindingTarget)) { + var initializer = visitor + ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) + : bindingTarget.objectAssignmentInitializer; + if (initializer) { + value = createDefaultValueCheck(value, initializer, location); + } + target = bindingTarget.name; + } + else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56 /* EqualsToken */) { + var initializer = visitor + ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) + : bindingTarget.right; + value = createDefaultValueCheck(value, initializer, location); + target = bindingTarget.left; + } + else { + target = bindingTarget; + } + if (target.kind === 171 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value, location); + } + else if (target.kind === 170 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value, location); + } + else { + var name_26 = ts.getMutableClone(target); + context.setSourceMapRange(name_26, target); + context.setCommentRange(name_26, target); + emitAssignment(name_26, value, location, /*original*/ undefined); + } + } + function emitObjectLiteralAssignment(target, value, location) { + var properties = target.properties; + if (properties.length !== 1) { + // For anything but a single element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. + // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); + } + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + if (p.kind === 253 /* PropertyAssignment */ || p.kind === 254 /* ShorthandPropertyAssignment */) { + var propName = p.name; + var target_1 = p.kind === 254 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + // Assignment for target = value.propName should highligh whole property, hence use p as source map node + emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); + } + } + } + function emitArrayLiteralAssignment(target, value, location) { + var elements = target.elements; + var numElements = elements.length; + if (numElements !== 1) { + // For anything but a single element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. + // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var e = elements[i]; + if (e.kind !== 193 /* OmittedExpression */) { + // Assignment for target = value.propName should highligh whole property, hence use e as source map node + if (e.kind !== 191 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); + } + else if (i === numElements - 1) { + emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); + } + } + } + } + function emitBindingElement(target, value) { + // Any temporary assignments needed to emit target = value should point to target + var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + if (initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = ts.createVoidZero(); + } + var name = target.name; + if (ts.isBindingPattern(name)) { + var elements = name.elements; + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment); + } + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (ts.isOmittedExpression(element)) { + continue; + } + else if (name.kind === 167 /* ObjectBindingPattern */) { + // Rewrite element to a declaration with an initializer that fetches property + var propName = element.propertyName || element.name; + emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); + } + else { + if (!element.dotDotDotToken) { + // Rewrite element to a declaration that accesses array element at index i + emitBindingElement(element, ts.createElementAccess(value, i)); + } + else if (i === numElements - 1) { + emitBindingElement(element, ts.createArraySlice(value, i)); + } + } + } + } + else { + emitAssignment(name, value, target, target); + } + } + function createDefaultValueCheck(value, defaultValue, location) { + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); + return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53 /* QuestionToken */), defaultValue, ts.createToken(54 /* ColonToken */), value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @param expression The right-hand expression that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(expression, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)); + } + else if (ts.isLiteralExpression(propertyName)) { + var clone_2 = ts.getSynthesizedClone(propertyName); + clone_2.text = ts.unescapeIdentifier(clone_2.text); + return ts.createElementAccess(expression, clone_2); + } + else { + if (ts.isGeneratedIdentifier(propertyName)) { + var clone_3 = ts.getSynthesizedClone(propertyName); + clone_3.text = ts.unescapeIdentifier(clone_3.text); + return ts.createPropertyAccess(expression, clone_3); + } + else { + return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + } + } + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + * @param emitTempVariableAssignment A callback used to emit a temporary variable. + * @param visitor An optional callback used to visit the value. + */ + function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + if (ts.isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } + else { + if (visitor) { + value = ts.visitNode(value, visitor, ts.isExpression); + } + return emitTempVariableAssignment(value, location); + } + } +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ + var USE_NEW_TYPE_METADATA_FORMAT = false; + var TypeScriptSubstitutionFlags; + (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /** Enables substitutions for async methods with `super` calls. */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["AsyncMethodsWithSuper"] = 4] = "AsyncMethodsWithSuper"; + /* Enables substitutions for unqualified enum members */ + TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; + })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + function transformTypeScript(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + var currentNamespace; + var currentNamespaceContainerName; + var currentScope; + var currentSourceFileExternalHelpersModuleName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + var applicableSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var currentSuperContainer; + return transformSourceFile; + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + return ts.visitNode(node, visitor, ts.isSourceFile); + } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ + function saveStateAndInvoke(node, f) { + // Save state + var savedCurrentScope = currentScope; + // Handle state changes before visiting a node. + onBeforeVisitNode(node); + var visited = f(node); + // Restore state + currentScope = savedCurrentScope; + return visited; + } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ + function visitorWorker(node) { + if (node.kind === 256 /* SourceFile */) { + return visitSourceFile(node); + } + else if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ + function namespaceElementVisitorWorker(node) { + if (node.kind === 236 /* ExportDeclaration */ || + node.kind === 230 /* ImportDeclaration */ || + node.kind === 231 /* ImportClause */ || + (node.kind === 229 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 240 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace + return undefined; + } + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. + return visitTypeScript(node); + } + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + return node; + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitor(node) { + return saveStateAndInvoke(node, classElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ + function classElementVisitorWorker(node) { + switch (node.kind) { + case 148 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. + return undefined; + case 145 /* PropertyDeclaration */: + case 153 /* IndexSignature */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 147 /* MethodDeclaration */: + // Fallback to the default visit behavior. + return visitorWorker(node); + case 198 /* SemicolonClassElement */: + return node; + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ + function visitTypeScript(node) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + } + switch (node.kind) { + case 82 /* ExportKeyword */: + case 77 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. + return currentNamespace ? undefined : node; + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 115 /* AbstractKeyword */: + case 118 /* AsyncKeyword */: + case 74 /* ConstKeyword */: + case 122 /* DeclareKeyword */: + case 128 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 160 /* ArrayType */: + case 161 /* TupleType */: + case 159 /* TypeLiteral */: + case 154 /* TypePredicate */: + case 141 /* TypeParameter */: + case 117 /* AnyKeyword */: + case 120 /* BooleanKeyword */: + case 132 /* StringKeyword */: + case 130 /* NumberKeyword */: + case 127 /* NeverKeyword */: + case 103 /* VoidKeyword */: + case 133 /* SymbolKeyword */: + case 157 /* ConstructorType */: + case 156 /* FunctionType */: + case 158 /* TypeQuery */: + case 155 /* TypeReference */: + case 162 /* UnionType */: + case 163 /* IntersectionType */: + case 164 /* ParenthesizedType */: + case 165 /* ThisType */: + case 166 /* LiteralType */: + // TypeScript type nodes are elided. + case 153 /* IndexSignature */: + // TypeScript index signatures are elided. + case 143 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 223 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + case 145 /* PropertyDeclaration */: + // TypeScript property declarations are elided. + case 148 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + return undefined; + case 222 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. + return ts.createNotEmittedStatement(node); + case 221 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + // - async methods + return visitClassDeclaration(node); + case 192 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures + // - async methods + return visitClassExpression(node); + case 251 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause + return visitHeritageClause(node); + case 194 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. + return visitExpressionWithTypeArguments(node); + case 147 /* MethodDeclaration */: + // TypeScript method declarations may be 'async', and may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node); + case 149 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node); + case 150 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitSetAccessor(node); + case 220 /* FunctionDeclaration */: + // TypeScript function declarations may be 'async' + return visitFunctionDeclaration(node); + case 179 /* FunctionExpression */: + // TypeScript function expressions may be 'async' + return visitFunctionExpression(node); + case 180 /* ArrowFunction */: + // TypeScript arrow functions may be 'async' + return visitArrowFunction(node); + case 142 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters + return visitParameter(node); + case 178 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression + return visitParenthesizedExpression(node); + case 177 /* TypeAssertionExpression */: + case 195 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node); + case 196 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. + return visitNonNullExpression(node); + case 224 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. + return visitEnumDeclaration(node); + case 184 /* AwaitExpression */: + // TypeScript 'await' expressions must be transformed. + return visitAwaitExpression(node); + case 200 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. + return visitVariableStatement(node); + case 225 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. + return visitModuleDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. + return visitImportEqualsDeclaration(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 256 /* SourceFile */: + case 227 /* CaseBlock */: + case 226 /* ModuleBlock */: + case 199 /* Block */: + currentScope = node; + break; + } + } + function visitSourceFile(node) { + currentSourceFile = node; + // If the source file requires any helpers and is an external module, and + // the importHelpers compiler option is enabled, emit a synthesized import + // statement for the helpers library. + if (node.flags & 31744 /* EmitHelperFlags */ + && compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); + var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); + var externalHelpersModuleImport = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + externalHelpersModuleImport.parent = node; + externalHelpersModuleImport.flags &= ~8 /* Synthesized */; + statements.push(externalHelpersModuleImport); + currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + currentSourceFileExternalHelpersModuleName = undefined; + node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + node.externalHelpersModuleName = externalHelpersModuleName; + } + else { + node = ts.visitEachChild(node, visitor, context); + } + setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); + return node; + } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ + function shouldEmitDecorateCallForClass(node) { + if (node.decorators && node.decorators.length > 0) { + return true; + } + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter); + } + return false; + } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ + function shouldEmitDecorateCallForParameter(parameter) { + return parameter.decorators !== undefined && parameter.decorators.length > 0; + } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ + function visitClassDeclaration(node) { + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; + var isDecoratedClass = shouldEmitDecorateCallForClass(node); + var classAlias; + // emit name if + // - node has a name + // - node has static initializers + // + var name = node.name; + if (!name && staticProperties.length > 0) { + name = ts.getGeneratedNameForNode(node); + } + var statements = []; + if (!isDecoratedClass) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), + /*location*/ node); + ts.setOriginalNode(classDeclaration, node); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + if (staticProperties.length > 0) { + setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); + } + statements.push(classDeclaration); + } + else { + classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); + } + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (staticProperties.length) { + addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, /*noSourceMaps*/ true)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); + addConstructorDecorationStatement(statements, node, classAlias); + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (isNamespaceExport(node)) { + addExportMemberAssignment(statements, node); + } + else if (isDecoratedClass) { + if (isDefaultExternalModuleExport(node)) { + statements.push(ts.createExportAssignment( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*isExportEquals*/ false, getLocalName(node))); + } + else if (isNamedExternalModuleExport(node)) { + statements.push(createExternalModuleExport(name)); + } + } + return statements; + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param hasExtendsClause A value indicating whether + */ + function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | let C = C_1; + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C_1 = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | let C = C_1; + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C_1 = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | let C = C_1; + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + var location = ts.moveRangePastDecorators(node); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var classExpression = ts.setOriginalNode(ts.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), + /*location*/ location), node); + if (!name) { + name = ts.getGeneratedNameForNode(node); + } + // Record an alias to avoid class double-binding. + var classAlias; + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + } + var declaredName = getDeclarationName(node, /*allowComments*/ true); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var transformedClassExpression = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(classAlias || declaredName, + /*type*/ undefined, classExpression) + ]), + /*location*/ location); + setCommentRange(transformedClassExpression, node); + statements.push(ts.setOriginalNode( + /*node*/ transformedClassExpression, + /*original*/ node)); + if (classAlias) { + // We emit the class alias as a `let` declaration here so that it has the same + // TDZ as the class. + // let ${declaredName} = ${decoratedClassAlias} + statements.push(ts.setOriginalNode(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createLetDeclarationList([ + ts.createVariableDeclaration(declaredName, + /*type*/ undefined, classAlias) + ]), + /*location*/ location), + /*original*/ node)); + } + return classAlias; + } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ + function visitClassExpression(node) { + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, heritageClauses !== undefined); + var classExpression = ts.setOriginalNode(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members, + /*location*/ node), node); + if (staticProperties.length > 0) { + var expressions = []; + var temp = ts.createTempVariable(hoistVariableDeclaration); + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + // record an alias as the class name is not in scope for statics. + enableSubstitutionForClassAliases(); + classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + } + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + expressions.push(ts.startOnNewLine(temp)); + return ts.inlineExpressions(expressions); + } + return classExpression; + } + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + */ + function transformClassMembers(node, hasExtendsClause) { + var members = []; + var constructor = transformConstructor(node, hasExtendsClause); + if (constructor) { + members.push(constructor); + } + ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + return ts.createNodeArray(members, /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + */ + function transformConstructor(node, hasExtendsClause) { + // Check if we have property assignment inside class declaration. + // If there is a 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 + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = node.transformFlags & 131072 /* ContainsParameterPropertyAssignments */; + var constructor = ts.getFirstConstructorWithBody(node); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. + if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { + return ts.visitEachChild(constructor, visitor, context); + } + var parameters = transformConstructorParameters(constructor); + var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body, + /*location*/ constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + */ + function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". + return constructor + ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) + : []; + } + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param parameters The transformed parameters for the constructor. + */ + function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + var statements = []; + var indexOfFirstStatement = 0; + // The body of a constructor is a new lexical environment + startLexicalEnvironment(); + if (constructor) { + indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // + var propertyAssignments = getParametersWithPropertyAssignments(constructor); + ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); + } + else if (hasExtendsClause) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); + addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + } + // End the lexical environment. + ts.addRange(statements, endLexicalEnvironment()); + return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, + /*location*/ constructor ? constructor.body.statements : node.members), + /*location*/ constructor ? constructor.body : undefined), true); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ + function addPrologueDirectivesAndInitialSuperCall(ctor, result) { + if (ctor.body) { + var statements = ctor.body.statements; + // add prologue directives to the list (if any) + var index = ts.addPrologueDirectives(result, statements, /*ensureUseStrict*/ false, visitor); + if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit + return index; + } + var statement = statements[index]; + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + result.push(ts.visitNode(statement, visitor, ts.isStatement)); + return index + 1; + } + return index; + } + return 0; + } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ + function getParametersWithPropertyAssignments(node) { + return ts.filter(node.parameters, isParameterWithPropertyAssignment); + } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ + function isParameterWithPropertyAssignment(parameter) { + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) + && ts.isIdentifier(parameter.name); + } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ + function transformParameterWithPropertyAssignment(node) { + ts.Debug.assert(ts.isIdentifier(node.name)); + var name = node.name; + var propertyName = ts.getMutableClone(name); + setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + var localName = ts.getMutableClone(name); + setNodeEmitFlags(localName, 49152 /* NoComments */); + return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, + /*location*/ node.name), localName), + /*location*/ ts.moveRangePos(node, -1))); + } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ + function getInitializedProperties(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); + } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ + function isStaticInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ true); + } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ + function isInstanceInitializedProperty(member) { + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ + function isInitializedProperty(member, isStatic) { + return member.kind === 145 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) + && member.initializer !== undefined; + } + /** + * Generates assignment statements for property initializers. + * + * @param node The class node. + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function addInitializedPropertyStatements(statements, node, properties, receiver) { + for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { + var property = properties_7[_i]; + var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); + setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + setCommentRange(statement, property); + statements.push(statement); + } + } + /** + * Generates assignment expressions for property initializers. + * + * @param node The class node. + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ + function generateInitializedPropertyExpressions(node, properties, receiver) { + var expressions = []; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var expression = transformInitializedProperty(node, property, receiver); + expression.startsOnNewLine = true; + setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + setCommentRange(expression, property); + expressions.push(expression); + } + return expressions; + } + /** + * Transforms a property initializer into an assignment statement. + * + * @param node The class containing the property. + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ + function transformInitializedProperty(node, property, receiver) { + var propertyName = visitPropertyNameOfClassElement(property); + var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); + return ts.createAssignment(memberAccess, initializer); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member) { + return isDecoratedClassElement(member, /*isStatic*/ true); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member) { + return isDecoratedClassElement(member, /*isStatic*/ false); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic) { + return ts.nodeOrChildIsDecorated(member) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + if (decorators || parameter.decorators) { + if (!decorators) { + decorators = new Array(parameters.length); + } + decorators[i] = parameter.decorators; + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!decorators && !parameters) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(node, member) { + switch (member.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return getAllDecoratorsOfAccessors(node, member); + case 147 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 145 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(node, accessor) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; + if (accessor !== firstAccessor) { + return undefined; + } + var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = method.decorators; + var parameters = getDecoratorsOfParameters(method); + if (!decorators && !parameters) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = property.decorators; + if (!decorators) { + return undefined; + } + return { decorators: decorators }; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(node, allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addTypeMetadata(node, decoratorExpressions); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + var expression = generateClassElementDecorationExpression(node, member); + if (expression) { + if (!expressions) { + expressions = [expression]; + } + else { + expressions.push(expression); + } + } + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = getAllDecoratorsOfClassElement(node, member); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", undefined); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", undefined); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 145 /* PropertyDeclaration */ + ? ts.createVoidZero() + : ts.createNull() + : undefined; + var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + setNodeEmitFlags(helper, 49152 /* NoComments */); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { + var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + if (expression) { + statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node, decoratedClassAlias) { + var allDecorators = getAllDecoratorsOfConstructor(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the class: + // + // @dec + // class C { + // } + // + // The emit for the class is: + // + // C = C_1 = __decorate([dec], C); + // + if (decoratedClassAlias) { + var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); + var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152 /* NoComments */); + return result; + } + else { + var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); + setNodeEmitFlags(result, 49152 /* NoComments */); + return result; + } + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + setNodeEmitFlags(helper, 49152 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ + function addTypeMetadata(node, decoratorExpressions) { + if (USE_NEW_TYPE_METADATA_FORMAT) { + addNewTypeMetadata(node, decoratorExpressions); + } + else { + addOldTypeMetadata(node, decoratorExpressions); + } + } + function addOldTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + if (shouldAddTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + } + if (shouldAddParamTypesMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + } + if (shouldAddReturnTypeMetadata(node)) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + } + } + } + function addNewTypeMetadata(node, decoratorExpressions) { + if (compilerOptions.emitDecoratorMetadata) { + var properties = void 0; + if (shouldAddTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeTypeOfNode(node)))); + } + if (shouldAddParamTypesMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeParameterTypesOfNode(node)))); + } + if (shouldAddReturnTypeMetadata(node)) { + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeReturnTypeOfNode(node)))); + } + if (properties) { + decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); + } + } + } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddTypeMetadata(node) { + var kind = node.kind; + return kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */ + || kind === 145 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddReturnTypeMetadata(node) { + return node.kind === 147 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ + function shouldAddParamTypesMetadata(node) { + var kind = node.kind; + return kind === 221 /* ClassDeclaration */ + || kind === 192 /* ClassExpression */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */; + } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 145 /* PropertyDeclaration */: + case 142 /* Parameter */: + case 149 /* GetAccessor */: + return serializeTypeNode(node.type); + case 150 /* SetAccessor */: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 147 /* MethodDeclaration */: + return ts.createIdentifier("Function"); + default: + return ts.createVoidZero(); + } + } + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 160 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 155 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ + function serializeParameterTypesOfNode(node) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = valueDeclaration.parameters; + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.createArrayLiteral(expressions); + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunctionLike(node)) { + return ts.createIdentifier("Promise"); + } + return ts.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.createIdentifier("Object"); + } + switch (node.kind) { + case 103 /* VoidKeyword */: + return ts.createVoidZero(); + case 164 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 156 /* FunctionType */: + case 157 /* ConstructorType */: + return ts.createIdentifier("Function"); + case 160 /* ArrayType */: + case 161 /* TupleType */: + return ts.createIdentifier("Array"); + case 154 /* TypePredicate */: + case 120 /* BooleanKeyword */: + return ts.createIdentifier("Boolean"); + case 132 /* StringKeyword */: + return ts.createIdentifier("String"); + case 166 /* LiteralType */: + switch (node.literal.kind) { + case 9 /* StringLiteral */: + return ts.createIdentifier("String"); + case 8 /* NumericLiteral */: + return ts.createIdentifier("Number"); + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return ts.createIdentifier("Boolean"); + default: + ts.Debug.failBadSyntaxKind(node.literal); + break; + } + break; + case 130 /* NumberKeyword */: + return ts.createIdentifier("Number"); + case 133 /* SymbolKeyword */: + return languageVersion < 2 /* ES6 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case 155 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 158 /* TypeQuery */: + case 159 /* TypeLiteral */: + case 162 /* UnionType */: + case 163 /* IntersectionType */: + case 117 /* AnyKeyword */: + case 165 /* ThisType */: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + return ts.createIdentifier("Object"); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + case ts.TypeReferenceSerializationKind.Unknown: + var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.createVoidZero(); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return languageVersion < 2 /* ES6 */ + ? getGlobalSymbolNameWithFallback() + : ts.createIdentifier("Symbol"); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + default: + return ts.createIdentifier("Object"); + } + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * entity name at runtime. + */ + function serializeEntityNameAsExpression(node, useFallback) { + switch (node.kind) { + case 69 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name_27 = ts.getMutableClone(node); + name_27.flags &= ~8 /* Synthesized */; + name_27.original = undefined; + name_27.parent = currentScope; + if (useFallback) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_27), ts.createLiteral("undefined")), name_27); + } + return name_27; + case 139 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node, useFallback); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ + function serializeQualifiedNameAsExpression(node, useFallback) { + var left; + if (node.left.kind === 69 /* Identifier */) { + left = serializeEntityNameAsExpression(node.left, useFallback); + } + else if (useFallback) { + var temp = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); + } + else { + left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); + } + return ts.createPropertyAccess(left, node.right); + } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ + function getGlobalSymbolNameWithFallback() { + return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53 /* QuestionToken */), ts.createIdentifier("Symbol"), ts.createToken(54 /* ColonToken */), ts.createIdentifier("Object")); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName + ? ts.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return ts.createLiteral(name.text); + } + else { + return ts.getSynthesizedClone(name); + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + if (member.decorators) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + expression = ts.createAssignment(generatedName, expression); + } + return ts.setOriginalNode(ts.createComputedPropertyName(expression, /*location*/ name), name); + } + else { + return name; + } + } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ + function visitHeritageClause(node) { + if (node.token === 83 /* ExtendsKeyword */) { + var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); + return ts.createHeritageClause(83 /* ExtendsKeyword */, types, node); + } + return undefined; + } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ + function visitExpressionWithTypeArguments(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createExpressionWithTypeArguments( + /*typeArguments*/ undefined, expression, node); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ + function shouldEmitFunctionLikeDeclaration(node) { + return !ts.nodeIsMissing(node.body); + } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, async, public, private, protected, or readonly + * - The node has both a decorator and a computed property name + * + * @param node The method node. + */ + function visitMethodDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + var method = ts.createMethod( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(method, node); + setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(method, node); + return method; + } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ + function shouldEmitAccessorDeclaration(node) { + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has both a decorator and a computed property name + * + * @param node The get accessor node. + */ + function visitGetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createGetAccessor( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), + /*location*/ node); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has both a decorator and a computed property name + * + * @param node The set accessor node. + */ + function visitSetAccessor(node) { + if (!shouldEmitAccessorDeclaration(node)) { + return undefined; + } + var accessor = ts.createSetAccessor( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), + /*location*/ node); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(accessor, node); + setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setOriginalNode(accessor, node); + return accessor; + } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked async + * - The node is exported from a TypeScript namespace + * + * @param node The function node. + */ + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + var func = ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node); + ts.setOriginalNode(func, node); + if (isNamespaceExport(node)) { + var statements = [func]; + addExportMemberAssignment(statements, node); + return statements; + } + return func; + } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The function expression node. + */ + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + var func = ts.createFunctionExpression(node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node); + ts.setOriginalNode(func, node); + return func; + } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node is marked async + */ + function visitArrowFunction(node) { + var func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, node.equalsGreaterThanToken, transformConciseBody(node), + /*location*/ node); + ts.setOriginalNode(func, node); + return func; + } + function transformFunctionBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformFunctionBodyWorker(node.body); + } + function transformFunctionBodyWorker(body, start) { + if (start === void 0) { start = 0; } + var savedCurrentScope = currentScope; + currentScope = body; + startLexicalEnvironment(); + var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); + var visited = ts.updateBlock(body, statements); + var declarations = endLexicalEnvironment(); + currentScope = savedCurrentScope; + return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + } + function transformConciseBody(node) { + if (ts.isAsyncFunctionLike(node)) { + return transformAsyncFunctionBody(node); + } + return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false); + } + function transformConciseBodyWorker(body, forceBlockFunctionBody) { + if (ts.isBlock(body)) { + return transformFunctionBodyWorker(body); + } + else { + startLexicalEnvironment(); + var visited = ts.visitNode(body, visitor, ts.isConciseBody); + var declarations = endLexicalEnvironment(); + var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); + if (forceBlockFunctionBody && !ts.isBlock(merged)) { + return ts.createBlock([ + ts.createReturn(merged) + ]); + } + else { + return merged; + } + } + } + function getPromiseConstructor(type) { + var typeName = ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function transformAsyncFunctionBody(node) { + var promiseConstructor = languageVersion < 2 /* ES6 */ ? getPromiseConstructor(node.type) : undefined; + var isArrowFunction = node.kind === 180 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + var block = ts.createBlock(statements, /*location*/ node.body, /*multiLine*/ true); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= 2 /* ES6 */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + enableSubstitutionForAsyncMethodsWithSuper(); + setNodeEmitFlags(block, 4 /* EmitSuperHelper */); + } + } + return block; + } + else { + return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)); + } + } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ + function visitParameter(node) { + if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + return undefined; + } + var parameter = ts.createParameterDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), + /*location*/ ts.moveRangePastModifiers(node)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setOriginalNode(parameter, node); + setCommentRange(parameter, node); + setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + return parameter; + } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ + function visitVariableStatement(node) { + if (isNamespaceExport(node)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + // elide statement if there are no initialized variables. + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), + /*location*/ node); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + } + else { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), + /*location*/ node); + } + } + /** + * Visits an await expression. + * + * This function will be called any time a TypeScript await expression is encountered. + * + * @param node The await expression node. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node), node); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ + function visitParenthesizedExpression(node) { + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + return ts.createPartiallyEmittedExpression(expression, node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); + return ts.createPartiallyEmittedExpression(expression, node); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ + function shouldEmitEnumDeclaration(node) { + return !ts.isConst(node) + || compilerOptions.preserveConstEnums + || compilerOptions.isolatedModules; + } + function shouldEmitVarForEnumDeclaration(node) { + return !ts.hasModifier(node, 1 /* Export */) + || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + } + /* + * Adds a trailing VariableStatement for an enum or module declaration. + */ + function addVarForEnumExportedFromNamespace(statements, node) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), + /*type*/ undefined, getExportName(node))]); + setSourceMapRange(statement, node); + statements.push(statement); + } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return undefined; + } + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 64 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. + if (shouldEmitVarForEnumDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the enum. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = getExportName(node); + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), + /*location*/ node); + ts.setOriginalNode(enumStatement, node); + setNodeEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + if (isNamespaceExport(node)) { + addVarForEnumExportedFromNamespace(statements, node); + } + return statements; + } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ + function transformEnumBody(node, localName) { + var savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, ts.map(node.members, transformEnumMember)); + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), + /*location*/ undefined, + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ + function transformEnumMember(member) { + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); + return ts.createStatement(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name, + /*location*/ member), + /*location*/ member); + } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ + function transformEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + return ts.createLiteral(value); + } + else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return ts.visitNode(member.initializer, visitor, ts.isExpression); + } + else { + return ts.createVoidZero(); + } + } + } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + function isModuleMergedWithES6Class(node) { + return languageVersion === 2 /* ES6 */ + && ts.isMergedWithClass(node); + } + function isES6ExportedDeclaration(node) { + return isExternalModuleExport(node) + && moduleKind === ts.ModuleKind.ES6; + } + function shouldEmitVarForModuleDeclaration(node) { + return !isModuleMergedWithES6Class(node) + && (!isES6ExportedDeclaration(node) + || ts.isFirstDeclarationOfKind(node, node.kind)); + } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ + function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. + var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) + ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) + : undefined, [ + ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]); + ts.setOriginalNode(statement, /*original*/ node); + // Adjust the source map emit to match the old emitter. + if (node.kind === 224 /* EnumDeclaration */) { + setSourceMapRange(statement.declarationList, node); + } + else { + setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + setCommentRange(statement, node); + setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); + statements.push(statement); + } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return ts.createNotEmittedStatement(node); + } + ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + var statements = []; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 64 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. + if (shouldEmitVarForModuleDeclaration(node)) { + addVarForEnumOrModuleDeclaration(statements, node); + // We should still emit the comments if we are emitting a system module. + if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + emitFlags |= 16384 /* NoLeadingComments */; + } + } + // `parameterName` is the declaration name used inside of the namespace. + var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. + var containerName = getNamespaceContainerName(node); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = getExportName(node); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (ts.hasModifier(node, 1 /* Export */) && !isES6ExportedDeclaration(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = getLocalName(node); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg]), + /*location*/ node); + ts.setOriginalNode(moduleStatement, node); + setNodeEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + return statements; + } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ + function transformModuleBody(node, namespaceLocalName) { + var savedCurrentNamespaceContainerName = currentNamespaceContainerName; + var savedCurrentNamespace = currentNamespace; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + var statements = []; + startLexicalEnvironment(); + var statementsLocation; + var blockLocation; + var body = node.body; + if (body.kind === 226 /* ModuleBlock */) { + ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); + statementsLocation = body.statements; + blockLocation = body; + } + else { + var result = visitModuleDeclaration(body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); + } + ts.addRange(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + var block = ts.createBlock(ts.createNodeArray(statements, + /*location*/ statementsLocation), + /*location*/ blockLocation, + /*multiLine*/ true); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 226 /* ModuleBlock */) { + setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ + function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + return resolver.isReferencedAliasDeclaration(node) + || (!ts.isExternalModule(currentSourceFile) + && resolver.isTopLevelValueImportEqualsWithEntityName(node)); + } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ + function visitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + return ts.visitEachChild(node, visitor, context); + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return undefined; + } + var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); + setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference) + ]), node), node); + } + else { + // exports.${name} = ${moduleReference}; + return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); + } + } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ + function isNamespaceExport(node) { + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ + function isExternalModuleExport(node) { + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); + } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) + && !ts.hasModifier(node, 512 /* Default */); + } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) + && ts.hasModifier(node, 512 /* Default */); + } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ + function expressionToStatement(expression) { + return ts.createStatement(expression, /*location*/ undefined); + } + function addExportMemberAssignment(statements, node) { + var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); + setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var statement = ts.createStatement(expression); + setSourceMapRange(statement, ts.createRange(-1, node.end)); + statements.push(statement); + } + function createNamespaceExport(exportName, exportValue, location) { + return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue), location); + } + function createExternalModuleExport(exportName) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createNamedExports([ + ts.createExportSpecifier(exportName) + ])); + } + function getNamespaceMemberName(name, allowComments, allowSourceMaps) { + var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), /*location*/ name); + var emitFlags; + if (!allowComments) { + emitFlags |= 49152 /* NoComments */; + } + if (!allowSourceMaps) { + emitFlags |= 1536 /* NoSourceMap */; + } + if (emitFlags) { + setNodeEmitFlags(qualifiedName, emitFlags); + } + return qualifiedName; + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return getNamespaceMemberName(name, /*allowComments*/ false, /*allowSourceMaps*/ true); + } + /** + * Gets the declaration name used inside of a namespace or enum. + */ + function getNamespaceParameterName(node) { + var name = ts.getGeneratedNameForNode(node); + setSourceMapRange(name, node.name); + return name; + } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ + function getNamespaceContainerName(node) { + return ts.getGeneratedNameForNode(node); + } + /** + * Gets the local name for a declaration for use in expressions. + * + * A local name will *never* be prefixed with an module or namespace export modifier like + * "exports.". + * + * @param node The declaration. + * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. + * @param allowComments A value indicating whether comments may be emitted for the name. + */ + function getLocalName(node, noSourceMaps, allowComments) { + return getDeclarationName(node, allowComments, !noSourceMaps, 262144 /* LocalName */); + } + /** + * Gets the export name for a declaration for use in expressions. + * + * An export name will *always* be prefixed with an module or namespace export modifier + * like "exports." if one is required. + * + * @param node The declaration. + * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. + * @param allowComments A value indicating whether comments may be emitted for the name. + */ + function getExportName(node, noSourceMaps, allowComments) { + if (isNamespaceExport(node)) { + return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); + } + return getDeclarationName(node, allowComments, !noSourceMaps, 131072 /* ExportName */); + } + /** + * Gets the name for a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + * @param emitFlags Additional NodeEmitFlags to specify for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name) { + var name_28 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536 /* NoSourceMap */; + } + if (!allowComments) { + emitFlags |= 49152 /* NoComments */; + } + if (emitFlags) { + setNodeEmitFlags(name_28, emitFlags); + } + return name_28; + } + else { + return ts.getGeneratedNameForNode(node); + } + } + function getClassPrototype(node) { + return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.hasModifier(member, 32 /* Static */) + ? getDeclarationName(node) + : getClassPrototype(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(69 /* Identifier */); + } + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 4 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(174 /* CallExpression */); + context.enableSubstitution(172 /* PropertyAccessExpression */); + context.enableSubstitution(173 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(221 /* ClassDeclaration */); + context.enableEmitNotification(147 /* MethodDeclaration */); + context.enableEmitNotification(149 /* GetAccessor */); + context.enableEmitNotification(150 /* SetAccessor */); + context.enableEmitNotification(148 /* Constructor */); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(69 /* Identifier */); + // Keep track of class aliases. + classAliases = ts.createMap(); + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(254 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(225 /* ModuleDeclaration */); + } + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 221 /* ClassDeclaration */ + || kind === 148 /* Constructor */ + || kind === 147 /* MethodDeclaration */ + || kind === 149 /* GetAccessor */ + || kind === 150 /* SetAccessor */; + } + function isTransformedModuleDeclaration(node) { + return ts.getOriginalNode(node).kind === 225 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return ts.getOriginalNode(node).kind === 224 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(node, emit) { + var savedApplicableSubstitutions = applicableSubstitutions; + var savedCurrentSuperContainer = currentSuperContainer; + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + currentSuperContainer = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(node, emit); + applicableSubstitutions = savedApplicableSubstitutions; + currentSuperContainer = savedCurrentSuperContainer; + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name_29 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_29); + if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + } + return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + } + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { + switch (node.kind) { + case 174 /* CallExpression */: + return substituteCallExpression(node); + case 172 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) + || trySubstituteNamespaceExportedName(node) + || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; + if (classAlias) { + var clone_4 = ts.getSynthesizedClone(classAlias); + setSourceMapRange(clone_4, node); + setCommentRange(clone_4, node); + return clone_4; + } + } + } + } + return undefined; + } + function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. + if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 225 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 224 /* EnumDeclaration */); + if (substitute) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, /*location*/ node); + } + } + } + return undefined; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 95 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 95 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + } + } + ts.transformTypeScript = transformTypeScript; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES6Module(context) { + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + return ts.visitEachChild(node, visitor, context); + } + return node; + } + function visitor(node) { + switch (node.kind) { + case 230 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 231 /* ImportClause */: + return visitImportClause(node); + case 233 /* NamedImports */: + case 232 /* NamespaceImport */: + return visitNamedBindings(node); + case 234 /* ImportSpecifier */: + return visitImportSpecifier(node); + case 235 /* ExportAssignment */: + return visitExportAssignment(node); + case 236 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 237 /* NamedExports */: + return visitNamedExports(node); + case 238 /* ExportSpecifier */: + return visitExportSpecifier(node); + } + return node; + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; // do not emit export equals for ES6 + } + var original = ts.getOriginalNode(node); + return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true); + if (node.exportClause === newExportClause) { + return node; + } + return newExportClause + ? ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, newExportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); + if (node.elements === newExports) { + return node; + } + return newExports.length ? ts.createNamedExports(newExports) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + function visitImportEqualsDeclaration(node) { + return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitImportDeclaration(node) { + if (node.importClause) { + var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); + if (!newImportClause.name && !newImportClause.namedBindings) { + return undefined; + } + else if (newImportClause !== node.importClause) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, newImportClause, node.moduleSpecifier); + } + } + return node; + } + function visitImportClause(node) { + var newDefaultImport = node.name; + if (!resolver.isReferencedAliasDeclaration(node)) { + newDefaultImport = undefined; + } + var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true); + return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings + ? ts.createImportClause(newDefaultImport, newNamedBindings) + : node; + } + function visitNamedBindings(node) { + if (node.kind === 232 /* NamespaceImport */) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); + if (!newNamedImportElements || newNamedImportElements.length == 0) { + return undefined; + } + if (newNamedImportElements === node.elements) { + return node; + } + return ts.createNamedImports(newNamedImportElements); + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + } + ts.transformES6Module = transformES6Module; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(187 /* BinaryExpression */); + context.enableSubstitution(185 /* PrefixUnaryExpression */); + context.enableSubstitution(186 /* PostfixUnaryExpression */); + context.enableEmitNotification(256 /* SourceFile */); + var exportFunctionForFileMap = []; + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var hasExportStarsToExportValues; + var exportFunctionForFile; + var contextObjectForFile; + var exportedLocalNames; + var exportedFunctionDeclarations; + var enclosingBlockScopedContainer; + var currentParent; + var currentNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + currentNode = node; + // Perform the transformation. + var updated = transformSystemModuleWorker(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + exportedLocalNames = undefined; + exportedFunctionDeclarations = undefined; + return updated; + } + return node; + } + function transformSystemModuleWorker(node) { + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + ts.Debug.assert(!exportFunctionForFile); + // Collect information about the external module and dependency groups. + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunctionForFile = ts.createUniqueName("exports"); + contextObjectForFile = ts.createUniqueName("context"); + exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; + var dependencyGroups = collectDependencyGroups(externalImports); + var statements = []; + // Add the body of the module. + addSystemModuleBody(statements, node, dependencyGroups); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); + var body = ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(exportFunctionForFile), + ts.createParameter(contextObjectForFile) + ], + /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, body] + : [dependencies, body])) + ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); + var _a; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param statements The output statements for the module body. + * @param node The source file for the module. + * @param statementOffset The offset at which to begin visiting the statements of the SourceFile. + */ + function addSystemModuleBody(statements, node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // var file_1; // local alias + // var y; + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitSourceElement); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) + ]))); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); + // We emit the lexical environment (hoisted variables and function declarations) + // early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + // - Calls to the exporter for exported function declarations are grouped after + // the declarations. + ts.addRange(statements, endLexicalEnvironment()); + // Emit early exports for function declarations. + ts.addRange(statements, exportedFunctionDeclarations); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, + /*location*/ undefined, + /*multiLine*/ true))) + ]), + /*multiLine*/ true))); + } + function addExportStarIfNeeded(statements) { + if (!hasExportStarsToExportValues) { + return; + } + // 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. + // local names set should only be added if we have anything exported + if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; + if (externalImport.kind === 236 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + return addExportStarFunction(statements, /*localNames*/ undefined); + } + } + var exportedNames = []; + if (exportedLocalNames) { + for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { + var exportedLocalName = exportedLocalNames_1[_a]; + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); + } + } + for (var _b = 0, externalImports_2 = externalImports; _b < externalImports_2.length; _b++) { + var externalImport = externalImports_2[_b]; + if (externalImport.kind !== 236 /* ExportDeclaration */) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + // export * from ... + continue; + } + for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { + var element = _d[_c]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true)) + ]))); + return addExportStarFunction(statements, exportedNamesStorageRef); + } + /** + * Emits a setter callback for each dependency group. + * @param write The callback used to write each callback. + */ + function generateSetters(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 230 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // fall-through + case 229 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 236 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true); + } + function visitSourceElement(node) { + switch (node.kind) { + case 230 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 236 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 235 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return visitNestedNode(node); + } + } + function visitNestedNode(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var currentGrandparent = currentParent; + currentParent = currentNode; + currentNode = node; + if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { + enclosingBlockScopedContainer = currentParent; + } + var result = visitNestedNodeWorker(node); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return result; + } + function visitNestedNodeWorker(node) { + switch (node.kind) { + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 221 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 206 /* ForStatement */: + return visitForStatement(node); + case 207 /* ForInStatement */: + return visitForInStatement(node); + case 208 /* ForOfStatement */: + return visitForOfStatement(node); + case 204 /* DoStatement */: + return visitDoStatement(node); + case 205 /* WhileStatement */: + return visitWhileStatement(node); + case 214 /* LabeledStatement */: + return visitLabeledStatement(node); + case 212 /* WithStatement */: + return visitWithStatement(node); + case 213 /* SwitchStatement */: + return visitSwitchStatement(node); + case 227 /* CaseBlock */: + return visitCaseBlock(node); + case 249 /* CaseClause */: + return visitCaseClause(node); + case 250 /* DefaultClause */: + return visitDefaultClause(node); + case 216 /* TryStatement */: + return visitTryStatement(node); + case 252 /* CatchClause */: + return visitCatchClause(node); + case 199 /* Block */: + return visitBlock(node); + case 202 /* ExpressionStatement */: + return visitExpressionStatement(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + if (node.importClause && ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + return undefined; + } + function visitImportEqualsDeclaration(node) { + if (ts.contains(externalImports, node)) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + // NOTE(rbuckton): Do we support export import = require('') in System? + return undefined; + } + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + var statements = []; + ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); + return statements; + } + return undefined; + } + function visitExportSpecifier(specifier) { + if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) + || resolver.isValueAliasDeclaration(specifier)) { + recordExportName(specifier.name); + return createExportStatement(specifier.name, specifier.propertyName || specifier.name); + } + return undefined; + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + return createExportStatement(ts.createLiteral("default"), node.expression); + } + } + return undefined; + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The variable statement to visit. + */ + function visitVariableStatement(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3 /* BlockScoped */) == 0) || + enclosingBlockScopedContainer.kind === 256 /* SourceFile */; + if (!shouldHoist) { + return node; + } + var isExported = ts.hasModifier(node, 1 /* Export */); + var expressions = []; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, isExported); + if (visited) { + expressions.push(visited); + } + } + if (expressions.length) { + return ts.createStatement(ts.inlineExpressions(expressions), node); + } + return undefined; + } + /** + * Transforms a VariableDeclaration into one or more assignment expressions. + * + * @param node The VariableDeclaration to transform. + * @param isExported A value used to indicate whether the containing statement was exported. + */ + function transformVariable(node, isExported) { + // Hoist any bound names within the declaration. + hoistBindingElement(node, isExported); + if (!node.initializer) { + // If the variable has no initializer, ignore it. + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + // If the variable has an IdentifierName, write out an assignment expression in its place. + return ts.createAssignment(name, node.initializer); + } + else { + // If the variable has a BindingPattern, flatten the variable into multiple assignment expressions. + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The function declaration to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + // If the function is exported, ensure it has a name and rewrite the function without any export flags. + var name_30 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.asteriskToken, name_30, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, node.body, + /*location*/ node); + // Record a declaration export in the outer module body function. + recordExportedFunctionDeclaration(node); + if (!ts.hasModifier(node, 512 /* Default */)) { + recordExportName(name_30); + } + ts.setOriginalNode(newNode, node); + node = newNode; + } + // Hoist the function declaration to the outer module body function. + hoistFunctionDeclaration(node); + return undefined; + } + function visitExpressionStatement(node) { + var originalNode = ts.getOriginalNode(node); + if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { + var name_31 = getDeclarationName(originalNode); + // We only need to hoistVariableDeclaration for EnumDeclaration + // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement + // which then call transformsVariable for each declaration in declarationList + if (originalNode.kind === 224 /* EnumDeclaration */) { + hoistVariableDeclaration(name_31); + } + return [ + node, + createExportStatement(name_31, name_31) + ]; + } + return node; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The class declaration to visit. + */ + function visitClassDeclaration(node) { + // Hoist the name of the class declaration to the outer module body function. + var name = getDeclarationName(node); + hoistVariableDeclaration(name); + var statements = []; + // Rewrite the class declaration into an assignment of a class expression. + statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, node.heritageClauses, node.members, + /*location*/ node)), + /*location*/ node)); + // If the class was exported, write a declaration export to the inner module body function. + if (ts.hasModifier(node, 1 /* Export */)) { + if (!ts.hasModifier(node, 512 /* Default */)) { + recordExportName(name); + } + statements.push(createDeclarationExport(node)); + } + return statements; + } + function shouldHoistLoopInitializer(node) { + return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) === 0; + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitForStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var expressions = []; + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + var visited = transformVariable(variable, /*isExported*/ false); + if (visited) { + expressions.push(visited); + } + } + ; + return ts.createFor(expressions.length + ? ts.inlineExpressions(expressions) + : ts.createSynthesizedNode(193 /* OmittedExpression */), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), + /*location*/ node); + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + /** + * Transforms and hoists the declaration list of a ForInStatement or ForOfStatement into an expression. + * + * @param node The decalaration list to transform. + */ + function transformForBinding(node) { + var firstDeclaration = ts.firstOrUndefined(node.declarations); + hoistBindingElement(firstDeclaration, /*isExported*/ false); + var name = firstDeclaration.name; + return ts.isIdentifier(name) + ? name + : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitForInStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitForOfStatement(node) { + var initializer = node.initializer; + if (shouldHoistLoopInitializer(initializer)) { + var updated = ts.getMutableClone(node); + updated.initializer = transformForBinding(initializer); + updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + return updated; + } + else { + return ts.visitEachChild(node, visitNestedNode, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitDoStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitWhileStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitLabeledStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitWithStatement(node) { + var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); + if (statement !== node.statement) { + var updated = ts.getMutableClone(node); + updated.statement = statement; + return updated; + } + return node; + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitSwitchStatement(node) { + var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); + if (caseBlock !== node.caseBlock) { + var updated = ts.getMutableClone(node); + updated.caseBlock = caseBlock; + return updated; + } + return node; + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); + if (clauses !== node.clauses) { + var updated = ts.getMutableClone(node); + updated.clauses = clauses; + return updated; + } + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The clause to visit. + */ + function visitCaseClause(node) { + var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); + if (statements !== node.statements) { + var updated = ts.getMutableClone(node); + updated.statements = statements; + return updated; + } + return node; + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The clause to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The statement to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The clause to visit. + */ + function visitCatchClause(node) { + var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); + if (block !== node.block) { + var updated = ts.getMutableClone(node); + updated.block = block; + return updated; + } + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The block to visit. + */ + function visitBlock(node) { + return ts.visitEachChild(node, visitNestedNode, context); + } + // + // Substitutions + // + function onEmitNode(node, emit) { + if (node.kind === 256 /* SourceFile */) { + exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + exportFunctionForFile = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + case 187 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 185 /* PrefixUnaryExpression */: + case 186 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for identifiers exported at the top level of a module. + */ + function substituteExpressionIdentifier(node) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + var importBinding = createImportBinding(importDeclaration); + if (importBinding) { + return importBinding; + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return substituteAssignmentExpression(node); + } + return node; + } + function substituteAssignmentExpression(node) { + setNodeEmitFlags(node, 128 /* NoSubstitution */); + var left = node.left; + switch (left.kind) { + case 69 /* Identifier */: + var exportDeclaration = resolver.getReferencedExportContainer(left); + if (exportDeclaration) { + return createExportExpression(left, node); + } + break; + case 171 /* ObjectLiteralExpression */: + case 170 /* ArrayLiteralExpression */: + if (hasExportedReferenceInDestructuringPattern(left)) { + return substituteDestructuring(node); + } + break; + } + return node; + } + function isExportedBinding(name) { + var container = resolver.getReferencedExportContainer(name); + return container && container.kind === 256 /* SourceFile */; + } + function hasExportedReferenceInDestructuringPattern(node) { + switch (node.kind) { + case 69 /* Identifier */: + return isExportedBinding(node); + case 171 /* ObjectLiteralExpression */: + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (hasExportedReferenceInObjectDestructuringElement(property)) { + return true; + } + } + break; + case 170 /* ArrayLiteralExpression */: + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (hasExportedReferenceInArrayDestructuringElement(element)) { + return true; + } + } + break; + } + return false; + } + function hasExportedReferenceInObjectDestructuringElement(node) { + if (ts.isShorthandPropertyAssignment(node)) { + return isExportedBinding(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringElement(node.initializer); + } + else { + return false; + } + } + function hasExportedReferenceInArrayDestructuringElement(node) { + if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else { + return hasExportedReferenceInDestructuringElement(node); + } + } + function hasExportedReferenceInDestructuringElement(node) { + if (ts.isBinaryExpression(node)) { + var left = node.left; + return node.operatorToken.kind === 56 /* EqualsToken */ + && isDestructuringPattern(left) + && hasExportedReferenceInDestructuringPattern(left); + } + else if (ts.isIdentifier(node)) { + return isExportedBinding(node); + } + else if (ts.isSpreadElementExpression(node)) { + var expression = node.expression; + return ts.isIdentifier(expression) && isExportedBinding(expression); + } + else if (isDestructuringPattern(node)) { + return hasExportedReferenceInDestructuringPattern(node); + } + else { + return false; + } + } + function isDestructuringPattern(node) { + var kind = node.kind; + return kind === 69 /* Identifier */ + || kind === 171 /* ObjectLiteralExpression */ + || kind === 170 /* ArrayLiteralExpression */; + } + function substituteDestructuring(node) { + return ts.flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration); + } + function substituteUnaryExpression(node) { + var operand = node.operand; + var operator = node.operator; + var substitute = ts.isIdentifier(operand) && + (node.kind === 186 /* PostfixUnaryExpression */ || + (node.kind === 185 /* PrefixUnaryExpression */ && (operator === 41 /* PlusPlusToken */ || operator === 42 /* MinusMinusToken */))); + if (substitute) { + var exportDeclaration = resolver.getReferencedExportContainer(operand); + if (exportDeclaration) { + var expr = ts.createPrefix(node.operator, operand, node); + setNodeEmitFlags(expr, 128 /* NoSubstitution */); + var call = createExportExpression(operand, expr); + if (node.kind === 185 /* PrefixUnaryExpression */) { + return call; + } + else { + // export function returns the value that was passes as the second argument + // however for postfix unary expressions result value should be the value before modification. + // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' + return operator === 41 /* PlusPlusToken */ + ? ts.createSubtract(call, ts.createLiteral(1)) + : ts.createAdd(call, ts.createLiteral(1)); + } + } + } + return node; + } + /** + * Gets a name to use for a DeclarationStatement. + * @param node The declaration statement. + */ + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function addExportStarFunction(statements, localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); + } + statements.push(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) + ])), + ts.createStatement(ts.createCall(exportFunctionForFile, + /*typeArguments*/ undefined, [exports])) + ], + /*location*/ undefined, + /*multiline*/ true))); + return exportStarFunction; + } + /** + * Creates a call to the current file's export function to export a value. + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; + return ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exportName, value]); + } + /** + * Creates a call to the current file's export function to export a value. + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportStatement(name, value) { + return ts.createStatement(createExportExpression(name, value)); + } + /** + * Creates a call to the current file's export function to export a declaration. + * @param node The declaration to export. + */ + function createDeclarationExport(node) { + var declarationName = getDeclarationName(node); + var exportName = ts.hasModifier(node, 512 /* Default */) ? ts.createLiteral("default") : declarationName; + return createExportStatement(exportName, declarationName); + } + function createImportBinding(importDeclaration) { + var importAlias; + var name; + if (ts.isImportClause(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); + name = ts.createIdentifier("default"); + } + else if (ts.isImportSpecifier(importDeclaration)) { + importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); + name = importDeclaration.propertyName || importDeclaration.name; + } + else { + return undefined; + } + if (name.originalKeywordKind && languageVersion === 0 /* ES3 */) { + return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); + } + else { + return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); + } + } + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + // deduplicate/group entries in dependency list by the dependency name + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + continue; + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + function getNameOfDependencyGroup(dependencyGroup) { + return dependencyGroup.name; + } + function recordExportName(name) { + if (!exportedLocalNames) { + exportedLocalNames = []; + } + exportedLocalNames.push(name); + } + function recordExportedFunctionDeclaration(node) { + if (!exportedFunctionDeclarations) { + exportedFunctionDeclarations = []; + } + exportedFunctionDeclarations.push(createDeclarationExport(node)); + } + function hoistBindingElement(node, isExported) { + if (ts.isOmittedExpression(node)) { + return; + } + var name = node.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + if (isExported) { + recordExportName(name); + } + } + else if (ts.isBindingPattern(name)) { + ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + } + } + function hoistExportedBindingElement(node) { + hoistBindingElement(node, /*isExported*/ true); + } + function hoistNonExportedBindingElement(node) { + hoistBindingElement(node, /*isExported*/ false); + } + function updateSourceFile(node, statements, nodeEmitFlags) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + setNodeEmitFlags(updated, nodeEmitFlags); + return updated; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(187 /* BinaryExpression */); + context.enableSubstitution(185 /* PrefixUnaryExpression */); + context.enableSubstitution(186 /* PostfixUnaryExpression */); + context.enableSubstitution(254 /* ShorthandPropertyAssignment */); + context.enableEmitNotification(256 /* SourceFile */); + var currentSourceFile; + var externalImports; + var exportSpecifiers; + var exportEquals; + var bindingNameExportSpecifiersMap; + // Subset of exportSpecifiers that is a binding-name. + // This is to reduce amount of memory we have to keep around even after we done with module-transformer + var bindingNameExportSpecifiersForFileMap = ts.createMap(); + var hasExportStarsToExportValues; + return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + currentSourceFile = node; + // Collect information about the external module. + (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); + // Perform the transformation. + var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule_1(node); + ts.aggregateTransformFlags(updated); + currentSourceFile = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = false; + return updated; + } + return node; + var _a; + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + var updated = updateSourceFile(node, statements); + if (hasExportStarsToExportValues) { + setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); + } + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true); + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var define = ts.createIdentifier("define"); + setNodeEmitFlags(define, 16 /* UMDDefine */); + return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); + } + /** + * Transforms a SourceFile into an AMD or UMD module. + * + * @param node The SourceFile node. + * @param define The expression used to define the module. + * @param moduleName An expression for the module name, if available. + * @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies. + */ + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + return updateSourceFile(node, [ + ts.createStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter("require"), + ts.createParameter("exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ]); + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); + // Visit each statement of the module body. + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addRange(statements, endLexicalEnvironment()); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + var body = ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); + if (hasExportStarsToExportValues) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + setNodeEmitFlags(body, 2 /* EmitExportStar */); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (emitAsReturn) { + var statement = ts.createReturn(exportEquals.expression, + /*location*/ exportEquals); + setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), + /*location*/ exportEquals); + setNodeEmitFlags(statement, 49152 /* NoComments */); + statements.push(statement); + } + } + } + /** + * Visits a node at the top level of the source file. + * + * @param node The node. + */ + function visitor(node) { + switch (node.kind) { + case 230 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 229 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 236 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 235 /* ExportAssignment */: + return visitExportAssignment(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 221 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 202 /* ExpressionStatement */: + return visitExpressionStatement(node); + default: + // This visitor does not descend into the tree, as export/import statements + // are only transformed at the top level of a file. + return node; + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The ImportDeclaration node. + */ + function visitImportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var statements = []; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + statements.push(ts.createStatement(createRequireCall(node), + /*location*/ node)); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, createRequireCall(node))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createConstDeclarationList(variables), + /*location*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node), + /*location*/ node) + ]))); + } + addExportImportAssignments(statements, node); + return ts.singleOrMany(statements); + } + function visitImportEqualsDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + // Set emitFlags on the name of the importEqualsDeclaration + // This is so the printer will not substitute the identifier + setNodeEmitFlags(node.name, 128 /* NoSubstitution */); + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), + /*location*/ node)); + } + else { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*location*/ undefined, + /*flags*/ languageVersion >= 2 /* ES6 */ ? 2 /* Const */ : 0 /* None */), + /*location*/ node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.createStatement(createExportAssignment(node.name, node.name), + /*location*/ node)); + } + } + addExportImportAssignments(statements, node); + return statements; + } + function visitExportDeclaration(node) { + if (!ts.contains(externalImports, node)) { + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ]), + /*location*/ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + if (resolver.isValueAliasDeclaration(specifier)) { + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), + /*location*/ specifier)); + } + } + return ts.singleOrMany(statements); + } + else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + // export * from "mod"; + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), + /*typeArguments*/ undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), + /*location*/ node); + } + } + function visitExportAssignment(node) { + if (!node.isExportEquals) { + if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { + var statements = []; + addExportDefault(statements, node.expression, /*location*/ node); + return statements; + } + } + return undefined; + } + function addExportDefault(statements, expression, location) { + tryAddExportDefaultCompat(statements); + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); + } + function tryAddExportDefaultCompat(statements) { + var original = ts.getOriginalNode(currentSourceFile); + ts.Debug.assert(original.kind === 256 /* SourceFile */); + if (!original.symbol.exports["___esModule"]) { + if (languageVersion === 0 /* ES3 */) { + statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + function addExportImportAssignments(statements, node) { + if (ts.isImportEqualsDeclaration(node)) { + addExportMemberAssignments(statements, node.name); + } + else { + var names = ts.reduceEachChild(node, collectExportMembers, []); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_32 = names_1[_i]; + addExportMemberAssignments(statements, name_32); + } + } + } + function collectExportMembers(names, node) { + if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { + var name_33 = node.name; + if (ts.isIdentifier(name_33)) { + names.push(name_33); + } + } + return ts.reduceEachChild(node, collectExportMembers, names); + } + function addExportMemberAssignments(statements, name) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), + /*location*/ specifier.name))); + } + } + } + function addExportMemberAssignment(statements, node) { + if (ts.hasModifier(node, 512 /* Default */)) { + addExportDefault(statements, getDeclarationName(node), /*location*/ node); + } + else { + statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); + } + } + function visitVariableStatement(node) { + // If the variable is for a generated declaration, + // we should maintain it and just strip off the 'export' modifier if necessary. + var originalKind = ts.getOriginalNode(node).kind; + if (originalKind === 225 /* ModuleDeclaration */ || + originalKind === 224 /* EnumDeclaration */ || + originalKind === 221 /* ClassDeclaration */) { + if (!ts.hasModifier(node, 1 /* Export */)) { + return node; + } + return ts.setOriginalNode(ts.createVariableStatement( + /*modifiers*/ undefined, node.declarationList), node); + } + var resultStatements = []; + // If we're exporting these variables, then these just become assignments to 'exports.blah'. + // We only want to emit assignments for variables with initializers. + if (ts.hasModifier(node, 1 /* Export */)) { + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length > 0) { + var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); + resultStatements.push(inlineAssignments); + } + } + else { + resultStatements.push(node); + } + // While we might not have been exported here, each variable might have been exported + // later on in an export specifier (e.g. `export {foo as blah, bar}`). + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + addExportMemberAssignmentsForBindingName(resultStatements, decl.name); + } + return resultStatements; + } + /** + * Creates appropriate assignments for each binding identifier that is exported in an export specifier, + * and inserts it into 'resultStatements'. + */ + function addExportMemberAssignmentsForBindingName(resultStatements, name) { + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + addExportMemberAssignmentsForBindingName(resultStatements, element.name); + } + } + } + else { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + var sourceFileId = ts.getOriginalNodeId(currentSourceFile); + if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { + bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); + } + bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; + addExportMemberAssignments(resultStatements, name); + } + } + } + function transformInitializedVariable(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); + } + else { + return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + } + function visitFunctionDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, node.body, + /*location*/ node), + /*original*/ node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + if (node.name) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitClassDeclaration(node) { + var statements = []; + var name = node.name || ts.getGeneratedNameForNode(node); + if (ts.hasModifier(node, 1 /* Export */)) { + statements.push(ts.setOriginalNode(ts.createClassDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, node.heritageClauses, node.members, + /*location*/ node), + /*original*/ node)); + addExportMemberAssignment(statements, node); + } + else { + statements.push(node); + } + // Decorators end up creating a series of assignment expressions which overwrite + // the local binding that we export, so we need to defer from exporting decorated classes + // until the decoration assignments take place. We do this when visiting expression-statements. + if (node.name && !(node.decorators && node.decorators.length)) { + addExportMemberAssignments(statements, node.name); + } + return ts.singleOrMany(statements); + } + function visitExpressionStatement(node) { + var original = ts.getOriginalNode(node); + var origKind = original.kind; + if (origKind === 224 /* EnumDeclaration */ || origKind === 225 /* ModuleDeclaration */) { + return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); + } + else if (origKind === 221 /* ClassDeclaration */) { + // The decorated assignment for a class name may need to be transformed. + var classDecl = original; + if (classDecl.name) { + var statements = [node]; + addExportMemberAssignments(statements, classDecl.name); + return statements; + } + } + return node; + } + function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { + var statements = [node]; + // Preserve old behavior for enums in which a variable statement is emitted after the body itself. + if (ts.hasModifier(original, 1 /* Export */) && + original.kind === 224 /* EnumDeclaration */ && + ts.isFirstDeclarationOfKind(original, 224 /* EnumDeclaration */)) { + addVarForExportedEnumOrNamespaceDeclaration(statements, original); + } + addExportMemberAssignments(statements, original.name); + return statements; + } + /** + * Adds a trailing VariableStatement for an enum or module declaration. + */ + function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { + var transformedStatement = ts.createVariableStatement( + /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), + /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], + /*location*/ node); + setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); + statements.push(transformedStatement); + } + function getDeclarationName(node) { + return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + } + function onEmitNode(node, emit) { + if (node.kind === 256 /* SourceFile */) { + bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; + previousOnEmitNode(node, emit); + bindingNameExportSpecifiersMap = undefined; + } + else { + previousOnEmitNode(node, emit); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, /*location*/ node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, /*location*/ node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + case 187 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 186 /* PostfixUnaryExpression */: + case 185 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteExportedName(node) + || trySubstituteImportedName(node) + || node; + } + function substituteBinaryExpression(node) { + var left = node.left; + // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier + if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { + setNodeEmitFlags(node, 128 /* NoSubstitution */); + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, node); + } + return nestedExportAssignment; + } + } + return node; + } + function substituteUnaryExpression(node) { + // Because how the compiler only parse plusplus and minusminus to be either prefixUnaryExpression or postFixUnaryExpression depended on where they are + // We don't need to check that the operator has SyntaxKind.plusplus or SyntaxKind.minusminus + var operator = node.operator; + var operand = node.operand; + if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { + if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { + setNodeEmitFlags(node, 128 /* NoSubstitution */); + var transformedUnaryExpression = void 0; + if (node.kind === 186 /* PostfixUnaryExpression */) { + transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), + /*location*/ node); + // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here + setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); + } + var nestedExportAssignment = void 0; + for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { + var specifier = _a[_i]; + nestedExportAssignment = nestedExportAssignment ? + createExportAssignment(specifier.name, nestedExportAssignment) : + createExportAssignment(specifier.name, transformedUnaryExpression || node); + } + return nestedExportAssignment; + } + } + return node; + } + function trySubstituteExportedName(node) { + var emitFlags = getNodeEmitFlags(node); + if ((emitFlags & 262144 /* LocalName */) === 0) { + var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); + if (container) { + if (container.kind === 256 /* SourceFile */) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), + /*location*/ node); + } + } + } + return undefined; + } + function trySubstituteImportedName(node) { + if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (ts.isImportClause(declaration)) { + if (languageVersion >= 1 /* ES5 */) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), + /*location*/ node); + } + else { + // TODO: ES3 transform to handle x.default -> x["default"] + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), + /*location*/ node); + } + } + else if (ts.isImportSpecifier(declaration)) { + var name_34 = declaration.propertyName || declaration.name; + if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { + // TODO: ES3 transform to handle x.default -> x["default"] + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), + /*location*/ node); + } + else { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), + /*location*/ node); + } + } + } + } + return undefined; + } + function getModuleMemberName(name) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), name, + /*location*/ name); + } + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (ts.isDefined(moduleName)) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + function createExportStatement(name, value, location) { + var statement = ts.createStatement(createExportAssignment(name, value)); + statement.startsOnNewLine = true; + if (location) { + setSourceMapRange(statement, location); + } + return statement; + } + function createExportAssignment(name, value) { + return ts.createAssignment(name.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion === 0 /* ES3 */ + ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) + : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { + var importNode = externalImports_3[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function updateSourceFile(node, statements) { + var updated = ts.getMutableClone(node); + updated.statements = ts.createNodeArray(statements, node.statements); + return updated; + } + var _a; + } + ts.transformModule = transformModule; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var entities = createEntitiesMap(); + function transformJsx(context) { + var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; + return transformSourceFile; + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ + function transformSourceFile(node) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + return node; + } + function visitor(node) { + if (node.transformFlags & 4 /* Jsx */) { + return visitorWorker(node); + } + else if (node.transformFlags & 8 /* ContainsJsx */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 241 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 242 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 248 /* JsxExpression */: + return visitJsxExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 244 /* JsxText */: + return visitJsxText(node); + case 248 /* JsxExpression */: + return visitJsxExpression(node); + case 241 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 242 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + default: + ts.Debug.failBadSyntaxKind(node); + return undefined; + } + } + function visitJsxElement(node, isChild) { + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); + } + function visitJsxSelfClosingElement(node, isChild) { + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxOpeningLikeElement(node, children, isChild, location) { + var tagName = getTagName(node); + var objectProperties; + var attrs = node.attributes; + if (attrs.length === 0) { + // When there are no attributes, React wants "null" + objectProperties = ts.createNull(); + } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. + segments.unshift(ts.createObjectLiteral()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments) + || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + } + var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function transformJsxAttributeToObjectLiteralElement(node) { + var name = getAttributeName(node); + var expression = transformJsxAttributeInitializer(node.initializer); + return ts.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === undefined) { + return ts.createLiteral(true); + } + else if (node.kind === 9 /* StringLiteral */) { + var decoded = tryDecodeEntities(node.text); + return decoded ? ts.createLiteral(decoded, /*location*/ node) : node; + } + else if (node.kind === 248 /* JsxExpression */) { + return visitJsxExpression(node); + } + else { + ts.Debug.failBadSyntaxKind(node); + } + } + function visitJsxText(node) { + var text = ts.getTextOfNode(node, /*includeTrivia*/ true); + var parts; + var firstNonWhitespace = 0; + var lastNonWhitespace = -1; + // JSX trims whitespace at the end and beginning of lines, except that the + // start/end of a tag is considered a start/end of a line only if that line is + // on the same line as the closing tag. See examples in + // tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { + var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + if (!parts) { + parts = []; + } + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + parts.push(ts.createLiteral(decodeEntities(part))); + } + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpace(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + if (firstNonWhitespace !== -1) { + var part = text.substr(firstNonWhitespace); + if (!parts) { + parts = []; + } + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. + parts.push(ts.createLiteral(decodeEntities(part))); + } + if (parts) { + return ts.reduceLeft(parts, aggregateJsxTextParts); + } + return undefined; + } + /** + * Aggregates two expressions by interpolating them with a whitespace literal. + */ + function aggregateJsxTextParts(left, right) { + return ts.createAdd(ts.createAdd(left, ts.createLiteral(" ")), right); + } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { + if (decimal) { + return String.fromCharCode(parseInt(decimal, 10)); + } + else if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + else { + var ch = entities[word]; + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) + return ch ? String.fromCharCode(ch) : match; + } + }); + } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ + function tryDecodeEntities(text) { + var decoded = decodeEntities(text); + return decoded === text ? undefined : decoded; + } + function getTagName(node) { + if (node.kind === 241 /* JsxElement */) { + return getTagName(node.openingElement); + } + else { + var name_35 = node.tagName; + if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { + return ts.createLiteral(name_35.text); + } + else { + return ts.createExpressionFromEntityName(name_35); + } + } + } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ + function getAttributeName(node) { + var name = node.name; + if (/^[A-Za-z_]\w*$/.test(name.text)) { + return name; + } + else { + return ts.createLiteral(name.text); + } + } + function visitJsxExpression(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + } + ts.transformJsx = transformJsx; + function createEntitiesMap() { + return ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); + } +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES7(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + return transformSourceFile; + function transformSourceFile(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if (node.transformFlags & 16 /* ES7 */) { + return visitorWorker(node); + } + else if (node.transformFlags & 32 /* ContainsES7 */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 187 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + // We are here because ES7 adds support for the exponentiation operator. + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { + var target = void 0; + var value = void 0; + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), + /*location*/ left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, + /*location*/ left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), left.name, + /*location*/ left); + value = ts.createPropertyAccess(expressionTemp, left.name, + /*location*/ left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node), /*location*/ node); + } + else if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */) { + // Transforms `a ** b` into `Math.pow(a, b)` + return ts.createMathPow(left, right, /*location*/ node); + } + else { + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + } + ts.transformES7 = transformES7; +})(ts || (ts = {})); +/// +/// +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ +var ts; +(function (ts) { + var OpCode; + (function (OpCode) { + OpCode[OpCode["Nop"] = 0] = "Nop"; + OpCode[OpCode["Statement"] = 1] = "Statement"; + OpCode[OpCode["Assign"] = 2] = "Assign"; + OpCode[OpCode["Break"] = 3] = "Break"; + OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; + OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; + OpCode[OpCode["Yield"] = 6] = "Yield"; + OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; + OpCode[OpCode["Return"] = 8] = "Return"; + OpCode[OpCode["Throw"] = 9] = "Throw"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block + })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder + var BlockAction; + (function (BlockAction) { + BlockAction[BlockAction["Open"] = 0] = "Open"; + BlockAction[BlockAction["Close"] = 1] = "Close"; + })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder + var CodeBlockKind; + (function (CodeBlockKind) { + CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; + CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; + CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; + CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; + CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; + })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block + var ExceptionBlockState; + (function (ExceptionBlockState) { + ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; + ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; + ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; + ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; + })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. + var Instruction; + (function (Instruction) { + Instruction[Instruction["Next"] = 0] = "Next"; + Instruction[Instruction["Throw"] = 1] = "Throw"; + Instruction[Instruction["Return"] = 2] = "Return"; + Instruction[Instruction["Break"] = 3] = "Break"; + Instruction[Instruction["Yield"] = 4] = "Yield"; + Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; + Instruction[Instruction["Catch"] = 6] = "Catch"; + Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; + })(Instruction || (Instruction = {})); + var instructionNames = ts.createMap((_a = {}, + _a[2 /* Return */] = "return", + _a[3 /* Break */] = "break", + _a[4 /* Yield */] = "yield", + _a[5 /* YieldStar */] = "yield*", + _a[7 /* Endfinally */] = "endfinally", + _a)); + function transformGenerators(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var renamedCatchVariables; + var renamedCatchVariableDeclarations; + var inGeneratorFunctionBody; + var inStatementContainingYield; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. + var labelNumbers; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. + return transformSourceFile; + function transformSourceFile(node) { + if (node.transformFlags & 1024 /* ContainsGenerator */) { + currentSourceFile = node; + node = ts.visitEachChild(node, visitor, context); + currentSourceFile = undefined; + } + return node; + } + /** + * Visits a node. + * + * @param node The node to visit. + */ + function visitor(node) { + var transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } + else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } + else if (transformFlags & 512 /* Generator */) { + return visitGenerator(node); + } + else if (transformFlags & 1024 /* ContainsGenerator */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 204 /* DoStatement */: + return visitDoStatement(node); + case 205 /* WhileStatement */: + return visitWhileStatement(node); + case 213 /* SwitchStatement */: + return visitSwitchStatement(node); + case 214 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 179 /* FunctionExpression */: + return visitFunctionExpression(node); + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 206 /* ForStatement */: + return visitForStatement(node); + case 207 /* ForInStatement */: + return visitForInStatement(node); + case 210 /* BreakStatement */: + return visitBreakStatement(node); + case 209 /* ContinueStatement */: + return visitContinueStatement(node); + case 211 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 4194304 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } + else if (node.transformFlags & (1024 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 187 /* BinaryExpression */: + return visitBinaryExpression(node); + case 188 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 190 /* YieldExpression */: + return visitYieldExpression(node); + case 170 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 171 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 173 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 174 /* CallExpression */: + return visitCallExpression(node); + case 175 /* NewExpression */: + return visitNewExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ + function visitGenerator(node) { + switch (node.kind) { + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 179 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + node = ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, transformGeneratorFunctionBody(node.body), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. + hoistFunctionDeclaration(node); + return undefined; + } + else { + return node; + } + } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. + if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + node = ts.setOriginalNode(ts.createFunctionExpression( + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, transformGeneratorFunctionBody(node.body), + /*location*/ node), node); + } + else { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitAccessorDeclaration(node) { + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = ts.visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ + function transformGeneratorFunctionBody(body) { + // Save existing generator state + var statements = []; + var savedInGeneratorFunctionBody = inGeneratorFunctionBody; + var savedInStatementContainingYield = inStatementContainingYield; + var savedBlocks = blocks; + var savedBlockOffsets = blockOffsets; + var savedBlockActions = blockActions; + var savedLabelOffsets = labelOffsets; + var savedLabelExpressions = labelExpressions; + var savedNextLabelId = nextLabelId; + var savedOperations = operations; + var savedOperationArguments = operationArguments; + var savedOperationLocations = operationLocations; + var savedState = state; + // Initialize generator state + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = undefined; + blockOffsets = undefined; + blockActions = undefined; + labelOffsets = undefined; + labelExpressions = undefined; + nextLabelId = 1; + operations = undefined; + operationArguments = undefined; + operationLocations = undefined; + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); + transformAndEmitStatements(body.statements, statementOffset); + var buildResult = build(); + ts.addRange(statements, endLexicalEnvironment()); + statements.push(ts.createReturn(buildResult)); + // Restore previous generator state + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return ts.createBlock(statements, /*location*/ body, body.multiLine); + } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (node.transformFlags & 4194304 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return undefined; + } + else { + // Do not hoist custom prologues. + if (node.emitFlags & 8388608 /* CustomPrologue */) { + return node; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return undefined; + } + return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + } + } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitBinaryExpression(node) { + switch (ts.getExpressionAssociativity(node)) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + ts.Debug.fail("Unknown associativity."); + } + } + function isCompoundAssignment(kind) { + return kind >= 57 /* FirstCompoundAssignment */ + && kind <= 68 /* LastCompoundAssignment */; + } + function getOperatorForCompoundAssignment(kind) { + switch (kind) { + case 57 /* PlusEqualsToken */: return 35 /* PlusToken */; + case 58 /* MinusEqualsToken */: return 36 /* MinusToken */; + case 59 /* AsteriskEqualsToken */: return 37 /* AsteriskToken */; + case 60 /* AsteriskAsteriskEqualsToken */: return 38 /* AsteriskAsteriskToken */; + case 61 /* SlashEqualsToken */: return 39 /* SlashToken */; + case 62 /* PercentEqualsToken */: return 40 /* PercentToken */; + case 63 /* LessThanLessThanEqualsToken */: return 43 /* LessThanLessThanToken */; + case 64 /* GreaterThanGreaterThanEqualsToken */: return 44 /* GreaterThanGreaterThanToken */; + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 45 /* GreaterThanGreaterThanGreaterThanToken */; + case 66 /* AmpersandEqualsToken */: return 46 /* AmpersandToken */; + case 67 /* BarEqualsToken */: return 47 /* BarToken */; + case 68 /* CaretEqualsToken */: return 48 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ + function visitRightAssociativeBinaryExpression(node) { + var left = node.left, right = node.right; + if (containsYield(right)) { + var target = void 0; + switch (left.kind) { + case 172 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; + target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); + break; + case 173 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; + target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); + break; + default: + target = ts.visitNode(left, visitor, ts.isExpression); + break; + } + var operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return ts.createBinary(target, 56 /* EqualsToken */, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + } + else { + return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (ts.isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } + else if (node.operatorToken.kind === 24 /* CommaToken */) { + return visitCommaExpression(node); + } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ + function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + } + else { + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); + } + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); + markLabel(resultLabel); + return resultLocal; + } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ + function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); + var pendingExpressions = []; + visit(node.left); + visit(node.right); + return ts.inlineExpressions(pendingExpressions); + function visit(node) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24 /* CommaToken */) { + visit(node.left); + visit(node.right); + } + else { + if (containsYield(node) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); + } + } + } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ + function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + var whenFalseLabel = defineLabel(); + var resultLabel = defineLabel(); + var resultLocal = declareLocal(); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); + markLabel(resultLabel); + return resultLocal; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ + function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; + // NOTE: we are explicitly not handling YieldStar at this time. + var resumeLabel = defineLabel(); + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (node.asteriskToken) { + emitYieldStar(expression, /*location*/ node); + } + else { + emitYield(expression, /*location*/ node); + } + markLabel(resumeLabel); + return createGeneratorResume(); + } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitArrayLiteralExpression(node) { + return visitElements(node.elements, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ + function visitElements(elements, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); + var numInitialElements = countInitialNodesWithoutYield(elements); + var temp = declareLocal(); + var hasAssignedTemp = false; + if (numInitialElements > 0) { + emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + hasAssignedTemp = true; + } + var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); + return hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions); + function reduceElement(expressions, element) { + if (containsYield(element) && expressions.length > 0) { + emitAssignment(temp, hasAssignedTemp + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) + : ts.createArrayLiteral(expressions)); + hasAssignedTemp = true; + expressions = []; + } + expressions.push(ts.visitNode(element, visitor, ts.isExpression)); + return expressions; + } + } + function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); + var properties = node.properties; + var multiLine = node.multiLine; + var numInitialProperties = countInitialNodesWithoutYield(properties); + var temp = declareLocal(); + emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + /*location*/ undefined, multiLine)); + var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + function reduceProperty(expressions, property) { + if (containsYield(property) && expressions.length > 0) { + emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + expressions = []; + } + var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); + var visited = ts.visitNode(expression, visitor, ts.isExpression); + if (visited) { + if (multiLine) { + visited.startsOnNewLine = true; + } + expressions.push(visited); + } + return expressions; + } + } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; + } + return ts.visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false), + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false)), + /*typeArguments*/ undefined, [], + /*location*/ node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements, start) { + if (start === void 0) { start = 0; } + var numStatements = statements.length; + for (var i = start; i < numStatements; i++) { + transformAndEmitStatement(statements[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + transformAndEmitStatements(node.statements); + } + else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + var savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 199 /* Block */: + return transformAndEmitBlock(node); + case 202 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 203 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 204 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 205 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 206 /* ForStatement */: + return transformAndEmitForStatement(node); + case 207 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 209 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 210 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 211 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 212 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 213 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 214 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 215 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 216 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(ts.visitNode(node, visitor, ts.isStatement, /*optional*/ true)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(node); + var numVariables = variables.length; + var variablesWritten = 0; + var pendingExpressions = []; + while (variablesWritten < numVariables) { + for (var i = variablesWritten; i < numVariables; i++) { + var variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return undefined; + } + function transformInitializedVariable(node) { + return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + var endLabel = defineLabel(); + var elseLabel = node.elseStatement ? defineLabel() : undefined; + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel + var conditionLabel = defineLabel(); + var loopLabel = defineLabel(); + beginLoopBlock(/*continueLabel*/ conditionLabel); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel + var loopLabel = defineLabel(); + var endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression)); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = ts.visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } + else { + emitStatement(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression), + /*location*/ initializer)); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression)); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression), + /*location*/ node.incrementor)); + } + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + var variables = ts.getInitializedVariables(initializer); + node = ts.updateFor(node, variables.length > 0 + ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable)) + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.incrementor, visitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations + if (containsYield(node)) { + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i + var initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(keysArray, ts.createArrayLiteral()); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); + emitAssignment(keysIndex, ts.createLiteral(0)); + var conditionLabel = defineLabel(); + var incrementLabel = defineLabel(); + var endLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length"))); + var variable = void 0; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable_1 = _a[_i]; + hoistVariableDeclaration(variable_1.name); + } + variable = ts.getSynthesizedClone(initializer.declarations[0].name); + } + else { + variable = ts.visitNode(initializer, visitor, ts.isExpression); + ts.Debug.assert(ts.isLeftHandSideExpression(variable)); + } + emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { + for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + hoistVariableDeclaration(variable.name); + } + node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + else { + node = ts.visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + var label = findContinueTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); + emitBreak(label, /*location*/ node); + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + var label = findContinueTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + var label = findBreakTarget(node.label ? node.label.text : undefined); + ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); + emitBreak(label, /*location*/ node); + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + var label = findBreakTarget(node.label && node.label.text); + if (label > 0) { + return createInlineBreak(label, /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true), + /*location*/ node); + } + function visitReturnStatement(node) { + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true), + /*location*/ node); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith + beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel + var caseBlock = node.caseBlock; + var numClauses = caseBlock.clauses.length; + var endLabel = beginSwitchBlock(); + var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. + var clauseLabels = []; + var defaultClauseIndex = -1; + for (var i = 0; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 250 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. + var clausesWritten = 0; + var pendingClauses = []; + while (clausesWritten < numClauses) { + var defaultClausesSkipped = 0; + for (var i = clausesWritten; i < numClauses; i++) { + var clause = caseBlock.clauses[i]; + if (clause.kind === 249 /* CaseClause */) { + var caseClause = clause; + if (containsYield(caseClause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push(ts.createCaseClause(ts.visitNode(caseClause.expression, visitor, ts.isExpression), [ + createInlineBreak(clauseLabels[i], /*location*/ caseClause.expression) + ])); + } + else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } + else { + emitBreak(endLabel); + } + for (var i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(node.label.text); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } + else { + emitStatement(ts.visitNode(node, visitor, ts.isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(node.label.text); + } + node = ts.visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } + else { + emitStatement(ts.visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + var numNodes = nodes.length; + for (var i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (ts.isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (renamedCatchVariables && ts.hasProperty(renamedCatchVariables, node.text)) { + var original = ts.getOriginalNode(node); + if (ts.isIdentifier(original) && original.parent) { + var declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_36) { + var clone_7 = ts.getMutableClone(name_36); + setSourceMapRange(clone_7, node); + setCommentRange(clone_7, node); + return clone_7; + } + } + } + } + return node; + } + function cacheExpression(node) { + var temp; + if (ts.isGeneratedIdentifier(node)) { + return node; + } + temp = ts.createTempVariable(hoistVariableDeclaration); + emitAssignment(temp, node, /*location*/ node); + return temp; + } + function declareLocal(name) { + var temp = name + ? ts.createUniqueName(name) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + hoistVariableDeclaration(temp); + return temp; + } + /** + * Defines a label, uses as the target of a Break operation. + */ + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + var label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + /** + * Marks the current operation with the specified label. + */ + function markLabel(label) { + ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + var index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + /** + * Ends the current block operation. + */ + function endBlock() { + var block = peekBlock(); + ts.Debug.assert(block !== undefined, "beginBlock was never called."); + var index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + /** + * Gets the current open block. + */ + function peekBlock() { + return ts.lastOrUndefined(blockStack); + } + /** + * Gets the kind of the current open block. + */ + function peekBlockKind() { + var block = peekBlock(); + return block && block.kind; + } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ + function beginWithBlock(expression) { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression: expression, + startLabel: startLabel, + endLabel: endLabel + }); + } + /** + * Ends a code block for a generated `with` statement. + */ + function endWithBlock() { + ts.Debug.assert(peekBlockKind() === 1 /* With */); + var block = endBlock(); + markLabel(block.endLabel); + } + function isWithBlock(block) { + return block.kind === 1 /* With */; + } + /** + * Begins a code block for a generated `try` statement. + */ + function beginExceptionBlock() { + var startLabel = defineLabel(); + var endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel: startLabel, + endLabel: endLabel + }); + emitNop(); + return endLabel; + } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ + function beginCatchBlock(variable) { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var text = variable.name.text; + var name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = ts.createMap(); + renamedCatchVariableDeclarations = ts.createMap(); + context.enableSubstitution(69 /* Identifier */); + } + renamedCatchVariables[text] = true; + renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; + var exception = peekBlock(); + ts.Debug.assert(exception.state < 1 /* Catch */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); + emitNop(); + } + /** + * Enters the `finally` block of a generated `try` statement. + */ + function beginFinallyBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = peekBlock(); + ts.Debug.assert(exception.state < 2 /* Finally */); + var endLabel = exception.endLabel; + emitBreak(endLabel); + var finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + /** + * Ends the code block for a generated `try` statement. + */ + function endExceptionBlock() { + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + var exception = endBlock(); + var state = exception.state; + if (state < 2 /* Finally */) { + emitBreak(exception.endLabel); + } + else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + function isExceptionBlock(block) { + return block.kind === 0 /* Exception */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ + function beginLoopBlock(continueLabel) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel: breakLabel, + continueLabel: continueLabel + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ + function endLoopBlock() { + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ + function beginSwitchBlock() { + var breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel: breakLabel + }); + return breakLabel; + } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ + function endSwitchBlock() { + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); + var block = endBlock(); + var breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText: labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + var breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText: labelText, + breakLabel: breakLabel + }); + } + function endLabeledBlock() { + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); + var block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (var j = start; j >= 0; j--) { + var containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } + else { + break; + } + } + return false; + } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findBreakTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } + else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + return 0; + } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ + function findContinueTarget(labelText) { + ts.Debug.assert(blocks !== undefined); + if (labelText) { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } + else { + for (var i = blockStack.length - 1; i >= 0; i--) { + var block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + return 0; + } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ + function createLabel(label) { + if (label > 0) { + if (labelExpressions === undefined) { + labelExpressions = []; + } + var expression = ts.createSynthesizedNode(8 /* NumericLiteral */); + if (labelExpressions[label] === undefined) { + labelExpressions[label] = [expression]; + } + else { + labelExpressions[label].push(expression); + } + return expression; + } + return ts.createNode(193 /* OmittedExpression */); + } + /** + * Creates a numeric literal for the provided instruction. + */ + function createInstruction(instruction) { + var literal = ts.createLiteral(instruction); + literal.trailingComment = instructionNames[instruction]; + return literal; + } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ + function createInlineBreak(label, location) { + ts.Debug.assert(label > 0, "Invalid label: " + label); + return ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), location); + } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ + function createInlineReturn(expression, location) { + return ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)]), location); + } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ + function createGeneratorResume(location) { + return ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [], location); + } + /** + * Emits an empty instruction. + */ + function emitNop() { + emitWorker(0 /* Nop */); + } + /** + * Emits a Statement. + * + * @param node A statement. + */ + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } + else { + emitNop(); + } + } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ + function emitWorker(code, args, location) { + if (operations === undefined) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === undefined) { + // mark entry point + markLabel(defineLabel()); + } + var operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + /** + * Builds the generator function body. + */ + function build() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = undefined; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = undefined; + statements = undefined; + exceptionBlockStack = undefined; + currentExceptionBlock = undefined; + withBlockStack = undefined; + var buildResult = buildStatements(); + return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), + /*typeArguments*/ undefined, [ + ts.createThis(), + setNodeEmitFlags(ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*location*/ undefined, + /*multiLine*/ buildResult.length > 0)), 4194304 /* ReuseTempVariableScope */) + ]); + } + /** + * Builds the statements for the generator function body. + */ + function buildStatements() { + if (operations) { + for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } + else { + flushFinalLabel(0); + } + if (clauses) { + var labelExpression = ts.createPropertyAccess(state, "label"); + var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); + switchStatement.startsOnNewLine = true; + return [switchStatement]; + } + if (statements) { + return statements; + } + return []; + } + /** + * Flush the current label and advance to a new label. + */ + function flushLabel() { + if (!statements) { + return; + } + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + /** + * Flush the final label of the generator function body. + */ + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = undefined; + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + } + if (statements && clauses) { + appendLabel(/*markLabelEnd*/ false); + } + updateLabelExpressions(); + } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ + function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. + if (!lastOperationWasCompletion) { + return true; + } + // if there are no labels defined or referenced, then the final label is + // not reachable. + if (!labelOffsets || !labelExpressions) { + return false; + } + // if the label for this offset is referenced, then the final label + // is reachable. + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. + for (var i = withBlockStack.length - 1; i >= 0; i--) { + var withBlock = withBlockStack[i]; + statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. + var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; + statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ + ts.createArrayLiteral([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ]))); + currentExceptionBlock = undefined; + } + if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. + statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + } + } + clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); + statements = undefined; + } + /** + * Tries to enter into a new label at the current operation index. + */ + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (var label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === undefined) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === undefined) { + labelNumbers[labelNumber] = [label]; + } + else { + labelNumbers[labelNumber].push(label); + } + } + } + } + /** + * Updates literal expressions for labels with actual label numbers. + */ + function updateLabelExpressions() { + if (labelExpressions !== undefined && labelNumbers !== undefined) { + for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { + var labels = labelNumbers[labelNumber_1]; + if (labels !== undefined) { + for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) { + var label = labels_1[_i]; + var expressions = labelExpressions[label]; + if (expressions !== undefined) { + for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) { + var expression = expressions_1[_a]; + expression.text = String(labelNumber_1); + } + } + } + } + } + } + } + /** + * Tries to enter or leave a code block. + */ + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + var block = blocks[blockIndex]; + var blockAction = blockActions[blockIndex]; + if (isExceptionBlock(block)) { + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } + else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + } + else if (isWithBlock(block)) { + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } + else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + } + } + } + } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + var opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } + else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + var args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + var location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ + function writeAssign(left, right, operationLocation) { + writeStatement(ts.createStatement(ts.createAssignment(left, right), operationLocation)); + } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createThrow(expression, operationLocation)); + } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)]), operationLocation)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), operationLocation)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement(ts.createIf(condition, ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), operationLocation))); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement(ts.createIf(ts.createLogicalNot(condition), ts.createReturn(ts.createArrayLiteral([ + createInstruction(3 /* Break */), + createLabel(label) + ]), operationLocation))); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral(expression + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)]), operationLocation)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(5 /* YieldStar */), + expression + ]), operationLocation)); + } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement(ts.createReturn(ts.createArrayLiteral([ + createInstruction(7 /* Endfinally */) + ]))); + } + } + ts.transformGenerators = transformGenerators; + var _a; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var ES6SubstitutionFlags; + (function (ES6SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES6SubstitutionFlags[ES6SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES6SubstitutionFlags[ES6SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES6SubstitutionFlags || (ES6SubstitutionFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + function transformES6(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + return ts.visitNode(node, visitor, ts.isSourceFile); + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + // don't treat content of nodes that start new lexical environment as part of converted loop copy + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64 /* ES6 */) !== 0 || + node.kind === 214 /* LabeledStatement */ || + (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128 /* ContainsES6 */) { + return ts.visitEachChild(node, visitor, context); + } + else { + return node; + } + } + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { + switch (node.kind) { + case 211 /* ReturnStatement */: + return visitReturnStatement(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + case 213 /* SwitchStatement */: + return visitSwitchStatement(node); + case 210 /* BreakStatement */: + case 209 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 97 /* ThisKeyword */: + return visitThisKeyword(node); + case 69 /* Identifier */: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 82 /* ExportKeyword */: + return node; + case 221 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 192 /* ClassExpression */: + return visitClassExpression(node); + case 142 /* Parameter */: + return visitParameter(node); + case 220 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 180 /* ArrowFunction */: + return visitArrowFunction(node); + case 179 /* FunctionExpression */: + return visitFunctionExpression(node); + case 218 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 69 /* Identifier */: + return visitIdentifier(node); + case 219 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 214 /* LabeledStatement */: + return visitLabeledStatement(node); + case 204 /* DoStatement */: + return visitDoStatement(node); + case 205 /* WhileStatement */: + return visitWhileStatement(node); + case 206 /* ForStatement */: + return visitForStatement(node); + case 207 /* ForInStatement */: + return visitForInStatement(node); + case 208 /* ForOfStatement */: + return visitForOfStatement(node); + case 202 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 171 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 254 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 170 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 174 /* CallExpression */: + return visitCallExpression(node); + case 175 /* NewExpression */: + return visitNewExpression(node); + case 178 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 187 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* TemplateHead */: + case 13 /* TemplateMiddle */: + case 14 /* TemplateTail */: + return visitTemplateLiteral(node); + case 176 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 189 /* TemplateExpression */: + return visitTemplateExpression(node); + case 190 /* YieldExpression */: + return visitYieldExpression(node); + case 95 /* SuperKeyword */: + return visitSuperKeyword(node); + case 190 /* YieldExpression */: + // `yield` will be handled by a generators transform. + return ts.visitEachChild(node, visitor, context); + case 147 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 256 /* SourceFile */: + return visitSourceFileNode(node); + case 200 /* VariableStatement */: + return visitVariableStatement(node); + default: + ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); + } + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 180 /* ArrowFunction */) { + enclosingNonArrowFunction = currentNode; + if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + // keep track of the enclosing variable statement when in the context of + // variable statements, variable declarations, binding elements, and binding + // patterns. + switch (currentNode.kind) { + case 200 /* VariableStatement */: + enclosingVariableStatement = currentNode; + break; + case 219 /* VariableDeclarationList */: + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + case 167 /* ObjectBindingPattern */: + case 168 /* ArrayBindingPattern */: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8 /* Return */; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 180 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction is then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; + } + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 210 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 210 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 210 /* BreakStatement */) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 24 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 24 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var modifierFlags = ts.getModifierFlags(node); + var isExported = modifierFlags & 1 /* Export */; + var isDefault = modifierFlags & 512 /* Default */; + // Add an `export` modifier to the statement if needed (for `--target es5 --module es6`) + var modifiers = isExported && !isDefault + ? ts.filter(node.modifiers, isExportModifier) + : undefined; + var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)) + ]), + /*location*/ node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (isExported && isDefault) { + var statements = [statement]; + statements.push(ts.createExportAssignment( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*isExportEquals*/ false, getDeclarationName(node, /*allowComments*/ false))); + return statements; + } + return statement; + } + function isExportModifier(node) { + return node.kind === 82 /* ExportKeyword */; + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression( + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + if (getNodeEmitFlags(node) & 524288 /* Indented */) { + setNodeEmitFlags(classFunction, 524288 /* Indented */); + } + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + setNodeEmitFlags(inner, 49152 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + setNodeEmitFlags(outer, 49152 /* NoComments */); + return ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16 /* CloseBraceToken */); + var localName = getLocalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + setNodeEmitFlags(outer, 49152 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); + setNodeEmitFlags(block, 49152 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), + /*location*/ extendsClauseElement)); + } + } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + statements.push(ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, getDeclarationName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), + /*location*/ constructor || node)); + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + if (constructor && !hasSynthesizedSuper) { + return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); + } + return []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + startLexicalEnvironment(); + if (constructor) { + addCaptureThisForNodeIfNeeded(statements, constructor); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + } + addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); + if (constructor) { + var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + ts.addRange(statements, body); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, + /*location*/ constructor ? constructor.body.statements : node.members), + /*location*/ constructor ? constructor.body : node, + /*multiLine*/ true); + if (!constructor) { + setNodeEmitFlags(block, 49152 /* NoComments */); + } + return block; + } + function transformConstructorBodyWithSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); + } + function transformConstructorBodyWithoutSynthesizedSuper(node) { + return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + } + /** + * Adds a synthesized call to `_super` if it is needed. + * + * @param statements The statements for the new constructor body. + * @param constructor The constructor for the class. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, or if the class has an `extends` clause but no + // constructor, we emit a synthesized call to `_super`. + if (constructor ? hasSynthesizedSuper : extendsClauseElement) { + statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), + /*location*/ extendsClauseElement)); + } + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.createParameter(node.name, + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_37)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(setNodeEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), + /*location*/ parameter)) + ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), + /*elseStatement*/ undefined, + /*location*/ parameter); + statement.startsOnNewLine = true; + setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 69 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(setNodeEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ]), + /*location*/ parameter), 8388608 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ], /*location*/ parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), + /*location*/ parameter), ts.createPostfixIncrement(temp, /*location*/ parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), + /*location*/ parameter)) + ])); + setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, ts.createThis()) + ])); + setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); + setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 198 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 147 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 148 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(/*location*/ member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = getCommentRange(member); + var sourceMapRange = getSourceMapRange(member); + var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); + setNodeEmitFlags(func, 49152 /* NoComments */); + setSourceMapRange(func, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), + /*location*/ member.name), func), + /*location*/ member); + ts.setOriginalNode(statement, member); + setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + setNodeEmitFlags(statement, 1536 /* NoSourceMap */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), + /*location*/ getSourceMapRange(accessors.firstAccessor)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + setNodeEmitFlags(statement, 49152 /* NoComments */); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); + setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); + setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); + setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + var getter = ts.createPropertyAssignment("get", getterFunction); + setCommentRange(getter, getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); + setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + var setter = ts.createPropertyAssignment("set", setterFunction); + setCommentRange(setter, getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); + setNodeEmitFlags(func, 256 /* CapturesThis */); + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + return transformFunctionLikeToExpression(node, /*location*/ node, node.name); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + return ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, transformFunctionBody(node), + /*location*/ node), + /*original*/ node); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 180 /* ArrowFunction */) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), + /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location), + /*original*/ node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + startLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); + // If we added any generated statements, this must be a multi-line block. + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 180 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, /*location*/ body); + setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + // If we added any final generated statements, this must be a multi-line block + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + setNodeEmitFlags(block, 32 /* SingleLine */); + } + if (closeBraceLocation) { + setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 178 /* ParenthesizedExpression */: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 187 /* BinaryExpression */: + return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (needsDestructuringValue) { + switch (node.expression.kind) { + case 178 /* ParenthesizedExpression */: + return ts.createParen(visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ true), + /*location*/ node); + case 187 /* BinaryExpression */: + return ts.createParen(visitBinaryExpression(node.expression, /*needsDestructuringValue*/ true), + /*location*/ node); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + ts.Debug.assert(ts.isDestructuringAssignment(node)); + return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) == 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); + } + else { + assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24 /* CommaToken */, acc); }), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); + ts.setOriginalNode(declarationList, node); + setCommentRange(declarationList, node); + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, /*lookInLabeledStatements*/ false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 207 /* ForInStatement */ + && enclosingBlockScopeContainer.kind !== 208 /* ForOfStatement */ + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, /*lookInLabeledStatements*/ false))); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_8 = ts.getMutableClone(node); + clone_8.initializer = ts.createVoidZero(); + return clone_8; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern. + if (ts.isBindingPattern(node.name)) { + var recordTempVariablesInLine = !enclosingVariableStatement + || !ts.hasModifier(enclosingVariableStatement, 1 /* Export */); + return ts.flattenVariableDestructuring(context, node, /*value*/ undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + /** + * Visits a ForOfStatement and converts it into a compatible ForStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 69 /* Identifier */ + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + // Initialize LHS + // var v = _a[_i]; + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ initializer); + ts.setOriginalNode(declarationList, initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, ts.createElementAccess(rhsReference, counter)) + ], /*location*/ ts.moveRangePos(initializer, -1)), + /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); + if (ts.isDestructuringAssignment(assignment)) { + // This is a destructuring pattern, so we flatten the destructuring instead. + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, + /*needsValue*/ false, hoistVariableDeclaration, visitor))); + } + else { + // Currently there is not way to check that assignment is binary expression of destructing assignment + // so we have to cast never type to binaryExpression + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + // The old emitter does not emit source maps for the expression + setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); + // The old emitter does not emit source maps for the block. + // We add the location to preserve comments. + var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), + /*location*/ bodyLocation); + setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) + ], /*location*/ node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), + /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); + return forStatement; + } + /** + * Visits an ObjectLiteralExpression with computed propety names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 4194304 /* ContainsYield */ + || property.name.kind === 140 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + /*location*/ undefined, node.multiLine), 524288 /* Indented */)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 69 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert ? convert(node, /*convertedLoopBodyStatements*/ undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 219 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (outerConvertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length) { + var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_3); + loopBody = ts.createBlock(statements_3, /*location*/ undefined, /*multiline*/ true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 + && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 256 /* CapturesThis */; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 2097152 /* AsyncFunctionBody */; + } + var convertedLoopVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, loopParameters, + /*type*/ undefined, loopBody), loopBodyFlags)) + ])); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (currentState.argumentsName) { + // if alias for arguments is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + // if alias for this is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerConvertedLoopState) { + // pass them to outer converted loop + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var name_38 in currentState.hoistedLocalVariables) { + var identifier = currentState.hoistedLocalVariables[name_38]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { + var outParam = loopOutParameters_1[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + // clean statement part + loop.statement = undefined; + // visit childnodes to transform initializer/condition/incrementor parts + loop = ts.visitEachChild(loop, visitor, context); + // set loop statement + loop.statement = ts.createBlock(convertedLoopBodyStatements, + /*location*/ undefined, + /*multiline*/ true); + // reset and re-aggregate the transform flags + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 214 /* LabeledStatement */ + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 56 /* EqualsToken */, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37 /* AsteriskToken */), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(name)); + if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 253 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 254 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + break; + case 147 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined), + /*location*/ method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); + setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, + /*location*/ node); + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), + /*location*/ node); + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + // We are here because we contain a SpreadElementExpression. + ts.Debug.assert((node.transformFlags & 262144 /* ContainsSpreadElementExpression */) !== 0); + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + /** + * Transforms an array of Expression nodes that contains a SpreadElementExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpreadElement(node) { + return ts.isSpreadElementExpression(node) + ? visitSpanOfSpreadElements + : visitSpanOfNonSpreadElements; + } + function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.map(chunk, visitExpressionOfSpreadElement); + } + function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, ts.isExpression), + /*location*/ undefined, multiLine); + } + /** + * Transforms the expression of a SpreadElementExpression node. + * + * @param node A SpreadElementExpression node. + */ + function visitExpressionOfSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, /*location*/ node); + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Allocate storage for the template site object + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Build up the template arguments and the raw and cooked strings for the template. + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + // NOTE: The parentheses here is entirely optional as we are now able to auto- + // parenthesize when rebuilding the tree. This should be removed in a + // future version. It is here for now to match our existing emit. + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) + ])); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, /*location*/ node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword(node) { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32 /* Static */) + && currentParent.kind !== 174 /* CallExpression */ + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + function visitSourceFileNode(node) { + var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; + var statements = []; + startLexicalEnvironment(); + ts.addRange(statements, prologue); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); + ts.addRange(statements, endLexicalEnvironment()); + var clone = ts.getMutableClone(node); + clone.statements = ts.createNodeArray(statements, /*location*/ node.statements); + return clone; + } + /** + * Called by the printer just before a node is printed. + * + * @param node The node to be printed. + */ + function onEmitNode(node, emit) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + enclosingFunction = node; + } + previousOnEmitNode(node, emit); + enclosingFunction = savedEnclosingFunction; + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(69 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(97 /* ThisKeyword */); + context.enableEmitNotification(148 /* Constructor */); + context.enableEmitNotification(147 /* MethodDeclaration */); + context.enableEmitNotification(149 /* GetAccessor */); + context.enableEmitNotification(150 /* SetAccessor */); + context.enableEmitNotification(180 /* ArrowFunction */); + context.enableEmitNotification(179 /* FunctionExpression */); + context.enableEmitNotification(220 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + node = previousOnSubstituteNode(node, isExpression); + if (isExpression) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 169 /* BindingElement */: + case 221 /* ClassDeclaration */: + case 224 /* EnumDeclaration */: + case 218 /* VariableDeclaration */: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 69 /* Identifier */: + return substituteExpressionIdentifier(node); + case 97 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && enclosingFunction + && enclosingFunction.emitFlags & 256 /* CapturesThis */) { + return ts.createIdentifier("_this", /*location*/ node); + } + return node; + } + /** + * Gets the local name for a declaration for use in expressions. + * + * A local name will *never* be prefixed with an module or namespace export modifier like + * "exports.". + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getDeclarationName(node, allowComments, allowSourceMaps, 262144 /* LocalName */); + } + /** + * Gets the name of a declaration, without source map or comments. + * + * @param node The declaration. + * @param allowComments Allow comments for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && !ts.isGeneratedIdentifier(node.name)) { + var name_39 = ts.getMutableClone(node.name); + emitFlags |= getNodeEmitFlags(node.name); + if (!allowSourceMaps) { + emitFlags |= 1536 /* NoSourceMap */; + } + if (!allowComments) { + emitFlags |= 49152 /* NoComments */; + } + if (emitFlags) { + setNodeEmitFlags(name_39, emitFlags); + } + return name_39; + } + return ts.getGeneratedNameForNode(node); + } + function getClassMemberPrefix(node, member) { + var expression = getLocalName(node); + return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + var parameter = ts.singleOrUndefined(constructor.parameters); + if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191 /* SpreadElementExpression */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression === parameter.name; + } + } + ts.transformES6 = transformES6; +})(ts || (ts = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/* @internal */ +var ts; +(function (ts) { + var moduleTransformerMap = ts.createMap((_a = {}, + _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.System] = ts.transformSystemModule, + _a[ts.ModuleKind.AMD] = ts.transformModule, + _a[ts.ModuleKind.CommonJS] = ts.transformModule, + _a[ts.ModuleKind.UMD] = ts.transformModule, + _a[ts.ModuleKind.None] = ts.transformModule, + _a)); + var SyntaxKindFeatureFlags; + (function (SyntaxKindFeatureFlags) { + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; + SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; + })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); + function getTransformers(compilerOptions) { + var jsx = compilerOptions.jsx; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var transformers = []; + transformers.push(ts.transformTypeScript); + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (jsx === 2 /* React */) { + transformers.push(ts.transformJsx); + } + transformers.push(ts.transformES7); + if (languageVersion < 2 /* ES6 */) { + transformers.push(ts.transformES6); + transformers.push(ts.transformGenerators); + } + return transformers; + } + ts.getTransformers = getTransformers; + /** + * Tracks a monotonically increasing transformation id used to associate a node with a specific + * transformation. This ensures transient properties related to transformations can be safely + * stored on source tree nodes that may be reused across multiple transformations (such as + * with compile-on-save). + */ + var nextTransformId = 1; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host. + * @param sourceFiles An array of source files + * @param transforms An array of Transformers. + */ + function transformFiles(resolver, host, sourceFiles, transformers) { + var transformId = nextTransformId; + nextTransformId++; + var tokenSourceMapRanges = ts.createMap(); + var lexicalEnvironmentVariableDeclarationsStack = []; + var lexicalEnvironmentFunctionDeclarationsStack = []; + var enabledSyntaxKindFeatures = new Array(289 /* Count */); + var parseTreeNodesWithAnnotations = []; + var lastTokenSourceMapRangeNode; + var lastTokenSourceMapRangeToken; + var lastTokenSourceMapRange; + var lexicalEnvironmentStackOffset = 0; + var hoistedVariableDeclarations; + var hoistedFunctionDeclarations; + var lexicalEnvironmentDisabled; + // The transformation context is provided to each transformer as part of transformer + // initialization. + var context = { + getCompilerOptions: function () { return host.getCompilerOptions(); }, + getEmitResolver: function () { return resolver; }, + getEmitHost: function () { return host; }, + getNodeEmitFlags: getNodeEmitFlags, + setNodeEmitFlags: setNodeEmitFlags, + getSourceMapRange: getSourceMapRange, + setSourceMapRange: setSourceMapRange, + getTokenSourceMapRange: getTokenSourceMapRange, + setTokenSourceMapRange: setTokenSourceMapRange, + getCommentRange: getCommentRange, + setCommentRange: setCommentRange, + hoistVariableDeclaration: hoistVariableDeclaration, + hoistFunctionDeclaration: hoistFunctionDeclaration, + startLexicalEnvironment: startLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, + onSubstituteNode: onSubstituteNode, + enableSubstitution: enableSubstitution, + isSubstitutionEnabled: isSubstitutionEnabled, + onEmitNode: onEmitNode, + enableEmitNotification: enableEmitNotification, + isEmitNotificationEnabled: isEmitNotificationEnabled + }; + // Chain together and initialize each transformer. + var transformation = chain.apply(void 0, transformers)(context); + // Transform each source file. + var transformed = ts.map(sourceFiles, transformSourceFile); + // Disable modification of the lexical environment. + lexicalEnvironmentDisabled = true; + return { + getSourceFiles: function () { return transformed; }, + getTokenSourceMapRange: getTokenSourceMapRange, + isSubstitutionEnabled: isSubstitutionEnabled, + isEmitNotificationEnabled: isEmitNotificationEnabled, + onSubstituteNode: context.onSubstituteNode, + onEmitNode: context.onEmitNode, + dispose: function () { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { + var node = parseTreeNodesWithAnnotations_1[_i]; + if (node.transformId === transformId) { + node.transformId = 0; + node.emitFlags = 0; + node.commentRange = undefined; + node.sourceMapRange = undefined; + } + } + parseTreeNodesWithAnnotations.length = 0; + } + }; + /** + * Transforms a source file. + * + * @param sourceFile The source file to transform. + */ + function transformSourceFile(sourceFile) { + if (ts.isDeclarationFile(sourceFile)) { + return sourceFile; + } + return transformation(sourceFile); + } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + function enableSubstitution(kind) { + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + } + /** + * Default hook for node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(node, isExpression) { + return node; + } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ + function enableEmitNotification(kind) { + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + } + /** + * Default hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(node, emit) { + emit(node); + } + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function beforeSetAnnotation(node) { + if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + parseTreeNodesWithAnnotations.push(node); + node.transformId = transformId; + } + } + /** + * Gets flags that control emit behavior of a node. + * + * If the node does not have its own NodeEmitFlags set, the node emit flags of its + * original pointer are used. + * + * @param node The node. + */ + function getNodeEmitFlags(node) { + return node.emitFlags; + } + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setNodeEmitFlags(node, emitFlags) { + beforeSetAnnotation(node); + node.emitFlags = emitFlags; + return node; + } + /** + * Gets a custom text range to use when emitting source maps. + * + * If a node does not have its own custom source map text range, the custom source map + * text range of its original pointer is used. + * + * @param node The node. + */ + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + beforeSetAnnotation(node); + node.sourceMapRange = range; + return node; + } + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * If a node does not have its own custom source map text range for a token, the custom + * source map text range for the token of its original pointer is used. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + // As a performance optimization, use the cached value of the most recent node. + // This helps for cases where this function is called repeatedly for the same node. + if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { + return lastTokenSourceMapRange; + } + // Get the custom token source map range for a node or from one of its original nodes. + // Custom token ranges are not stored on the node to avoid the GC burden. + var range; + var current = node; + while (current) { + range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; + if (range !== undefined) { + break; + } + current = current.original; + } + // Cache the most recently requested value. + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + return range; + } + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + // Cache the most recently requested value. + lastTokenSourceMapRangeNode = node; + lastTokenSourceMapRangeToken = token; + lastTokenSourceMapRange = range; + tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; + return node; + } + /** + * Gets a custom text range to use when emitting comments. + * + * If a node does not have its own custom source map text range, the custom source map + * text range of its original pointer is used. + * + * @param node The node. + */ + function getCommentRange(node) { + return node.commentRange || node; + } + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + beforeSetAnnotation(node); + node.commentRange = range; + return node; + } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ + function hoistVariableDeclaration(name) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var decl = ts.createVariableDeclaration(name); + if (!hoistedVariableDeclarations) { + hoistedVariableDeclarations = [decl]; + } + else { + hoistedVariableDeclarations.push(decl); + } + } + /** + * Records a hoisted function declaration within a lexical environment. + */ + function hoistFunctionDeclaration(func) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + if (!hoistedFunctionDeclarations) { + hoistedFunctionDeclarations = [func]; + } + else { + hoistedFunctionDeclarations.push(func); + } + } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ + function startLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentStackOffset++; + hoistedVariableDeclarations = undefined; + hoistedFunctionDeclarations = undefined; + } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ + function endLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + var statements; + if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { + if (hoistedFunctionDeclarations) { + statements = hoistedFunctionDeclarations.slice(); + } + if (hoistedVariableDeclarations) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (!statements) { + statements = [statement]; + } + else { + statements.push(statement); + } + } + } + // Restore the previous lexical environment. + lexicalEnvironmentStackOffset--; + hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + return statements; + } + } + ts.transformFiles = transformFiles; + function chain(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + function compose(a, b, c, d, e) { + if (e) { + var args_4 = []; + for (var i = 0; i < arguments.length; i++) { + args_4[i] = arguments[i]; + } + return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + var _a; +})(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { + if (compilerOptions.extendedDiagnostics) { + return createSourceMapWriterWithExtendedDiagnostics(host, writer); + } + return createSourceMapWriterWorker(host, writer); + } + else { + return getNullSourceMapWriter(); + } + } + ts.createSourceMapWriter = createSourceMapWriter; var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { }, + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitPos: function (pos) { }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, + emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, + changeEmitSourcePos: function () { }, + stopOverridingSpan: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -33648,27 +51988,11 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitStart: function (range) { }, - emitEnd: function (range, stopOverridingSpan) { }, - emitPos: function (pos) { }, - changeEmitSourcePos: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; }, - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; - function createSourceMapWriter(host, writer) { + function createSourceMapWriterWorker(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; + var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be var stopOverridingSpan = false; var modifyLastSourcePos = false; @@ -33680,23 +52004,42 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; + // This keeps track of the number of times `disable` has been called without a + // corresponding call to `enable`. As long as this value is non-zero, mappings will not + // be recorded. + // This is primarily used to provide a better experience when debugging binding + // patterns and destructuring assignments for simple expressions. + var disableDepth; return { + initialize: initialize, + reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitStart: emitStart, emitEnd: emitEnd, + emitTokenStart: emitTokenStart, + emitTokenEnd: emitTokenEnd, changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: function () { return stopOverridingSpan = true; }, getText: getText, - getSourceMappingURL: getSourceMappingURL, - initialize: initialize, - reset: reset + getSourceMappingURL: getSourceMappingURL }; + /** + * Initialize the SourceMapWriter for a new output file. + * + * @param filePath The path to the generated output file. + * @param sourceMapFilePath The path to the output source map file. + * @param sourceFiles The input source files for the program. + * @param isBundledEmit A value indicating whether the generated output file is a bundle. + */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { if (sourceMapData) { reset(); } currentSourceFile = undefined; + currentSourceText = undefined; + disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -33746,6 +52089,9 @@ var ts; sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); } } + /** + * Reset the SourceMapWriter to an empty state. + */ function reset() { currentSourceFile = undefined; sourceMapDir = undefined; @@ -33754,6 +52100,21 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + disableDepth = 0; + } + /** + * Re-enables the recording of mappings. + */ + function enable() { + if (disableDepth > 0) { + disableDepth--; + } + } + /** + * Disables the recording of mappings. + */ + function disable() { + disableDepth++; } function updateLastEncodedAndRecordedSpans() { if (modifyLastSourcePos) { @@ -33827,10 +52188,21 @@ var ts; lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ function emitPos(pos) { - if (pos === -1) { + if (ts.positionIsSynthesized(pos) || disableDepth > 0) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; @@ -33863,24 +52235,84 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } - function getStartPos(range) { + function getStartPosPastDecorators(range) { var rangeHasDecorators = !!range.decorators; - return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); } - function emitStart(range) { - emitPos(getStartPos(range)); + function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(getStartPosPastDecorators(range)); + } + if (ignoreChildrenCallback(contextNode)) { + disable(); + } + } + else { + emitPos(getStartPosPastDecorators(range)); + } } - function emitEnd(range, stopOverridingEnd) { - emitPos(range.end); - stopOverridingSpan = stopOverridingEnd; + function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + if (contextNode) { + if (ignoreChildrenCallback(contextNode)) { + enable(); + } + if (!ignoreNodeCallback(contextNode)) { + range = getTextRangeCallback(contextNode) || range; + emitPos(range.end); + } + } + else { + emitPos(range.end); + } + stopOverridingSpan = false; } + function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return ts.skipTrivia(currentSourceText, tokenStartPos); + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenStartPos = range.pos; + } + } + tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); + emitPos(tokenStartPos); + return tokenStartPos; + } + function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + if (contextNode) { + if (ignoreTokenCallback(contextNode, token)) { + return tokenEndPos; + } + var range = getTokenTextRangeCallback(contextNode, token); + if (range) { + tokenEndPos = range.end; + } + } + emitPos(tokenEndPos); + return tokenEndPos; + } + // @deprecated function changeEmitSourcePos() { ts.Debug.assert(!modifyLastSourcePos); modifyLastSourcePos = true; } + /** + * Set the current source file. + * + * @param sourceFile The source file. + */ function setSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location @@ -33892,12 +52324,15 @@ var ts; sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); } } } + /** + * Gets the text for the source map. + */ function getText() { encodeLastRecordedSourceMapSpan(); return ts.stringify({ @@ -33910,6 +52345,9 @@ var ts; sourcesContent: sourceMapData.sourceMapSourcesContent }); } + /** + * Gets the SourceMappingURL for the source map. + */ function getSourceMappingURL() { if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url @@ -33921,7 +52359,46 @@ var ts; } } } - ts.createSourceMapWriter = createSourceMapWriter; + function createSourceMapWriterWithExtendedDiagnostics(host, writer) { + var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; + return { + initialize: initialize, + reset: reset, + getSourceMapData: getSourceMapData, + setSourceFile: setSourceFile, + emitPos: function (pos) { + ts.performance.mark("sourcemapStart"); + emitPos(pos); + ts.performance.measure("sourceMapTime", "sourcemapStart"); + }, + emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitStart"); + emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); + }, + emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitEnd"); + emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); + }, + emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenStart"); + tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); + return tokenStartPos; + }, + emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { + ts.performance.mark("emitSourcemap:emitTokenEnd"); + tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); + ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); + return tokenEndPos; + }, + changeEmitSourcePos: changeEmitSourcePos, + stopOverridingSpan: stopOverridingSpan, + getText: getText, + getSourceMappingURL: getSourceMappingURL + }; + } var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -33955,6 +52432,299 @@ var ts; return encodedStr; } })(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function createCommentWriter(host, writer, sourceMap) { + var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; + var newLine = host.getNewLine(); + var emitPos = sourceMap.emitPos; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentSourceFile; + var currentText; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var disabled = compilerOptions.removeComments; + return { + reset: reset, + setSourceFile: setSourceFile, + emitNodeWithComments: emitNodeWithComments, + emitBodyWithDetachedComments: emitBodyWithDetachedComments, + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + }; + function emitNodeWithComments(node, emitCallback) { + if (disabled) { + emitCallback(node); + return; + } + if (node) { + var _a = node.commentRange || node, pos = _a.pos, end = _a.end; + var emitFlags = node.emitFlags; + if ((pos < 0 && end < 0) || (pos === end)) { + // Both pos and end are synthesized, so just emit the node without comments. + if (emitFlags & 65536 /* NoNestedComments */) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + } + else { + if (extendedDiagnostics) { + ts.performance.mark("preEmitNodeWithComment"); + } + var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; + var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + // Save current container state on the stack. + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + if (!skipLeadingComments) { + containerPos = pos; + } + if (!skipTrailingComments) { + containerEnd = end; + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 219 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitNodeWithComment"); + } + if (emitFlags & 65536 /* NoNestedComments */) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitNodeWithComment"); + } + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitNodeWithComment"); + } + } + } + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + if (extendedDiagnostics) { + ts.performance.mark("preEmitBodyWithDetachedComments"); + } + var pos = detachedRange.pos, end = detachedRange.end; + var emitFlags = node.emitFlags; + var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); + } + if (emitFlags & 65536 /* NoNestedComments */) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + if (extendedDiagnostics) { + ts.performance.mark("beginEmitBodyWithDetachedCommetns"); + } + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + } + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + } + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!hasWrittenComment) { + ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); + hasWrittenComment = true; + } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.write(" "); + } + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos) { + if (disabled) { + return; + } + if (extendedDiagnostics) { + ts.performance.mark("beforeEmitTrailingCommentsOfPosition"); + } + forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + if (extendedDiagnostics) { + ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); + } + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + emitPos(commentPos); + ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (containerPos === -1 || pos !== containerPos) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { + ts.forEachTrailingCommentRange(currentText, end, cb); + } + } + function reset() { + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentText = currentSourceFile.text; + currentLineMap = ts.getLineStarts(currentSourceFile); + detachedCommentsInfo = undefined; + } + function disableCommentsAndEmit(node, emitCallback) { + if (disabled) { + emitCallback(node); + } + else { + disabled = true; + emitCallback(node); + disabled = false; + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos + var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + emitPos(commentPos); + ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + **/ + function isTripleSlashComment(commentPos, commentEnd) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (currentText.charCodeAt(commentPos + 1) === 47 /* slash */ && + commentPos + 2 < commentEnd && + currentText.charCodeAt(commentPos + 2) === 47 /* slash */) { + var textSubStr = currentText.substring(commentPos, commentEnd); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? + true : false; + } + return false; + } + } + ts.createCommentWriter = createCommentWriter; +})(ts || (ts = {})); /// /* @internal */ var ts; @@ -34070,9 +52840,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -34170,11 +52938,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = {}; + usedTypeDirectiveReferences = ts.createMap(); } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { + if (!(directive in usedTypeDirectiveReferences)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -34201,7 +52969,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -34263,7 +53031,7 @@ var ts; var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -34282,7 +53050,7 @@ var ts; case 93 /* NullKeyword */: case 127 /* NeverKeyword */: case 165 /* ThisType */: - case 166 /* StringLiteralType */: + case 166 /* LiteralType */: return writeTextOfNode(currentText, type); case 194 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); @@ -34333,7 +53101,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 172 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { @@ -34407,15 +53175,15 @@ var ts; // do not need to keep track of created temp names. function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentIdentifiers, baseName)) { + if (!(baseName in currentIdentifiers)) { return baseName; } var count = 0; while (true) { count++; - var name_23 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_23)) { - return name_23; + var name_40 = baseName + "_" + count; + if (!(name_40 in currentIdentifiers)) { + return name_40; } } } @@ -34518,11 +53286,12 @@ var ts; function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export if (node.parent.kind === 256 /* SourceFile */) { + var modifiers = ts.getModifierFlags(node); // If the node is exported - if (node.flags & 1 /* Export */) { + if (modifiers & 1 /* Export */) { write("export "); } - if (node.flags & 512 /* Default */) { + if (modifiers & 512 /* Default */) { write("default "); } else if (node.kind !== 222 /* InterfaceDeclaration */ && !noDeclare) { @@ -34551,7 +53320,7 @@ var ts; // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { write("export "); } write("import "); @@ -34587,7 +53356,7 @@ var ts; } function writeImportDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (ts.hasModifier(node, 1 /* Export */)) { write("export "); } write("import "); @@ -34685,7 +53454,7 @@ var ts; write("global "); } else { - if (node.flags & 4096 /* Namespace */) { + if (node.flags & 16 /* Namespace */) { write("namespace "); } else { @@ -34768,7 +53537,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 /* MethodDeclaration */ && (node.parent.flags & 8 /* Private */); + return node.parent.kind === 147 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -34812,7 +53581,7 @@ var ts; break; case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.parent.flags & 32 /* Static */) { + if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 221 /* ClassDeclaration */) { @@ -34847,7 +53616,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isSupportedExpressionWithTypeArguments(node)) { + if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { @@ -34882,7 +53651,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 92 /* ParameterPropertyModifier */) { + if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { emitPropertyDeclaration(param); } }); @@ -34890,7 +53659,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 128 /* Abstract */) { + if (ts.hasModifier(node, 128 /* Abstract */)) { write("abstract "); } write("class "); @@ -34936,7 +53705,7 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); emitVariableDeclaration(node); write(";"); writeLine(); @@ -34953,14 +53722,20 @@ var ts; // it if it's not a well known symbol. In that case, the text of the name will be exactly // what we want, namely the name expression enclosed in brackets. writeTextOfNode(currentText, node.name); - // If optional property emit ? - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || node.kind === 142 /* Parameter */) && ts.hasQuestionToken(node)) { + // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor + // we don't want to emit property declaration with "?" + if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || + (node.kind === 142 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) && node.parent.kind === 159 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 8 /* Private */)) { + else if (resolver.isLiteralConstDeclaration(node)) { + write(" = "); + resolver.writeLiteralConstValue(node, writer); + } + else if (!ts.hasModifier(node, 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -34975,7 +53750,7 @@ var ts; } else if (node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & 32 /* Static */) { + if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -35077,9 +53852,9 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64 /* Readonly */)); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64 /* Readonly */)); writeTextOfNode(currentText, node.name); - if (!(node.flags & 8 /* Private */)) { + if (!ts.hasModifier(node, 8 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -35108,7 +53883,7 @@ var ts; var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 150 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & 32 /* Static */) { + if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -35126,7 +53901,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 32 /* Static */) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -35160,7 +53935,7 @@ var ts; emitModuleElementDeclarationFlags(node); } else if (node.kind === 147 /* MethodDeclaration */ || node.kind === 148 /* Constructor */) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } if (node.kind === 220 /* FunctionDeclaration */) { write("function "); @@ -35188,7 +53963,7 @@ var ts; var closeParenthesizedFunctionType = false; if (node.kind === 153 /* IndexSignature */) { // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { @@ -35226,7 +54001,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 148 /* Constructor */ && !(node.flags & 8 /* Private */)) { + else if (node.kind !== 148 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -35260,7 +54035,7 @@ var ts; break; case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.flags & 32 /* Static */) { + if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -35321,7 +54096,7 @@ var ts; node.parent.parent.kind === 159 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 8 /* Private */)) { + else if (!ts.hasModifier(node.parent, 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { @@ -35352,7 +54127,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - if (node.parent.flags & 32 /* Static */) { + if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -35546,284 +54321,13 @@ var ts; ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); /// -/// +/// /// +/// +/// /* @internal */ var ts; (function (ts) { - function getResolvedExternalModuleName(host, file) { - return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); - } - ts.getResolvedExternalModuleName = getResolvedExternalModuleName; - function getExternalModuleNameFromDeclaration(host, resolver, declaration) { - var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || ts.isDeclarationFile(file)) { - return undefined; - } - return getResolvedExternalModuleName(host, file); - } - ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); - var entities = { - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }; // Flags enum to track count of temp variables and a few dedicated names var TempFlags; (function (TempFlags) { @@ -35831,15 +54335,15 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var CopyDirection; - (function (CopyDirection) { - CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; - CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; - })(CopyDirection || (CopyDirection = {})); // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature function emitFiles(resolver, host, targetSourceFile) { + var delimiters = createDelimiterMap(); + var brackets = createBracketsMap(); // emit output for the __extends helper function var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; + // Emit output for the __assign helper function. + // This is typically used for JSX spread attributes, + // and can be used for object literal spread properties. var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; // emit output for the __decorate helper function var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; @@ -35847,7071 +54351,130 @@ var ts; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; + // emit output for the __awaiter helper function var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // thisArg The value to use as the `this` binding for the transformed generator body. + // body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; + // emit output for the __export helper function + var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; + // emit output for the UMD helper function. + var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; + var superHelper = "\nconst _super = name => super[name];"; + var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); - var emitSkipped = false; var newLine = host.getNewLine(); - var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); + var transformers = ts.getTransformers(compilerOptions); + var writer = ts.createTextWriter(newLine); + var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = ts.createSourceMapWriter(host, writer); + var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var comments = ts.createCommentWriter(host, writer, sourceMap); + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var nodeIdToGeneratedName; + var autoGeneratedIdToGeneratedName; + var generatedNameSet; + var tempFlags; + var currentSourceFile; + var currentText; + var currentFileIdentifiers; + var extendsEmitted; + var assignEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; + var isOwnFileEmit; + var emitSkipped = false; + ts.performance.mark("beforeTransform"); + // Transform the source files + var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.measure("transformTime", "beforeTransform"); + // Extract helpers from the result + var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; + ts.performance.mark("beforePrint"); + // Emit each output file + ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); + // Clean up after transformation + transformed.dispose(); + ts.performance.measure("printTime", "beforePrint"); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList }; - function isUniqueLocalName(name, container) { - for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name)) { - // We conservatively include alias symbols to cover cases where they're emitted as locals - if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { - return false; - } - } - } - return true; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function hoistVariableDeclarationFromLoop(state, declaration) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(declaration.name); - function visit(node) { - if (node.kind === 69 /* Identifier */) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _a = 0, _b = node.elements; _a < _b.length; _a++) { - var element = _b[_a]; - visit(element.name); - } - } - } - } - function createFileEmitter() { - var writer = ts.createTextWriter(newLine); - var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; - var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); - var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; - var currentSourceFile; - var currentText; - var currentLineMap; - var currentFileIdentifiers; - var renamedDependencies; - var isEs6Module; - var isCurrentFileExternalModule; - // name of an exporter function if file is a System external module - // System.register([...], function () {...}) - // exporting in System modules looks like: - // export var x; ... x = 1 - // => - // var x;... exporter("x", x = 1) - var exportFunctionForFile; - var contextObjectForFile; - var generatedNameSet; - var nodeToGeneratedName; - var computedPropertyNamesToGeneratedNames; - var decoratedClassAliases; - var convertedLoopState; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; - var tempFlags = 0; - var tempVariables; - var tempParameters; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var detachedCommentsInfo; - /** Sourcemap data that will get encoded */ - var sourceMapData; - /** Is the file being emitted into its own file */ - var isOwnFileEmit; - /** If removeComments is true, no leading-comments needed to be emitted **/ - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; - var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, - _a[ts.ModuleKind.ES6] = emitES6Module, - _a[ts.ModuleKind.AMD] = emitAMDModule, - _a[ts.ModuleKind.System] = emitSystemModule, - _a[ts.ModuleKind.UMD] = emitUMDModule, - _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, - _a - ); - var bundleEmitDelegates = (_b = {}, - _b[ts.ModuleKind.ES6] = function () { }, - _b[ts.ModuleKind.AMD] = emitAMDModule, - _b[ts.ModuleKind.System] = emitSystemModule, - _b[ts.ModuleKind.UMD] = function () { }, - _b[ts.ModuleKind.CommonJS] = function () { }, - _b - ); - return doEmit; - function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = {}; - nodeToGeneratedName = []; - decoratedClassAliases = []; - isOwnFileEmit = !isBundledEmit; - // Emit helpers from all the files - if (isBundledEmit && modulekind) { - ts.forEach(sourceFiles, emitEmitHelpers); - } - // Do not call emit directly. It does not set the currentSourceFile. - ts.forEach(sourceFiles, emitSourceFile); - writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); - if (sourceMappingURL) { - write("//# sourceMappingURL=" + sourceMappingURL); - } - writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles); - // reset the state - sourceMap.reset(); - writer.reset(); - currentSourceFile = undefined; - currentText = undefined; - currentLineMap = undefined; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - generatedNameSet = undefined; - nodeToGeneratedName = undefined; - decoratedClassAliases = undefined; - computedPropertyNamesToGeneratedNames = undefined; - convertedLoopState = undefined; - extendsEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; - assignEmitted = false; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = undefined; - detachedCommentsInfo = undefined; - sourceMapData = undefined; - isEs6Module = false; - renamedDependencies = undefined; - isCurrentFileExternalModule = false; - } - function emitSourceFile(sourceFile) { - currentSourceFile = sourceFile; - currentText = sourceFile.text; - currentLineMap = ts.getLineStarts(sourceFile); - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; - renamedDependencies = sourceFile.renamedDependencies; - currentFileIdentifiers = sourceFile.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - setSourceFile(sourceFile); - emitNodeWithCommentsAndWithoutSourcemap(sourceFile); - } - function isUniqueName(name) { - return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); - } - // Return the next available name in the pattern _a ... _z, _0, _1, ... - // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. - // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. - function makeTempVariableName(flags) { - if (flags && !(tempFlags & flags)) { - var name_24 = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name_24)) { - tempFlags |= flags; - return name_24; - } - } - while (true) { - var count = tempFlags & 268435455 /* CountMask */; - tempFlags++; - // Skip over 'i' and 'n' - if (count !== 8 && count !== 13) { - var name_25 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_25)) { - return name_25; - } - } - } - } - // Generate a name that is unique within the current file and doesn't conflict with any names - // in global scope. The name is formed by adding an '_n' suffix to the specified base name, - // where n is a positive integer. Note that names generated by makeTempVariableName and - // makeUniqueName are guaranteed to never conflict. - function makeUniqueName(baseName) { - // Find the first unique 'name_n', where n is a positive number - if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { - baseName += "_"; - } - var i = 1; - while (true) { - var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - return generatedNameSet[generatedName] = generatedName; - } - i++; - } - } - function generateNameForModuleOrEnum(node) { - var name = node.name.text; - // Use module/enum name itself if it is unique, otherwise make a unique variation - return isUniqueLocalName(name, node) ? name : makeUniqueName(name); - } - function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 /* StringLiteral */ ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - return makeUniqueName(baseName); - } - function generateNameForExportDefault() { - return makeUniqueName("default"); - } - function generateNameForClassExpression() { - return makeUniqueName("class"); - } - function generateNameForNode(node) { - switch (node.kind) { - case 69 /* Identifier */: - return makeUniqueName(node.text); - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: - return generateNameForModuleOrEnum(node); - case 230 /* ImportDeclaration */: - case 236 /* ExportDeclaration */: - return generateNameForImportOrExportDeclaration(node); - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 235 /* ExportAssignment */: - return generateNameForExportDefault(); - case 192 /* ClassExpression */: - return generateNameForClassExpression(); - default: - ts.Debug.fail(); - } - } - function getGeneratedNameForNode(node) { - var id = ts.getNodeId(node); - return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); - } - /** Write emitted output to disk */ - function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark, sourceFiles) { - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); - } - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); - } - ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark, sourceFiles); - } - // Create a temporary variable with a unique unused name. - function createTempVariable(flags) { - var result = ts.createSynthesizedNode(69 /* Identifier */); - result.text = makeTempVariableName(flags); - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function createAndRecordTempVariable(flags) { - var temp = createTempVariable(flags); - recordTempDeclaration(temp); - return temp; - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - /** Emit the text for the given token that comes after startPos - * This by default writes the text provided with the given tokenKind - * but if optional emitFn callback is provided the text is emitted using the callback instead of default text - * @param tokenKind the kind of the token to search and emit - * @param startPos the position in the source to start searching for the token - * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - function emitToken(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - emitPos(tokenStartPos); - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - var tokenEndPos = tokenStartPos + tokenString.length; - emitPos(tokenEndPos); - return tokenEndPos; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitParenthesizedIf(node, parenthesized) { - if (parenthesized) { - write("("); - } - emit(node); - if (parenthesized) { - write(")"); - } - } - function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { - ts.Debug.assert(nodes.length > 0); - increaseIndent(); - if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - for (var i = 0, n = nodes.length; i < n; i++) { - if (i) { - if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { - write(", "); - } - else { - write(","); - writeLine(); - } - } - emit(nodes[i]); - } - if (nodes.hasTrailingComma && allowTrailingComma) { - write(","); - } - decreaseIndent(); - if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - } - function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) { - if (!emitNode) { - emitNode = emit; - } - for (var i = 0; i < count; i++) { - if (multiLine) { - if (i || leadingComma) { - write(","); - } - writeLine(); - } - else { - if (i || leadingComma) { - write(", "); - } - } - var node = nodes[start + i]; - // This emitting is to make sure we emit following comment properly - // ...(x, /*comment1*/ y)... - // ^ => node.pos - // "comment1" is not considered leading comment for "y" but rather - // considered as trailing comment of the previous node. - emitTrailingCommentsOfPosition(node.pos); - emitNode(node); - leadingComma = true; - } - if (trailingComma) { - write(","); - } - if (multiLine && !noTrailingNewLine) { - writeLine(); - } - return count; - } - function emitCommaList(nodes) { - if (nodes) { - emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false); - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, /*startIndex*/ 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(node, text) { - if (node.kind === 8 /* NumericLiteral */ && text.length > 1) { - switch (text.charCodeAt(1)) { - case 98 /* b */: - case 66 /* B */: - case 111 /* o */: - case 79 /* O */: - return true; - } - } - return false; - } - function emitLiteral(node) { - var text = getLiteralText(node); - if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { - write(node.text); - } - else { - write(text); - } - } - function getLiteralText(node) { - // Any template literal or string literal with an extended escape - // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. - if (languageVersion < 2 /* ES6 */ && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { - return getQuotedEscapedLiteralText('"', node.text, '"'); - } - // If we don't need to downlevel and we can reach the original source text using - // the node's parent reference, then simply get the text as it was originally written. - if (node.parent) { - return ts.getTextOfNodeFromSourceText(currentText, node); - } - // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. - switch (node.kind) { - case 9 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText("`", node.text, "`"); - case 12 /* TemplateHead */: - return getQuotedEscapedLiteralText("`", node.text, "${"); - case 13 /* TemplateMiddle */: - return getQuotedEscapedLiteralText("}", node.text, "${"); - case 14 /* TemplateTail */: - return getQuotedEscapedLiteralText("}", node.text, "`"); - case 8 /* NumericLiteral */: - return node.text; - } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); - } - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; - } - function emitDownlevelRawTemplateLiteral(node) { - // Find original source text, since we need to emit the raw strings of the tagged template. - // The raw strings contain the (escaped) strings of what the user wrote. - // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = ts.getTextOfNodeFromSourceText(currentText, node); - // text contains the original source, it will also contain quotes ("`"), dollar signs and braces ("${" and "}"), - // thus we need to remove those characters. - // First template piece starts with "`", others with "}" - // Last template piece ends with "`", others with "${" - var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - // Newline normalization: - // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's - // and LineTerminatorSequences are normalized to for both TV and TRV. - text = text.replace(/\r\n?/g, "\n"); - text = ts.escapeString(text); - write("\"" + text + "\""); - } - function emitDownlevelTaggedTemplateArray(node, literalEmitter) { - write("["); - if (node.template.kind === 11 /* NoSubstitutionTemplateLiteral */) { - literalEmitter(node.template); - } - else { - literalEmitter(node.template.head); - ts.forEach(node.template.templateSpans, function (child) { - write(", "); - literalEmitter(child.literal); - }); - } - write("]"); - } - function emitDownlevelTaggedTemplate(node) { - var tempVariable = createAndRecordTempVariable(0 /* Auto */); - write("("); - emit(tempVariable); - write(" = "); - emitDownlevelTaggedTemplateArray(node, emit); - write(", "); - emit(tempVariable); - write(".raw = "); - emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral); - write(", "); - emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); - write("("); - emit(tempVariable); - // Now we emit the expressions - if (node.template.kind === 189 /* TemplateExpression */) { - ts.forEach(node.template.templateSpans, function (templateSpan) { - write(", "); - var needsParens = templateSpan.expression.kind === 187 /* BinaryExpression */ - && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; - emitParenthesizedIf(templateSpan.expression, needsParens); - }); - } - write("))"); - } - function emitTemplateExpression(node) { - // In ES6 mode and above, we can simply emit each portion of a template in order, but in - // ES3 & ES5 we must convert the template expression into a series of string concatenations. - if (languageVersion >= 2 /* ES6 */) { - ts.forEachChild(node, emit); - return; - } - var emitOuterParens = ts.isExpression(node.parent) - && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - var headEmitted = false; - if (shouldEmitTemplateHead()) { - emitLiteral(node.head); - headEmitted = true; - } - for (var i = 0, n = node.templateSpans.length; i < n; i++) { - var templateSpan = node.templateSpans[i]; - // Check if the expression has operands and binds its operands less closely than binary '+'. - // If it does, we need to wrap the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 178 /* ParenthesizedExpression */ - && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; - if (i > 0 || headEmitted) { - // If this is the first span and the head was not emitted, then this templateSpan's - // expression will be the first to be emitted. Don't emit the preceding ' + ' in that - // case. - write(" + "); - } - emitParenthesizedIf(templateSpan.expression, needsParens); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - } - if (emitOuterParens) { - write(")"); - } - function shouldEmitTemplateHead() { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - return parent.expression === template; - case 176 /* TaggedTemplateExpression */: - case 178 /* ParenthesizedExpression */: - return false; - default: - return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; - } - } - /** - * Returns whether the expression has lesser, greater, - * or equal precedence to the binary '+' operator - */ - function comparePrecedenceToBinaryPlus(expression) { - // All binary expressions have lower precedence than '+' apart from '*', '/', and '%' - // which have greater precedence and '-' which has equal precedence. - // All unary operators have a higher precedence apart from yield. - // Arrow functions and conditionals have a lower precedence, - // although we convert the former into regular function expressions in ES5 mode, - // and in ES6 mode this function won't get called anyway. - // - // TODO (drosen): Note that we need to account for the upcoming 'yield' and - // spread ('...') unary operators that are anticipated for ES6. - switch (expression.kind) { - case 187 /* BinaryExpression */: - switch (expression.operatorToken.kind) { - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: - return 1 /* GreaterThan */; - case 35 /* PlusToken */: - case 36 /* MinusToken */: - return 0 /* EqualTo */; - default: - return -1 /* LessThan */; - } - case 190 /* YieldExpression */: - case 188 /* ConditionalExpression */: - return -1 /* LessThan */; - default: - return 1 /* GreaterThan */; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - function jsxEmitReact(node) { - /// Emit a tag name, which is either '"div"' for lower-cased names, or - /// 'Div' for upper-cased or dotted names - function emitTagName(name) { - if (name.kind === 69 /* Identifier */ && ts.isIntrinsicJsxName(name.text)) { - write('"'); - emit(name); - write('"'); - } - else { - emit(name); - } - } - /// Emit an attribute name, which is quoted if it needs to be quoted. Because - /// these emit into an object literal property name, we don't need to be worried - /// about keywords, just non-identifier characters - function emitAttributeName(name) { - if (/^[A-Za-z_]\w*$/.test(name.text)) { - emit(name); - } - else { - write('"'); - emit(name); - write('"'); - } - } - /// Emit an name/value pair for an attribute (e.g. "x: 3") - function emitJsxAttribute(node) { - emitAttributeName(node.name); - write(": "); - if (node.initializer) { - emit(node.initializer); - } - else { - write("true"); - } - } - function emitJsxElement(openingNode, children) { - var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); - syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; - syntheticReactRef.parent = openingNode; - // Call React.createElement(tag, ... - emitLeadingComments(openingNode); - emitExpressionIdentifier(syntheticReactRef); - write(".createElement("); - emitTagName(openingNode.tagName); - write(", "); - // Attribute list - if (openingNode.attributes.length === 0) { - // When there are no attributes, React wants "null" - write("null"); - } - else { - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper - var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 247 /* JsxSpreadAttribute */; })) { - write("__assign("); - var haveOpenedObjectLiteral = false; - for (var i = 0; i < attrs.length; i++) { - if (attrs[i].kind === 247 /* JsxSpreadAttribute */) { - // If this is the first argument, we need to emit a {} as the first argument - if (i === 0) { - write("{}, "); - } - if (haveOpenedObjectLiteral) { - write("}"); - haveOpenedObjectLiteral = false; - } - if (i > 0) { - write(", "); - } - emit(attrs[i].expression); - } - else { - ts.Debug.assert(attrs[i].kind === 246 /* JsxAttribute */); - if (haveOpenedObjectLiteral) { - write(", "); - } - else { - haveOpenedObjectLiteral = true; - if (i > 0) { - write(", "); - } - write("{"); - } - emitJsxAttribute(attrs[i]); - } - } - if (haveOpenedObjectLiteral) - write("}"); - write(")"); // closing paren to React.__spread( - } - else { - // One object literal with all the attributes in them - write("{"); - for (var i = 0, n = attrs.length; i < n; i++) { - if (i > 0) { - write(", "); - } - emitJsxAttribute(attrs[i]); - } - write("}"); - } - } - // Children - if (children) { - var firstChild = void 0; - var multipleEmittableChildren = false; - for (var i = 0, n = children.length; i < n; i++) { - var jsxChild = children[i]; - if (isJsxChildEmittable(jsxChild)) { - // we need to decide whether to emit in single line or multiple lines as indented list - // store firstChild reference, if we see another emittable child, then emit accordingly - if (!firstChild) { - write(", "); - firstChild = jsxChild; - } - else { - // more than one emittable child, emit indented list - if (!multipleEmittableChildren) { - multipleEmittableChildren = true; - increaseIndent(); - writeLine(); - emit(firstChild); - } - write(", "); - writeLine(); - emit(jsxChild); - } - } - } - if (multipleEmittableChildren) { - decreaseIndent(); - } - else if (firstChild) { - if (firstChild.kind !== 241 /* JsxElement */ && firstChild.kind !== 242 /* JsxSelfClosingElement */) { - emit(firstChild); - } - else { - // If the only child is jsx element, put it on a new indented line - increaseIndent(); - writeLine(); - emit(firstChild); - writeLine(); - decreaseIndent(); - } - } - } - // Closing paren - write(")"); // closes "React.createElement(" - emitTrailingComments(openingNode); - } - if (node.kind === 241 /* JsxElement */) { - emitJsxElement(node.openingElement, node.children); - } - else { - ts.Debug.assert(node.kind === 242 /* JsxSelfClosingElement */); - emitJsxElement(node); - } - } - function jsxEmitPreserve(node) { - function emitJsxAttribute(node) { - emit(node.name); - if (node.initializer) { - write("="); - emit(node.initializer); - } - } - function emitJsxSpreadAttribute(node) { - write("{..."); - emit(node.expression); - write("}"); - } - function emitAttributes(attribs) { - for (var i = 0, n = attribs.length; i < n; i++) { - if (i > 0) { - write(" "); - } - if (attribs[i].kind === 247 /* JsxSpreadAttribute */) { - emitJsxSpreadAttribute(attribs[i]); - } - else { - ts.Debug.assert(attribs[i].kind === 246 /* JsxAttribute */); - emitJsxAttribute(attribs[i]); - } - } - } - function emitJsxOpeningOrSelfClosingElement(node) { - write("<"); - emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 242 /* JsxSelfClosingElement */)) { - write(" "); - } - emitAttributes(node.attributes); - if (node.kind === 242 /* JsxSelfClosingElement */) { - write("/>"); - } - else { - write(">"); - } - } - function emitJsxClosingElement(node) { - write(""); - } - function emitJsxElement(node) { - emitJsxOpeningOrSelfClosingElement(node.openingElement); - for (var i = 0, n = node.children.length; i < n; i++) { - emit(node.children[i]); - } - emitJsxClosingElement(node.closingElement); - } - if (node.kind === 241 /* JsxElement */) { - emitJsxElement(node); - } - else { - ts.Debug.assert(node.kind === 242 /* JsxSelfClosingElement */); - emitJsxOpeningOrSelfClosingElement(node); - } - } - // This function specifically handles numeric/string literals for enum and accessor 'identifiers'. - // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. - // For example, this is utilized when feeding in a result to Object.defineProperty. - function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 169 /* BindingElement */); - if (node.kind === 9 /* StringLiteral */) { - emitLiteral(node); - } - else if (node.kind === 140 /* ComputedPropertyName */) { - // if this is a decorated computed property, we will need to capture the result - // of the property expression so that we can apply decorators later. This is to ensure - // we don't introduce unintended side effects: - // - // class C { - // [_a = x]() { } - // } - // - // The emit for the decorated computed property decorator is: - // - // __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a)); - // - if (ts.nodeIsDecorated(node.parent)) { - if (!computedPropertyNamesToGeneratedNames) { - computedPropertyNamesToGeneratedNames = []; - } - var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)]; - if (generatedName) { - // we have already generated a variable for this node, write that value instead. - write(generatedName); - return; - } - generatedName = createAndRecordTempVariable(0 /* Auto */).text; - computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName; - write(generatedName); - write(" = "); - } - emit(node.expression); - } - else { - write('"'); - if (node.kind === 8 /* NumericLiteral */) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - write('"'); - } - } - function isExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 170 /* ArrayLiteralExpression */: - case 195 /* AsExpression */: - case 184 /* AwaitExpression */: - case 187 /* BinaryExpression */: - case 174 /* CallExpression */: - case 249 /* CaseClause */: - case 140 /* ComputedPropertyName */: - case 188 /* ConditionalExpression */: - case 143 /* Decorator */: - case 181 /* DeleteExpression */: - case 204 /* DoStatement */: - case 173 /* ElementAccessExpression */: - case 235 /* ExportAssignment */: - case 202 /* ExpressionStatement */: - case 194 /* ExpressionWithTypeArguments */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 203 /* IfStatement */: - case 245 /* JsxClosingElement */: - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: - case 247 /* JsxSpreadAttribute */: - case 248 /* JsxExpression */: - case 175 /* NewExpression */: - case 196 /* NonNullExpression */: - case 178 /* ParenthesizedExpression */: - case 186 /* PostfixUnaryExpression */: - case 185 /* PrefixUnaryExpression */: - case 211 /* ReturnStatement */: - case 254 /* ShorthandPropertyAssignment */: - case 191 /* SpreadElementExpression */: - case 213 /* SwitchStatement */: - case 176 /* TaggedTemplateExpression */: - case 197 /* TemplateSpan */: - case 215 /* ThrowStatement */: - case 177 /* TypeAssertionExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 190 /* YieldExpression */: - return true; - case 169 /* BindingElement */: - case 255 /* EnumMember */: - case 142 /* Parameter */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 218 /* VariableDeclaration */: - return parent.initializer === node; - case 172 /* PropertyAccessExpression */: - return parent.expression === node; - case 180 /* ArrowFunction */: - case 179 /* FunctionExpression */: - return parent.body === node; - case 229 /* ImportEqualsDeclaration */: - return parent.moduleReference === node; - case 139 /* QualifiedName */: - return parent.left === node; - } - return false; - } - function emitExpressionIdentifier(node) { - var container = resolver.getReferencedExportContainer(node); - if (container) { - if (container.kind === 256 /* SourceFile */) { - // Identifier references module export - if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - else { - // Identifier references namespace export - write(getGeneratedNameForNode(container)); - write("."); - } - } - else { - if (modulekind !== ts.ModuleKind.ES6) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (declaration.kind === 231 /* ImportClause */) { - // Identifier references default import - write(getGeneratedNameForNode(declaration.parent)); - write(languageVersion === 0 /* ES3 */ ? '["default"]' : ".default"); - return; - } - else if (declaration.kind === 234 /* ImportSpecifier */) { - // Identifier references named import - write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_26 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_26); - if (languageVersion === 0 /* ES3 */ && identifier === "default") { - write('["default"]'); - } - else { - write("."); - write(identifier); - } - return; - } - } - } - if (languageVersion < 2 /* ES6 */) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - else if (resolver.getNodeCheckFlags(node) & 1048576 /* BodyScopedClassBinding */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; - if (classAlias !== undefined) { - write(classAlias); - return; - } - } - } - } - if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { - if (languageVersion < 2 /* ES6 */) { - var parent_13 = node.parent; - switch (parent_13.kind) { - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 218 /* VariableDeclaration */: - return parent_13.name === node && resolver.isDeclarationWithCollidingName(parent_13); - } - } - return false; - } - function getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node) { - if (languageVersion >= 2 /* ES6 */) { - var parent_14 = node.parent; - if (parent_14.kind === 172 /* PropertyAccessExpression */ && parent_14.expression === node) { - parent_14 = parent_14.parent; - while (parent_14 && parent_14.kind !== 145 /* PropertyDeclaration */) { - parent_14 = parent_14.parent; - } - return parent_14 && parent_14.kind === 145 /* PropertyDeclaration */ && (parent_14.flags & 32 /* Static */) !== 0 && - parent_14.parent.kind === 192 /* ClassExpression */ ? parent_14.parent : undefined; - } - } - return undefined; - } - function emitIdentifier(node) { - if (convertedLoopState) { - if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - // in converted loop body arguments cannot be used directly. - var name_27 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_27); - return; - } - } - if (!node.parent) { - write(node.text); - } - else if (isExpressionIdentifier(node)) { - var classExpression = getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node); - if (classExpression) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration === classExpression) { - write(getGeneratedNameForNode(declaration.name)); - return; - } - } - emitExpressionIdentifier(node); - } - else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { - write(getGeneratedNameForNode(node)); - } - else if (ts.nodeIsSynthesized(node)) { - write(node.text); - } - else { - writeTextOfNode(currentText, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { - write("_this"); - } - else if (convertedLoopState) { - write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); - } - else { - write("this"); - } - } - function emitSuper(node) { - if (languageVersion >= 2 /* ES6 */) { - write("super"); - } - else { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 256 /* SuperInstance */) { - write("_super.prototype"); - } - else { - write("_super"); - } - } - } - function emitObjectBindingPattern(node) { - write("{ "); - var elements = node.elements; - emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - var elements = node.elements; - emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); - write("]"); - } - function emitBindingElement(node) { - if (node.propertyName) { - emit(node.propertyName); - write(": "); - } - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emit(node.name); - } - else { - emitModuleMemberName(node); - } - emitOptional(" = ", node.initializer); - } - function emitSpreadElementExpression(node) { - write("..."); - emit(node.expression); - } - function emitYieldExpression(node) { - write(ts.tokenToString(114 /* YieldKeyword */)); - if (node.asteriskToken) { - write("*"); - } - if (node.expression) { - write(" "); - emit(node.expression); - } - } - function emitAwaitExpression(node) { - var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); - if (needsParenthesis) { - write("("); - } - write(ts.tokenToString(114 /* YieldKeyword */)); - write(" "); - emit(node.expression); - if (needsParenthesis) { - write(")"); - } - } - function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 187 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { - return true; - } - else if (node.parent.kind === 188 /* ConditionalExpression */ && node.parent.condition === node) { - return true; - } - return false; - } - function needsParenthesisForPropertyAccessOrInvocation(node) { - switch (node.kind) { - case 69 /* Identifier */: - case 170 /* ArrayLiteralExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: - case 174 /* CallExpression */: - case 178 /* ParenthesizedExpression */: - // This list is not exhaustive and only includes those cases that are relevant - // to the check in emitArrayLiteral. More cases can be added as needed. - return false; - } - return true; - } - function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { - var pos = 0; - var group = 0; - var length = elements.length; - while (pos < length) { - // Emit using the pattern .concat(, , ...) - if (group === 1 && useConcat) { - write(".concat("); - } - else if (group > 0) { - write(", "); - } - var e = elements[pos]; - if (e.kind === 191 /* SpreadElementExpression */) { - e = e.expression; - emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); - pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 170 /* ArrayLiteralExpression */) { - write(".slice()"); - } - } - else { - var i = pos; - while (i < length && elements[i].kind !== 191 /* SpreadElementExpression */) { - i++; - } - write("["); - if (multiLine) { - increaseIndent(); - } - emitList(elements, pos, i - pos, multiLine, trailingComma && i === length); - if (multiLine) { - decreaseIndent(); - } - write("]"); - pos = i; - } - group++; - } - if (group > 1) { - if (useConcat) { - write(")"); - } - } - } - function isSpreadElementExpression(node) { - return node.kind === 191 /* SpreadElementExpression */; - } - function emitArrayLiteral(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { - write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false); - write("]"); - } - else { - emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ node.multiLine, - /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); - } - } - function emitObjectLiteralBody(node, numElements) { - if (numElements === 0) { - write("{}"); - return; - } - write("{"); - if (numElements > 0) { - var properties = node.properties; - // If we are not doing a downlevel transformation for object literals, - // then try to preserve the original shape of the object literal. - // Otherwise just try to preserve the formatting. - if (numElements === properties.length) { - emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= 1 /* ES5 */, /*spacesBetweenBraces*/ true); - } - else { - var multiLine = node.multiLine; - if (!multiLine) { - write(" "); - } - else { - increaseIndent(); - } - emitList(properties, 0, numElements, /*multiLine*/ multiLine, /*trailingComma*/ false); - if (!multiLine) { - write(" "); - } - else { - decreaseIndent(); - } - } - } - write("}"); - } - function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = node.multiLine; - var properties = node.properties; - write("("); - if (multiLine) { - increaseIndent(); - } - // For computed properties, we need to create a unique handle to the object - // literal so we can modify it without risking internal assignments tainting the object. - var tempVar = createAndRecordTempVariable(0 /* Auto */); - // Write out the first non-computed properties - // (or all properties if none of them are computed), - // then emit the rest through indexing on the temp variable. - emit(tempVar); - write(" = "); - emitObjectLiteralBody(node, firstComputedPropertyIndex); - for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); - var property = properties[i]; - emitStart(property); - if (property.kind === 149 /* GetAccessor */ || property.kind === 150 /* SetAccessor */) { - // TODO (drosen): Reconcile with 'emitMemberFunctions'. - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property !== accessors.firstAccessor) { - continue; - } - write("Object.defineProperty("); - emit(tempVar); - write(", "); - emitStart(property.name); - emitExpressionForPropertyName(property.name); - emitEnd(property.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("})"); - emitEnd(property); - } - else { - emitLeadingComments(property); - emitStart(property.name); - emit(tempVar); - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - if (property.kind === 253 /* PropertyAssignment */) { - emit(property.initializer); - } - else if (property.kind === 254 /* ShorthandPropertyAssignment */) { - emitExpressionIdentifier(property.name); - } - else if (property.kind === 147 /* MethodDeclaration */) { - emitFunctionDeclaration(property); - } - else { - ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); - } - } - emitEnd(property); - } - writeComma(); - emit(tempVar); - if (multiLine) { - decreaseIndent(); - writeLine(); - } - write(")"); - function writeComma() { - if (multiLine) { - write(","); - writeLine(); - } - else { - write(", "); - } - } - } - function emitObjectLiteral(node) { - var properties = node.properties; - if (languageVersion < 2 /* ES6 */) { - var numProperties = properties.length; - // Find the first computed property. - // Everything until that point can be emitted as part of the initial object literal. - var numInitialNonComputedProperties = numProperties; - for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 140 /* ComputedPropertyName */) { - numInitialNonComputedProperties = i; - break; - } - } - var hasComputedProperty = numInitialNonComputedProperties !== properties.length; - if (hasComputedProperty) { - emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); - return; - } - } - // Ordinary case: either the object has no computed properties - // or we're compiling with an ES6+ target. - emitObjectLiteralBody(node, properties.length); - } - function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(187 /* BinaryExpression */, startsOnNewLine); - result.operatorToken = ts.createSynthesizedNode(operator); - result.left = left; - result.right = right; - return result; - } - function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(172 /* PropertyAccessExpression */); - result.expression = parenthesizeForAccess(expression); - result.name = name; - return result; - } - function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(173 /* ElementAccessExpression */); - result.expression = parenthesizeForAccess(expression); - result.argumentExpression = argumentExpression; - return result; - } - function parenthesizeForAccess(expr) { - // When diagnosing whether the expression needs parentheses, the decision should be based - // on the innermost expression in a chain of nested type assertions. - while (expr.kind === 177 /* TypeAssertionExpression */ || - expr.kind === 195 /* AsExpression */ || - expr.kind === 196 /* NonNullExpression */) { - expr = expr.expression; - } - // isLeftHandSideExpression is almost the correct criterion for when it is not necessary - // to parenthesize the expression before a dot. The known exceptions are: - // - // NewExpression: - // new C.x -> not the same as (new C).x - // NumberLiteral - // 1.x -> not the same as (1).x - // - if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 175 /* NewExpression */ && - expr.kind !== 8 /* NumericLiteral */) { - return expr; - } - var node = ts.createSynthesizedNode(178 /* ParenthesizedExpression */); - node.expression = expr; - return node; - } - function emitComputedPropertyName(node) { - write("["); - emitExpressionForPropertyName(node); - write("]"); - } - function emitMethod(node) { - if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { - write("*"); - } - emit(node.name); - if (languageVersion < 2 /* ES6 */) { - write(": function "); - } - emitSignatureAndBody(node); - } - function emitPropertyAssignment(node) { - emit(node.name); - write(": "); - // This is to ensure that we emit comment in the following case: - // For example: - // obj = { - // id: /*comment1*/ ()=>void - // } - // "comment1" is not considered to be leading comment for node.initializer - // but rather a trailing comment on the previous node. - emitTrailingCommentsOfPosition(node.initializer.pos); - emit(node.initializer); - } - // Return true if identifier resolves to an exported member of a namespace - function isExportReference(node) { - var container = resolver.getReferencedExportContainer(node); - return !!container; - } - // Return true if identifier resolves to an imported identifier - function isImportedReference(node) { - var declaration = resolver.getReferencedImportDeclaration(node); - return declaration && (declaration.kind === 231 /* ImportClause */ || declaration.kind === 234 /* ImportSpecifier */); - } - function emitShorthandPropertyAssignment(node) { - // The name property of a short-hand property assignment is considered an expression position, so here - // we manually emit the identifier to avoid rewriting. - writeTextOfNode(currentText, node.name); - // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier, - // we emit a normal property assignment. For example: - // module m { - // export let y; - // } - // module m { - // let obj = { y }; - // } - // Here we need to emit obj = { y : m.y } regardless of the output target. - // The same rules apply for imported identifiers when targeting module formats with indirect access to - // the imported identifiers. For example, when targeting CommonJS: - // - // import {foo} from './foo'; - // export const baz = { foo }; - // - // Must be transformed into: - // - // const foo_1 = require('./foo'); - // exports.baz = { foo: foo_1.foo }; - // - if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { - // Emit identifier as an identifier - write(": "); - emitExpressionIdentifier(node.name); - } - if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) { - write(" = "); - emit(node.objectAssignmentInitializer); - } - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(constantValue.toString()); - if (!compilerOptions.removeComments) { - var propertyName = node.kind === 172 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return node.kind === 172 /* PropertyAccessExpression */ || node.kind === 173 /* ElementAccessExpression */ - ? resolver.getConstantValue(node) - : undefined; - } - // Returns 'true' if the code was actually indented, false otherwise. - // If the code is not indented, an optional valueToWriteWhenNotIndenting will be - // emitted instead. - function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) { - var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); - // Always use a newline for synthesized code if the synthesizer desires it. - var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); - if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { - increaseIndent(); - writeLine(); - return true; - } - else { - if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); - } - return false; - } - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 /* ES6 */ && - node.expression.kind === 95 /* SuperKeyword */ && - isInAsyncMethodWithSuperInES6(node)) { - var name_28 = ts.createSynthesizedNode(9 /* StringLiteral */); - name_28.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_28); - return; - } - emit(node.expression); - var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; - var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); - // 1 .toString is a valid property access, emit a space after the literal - // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal - var shouldEmitSpace = false; - if (!indentedBeforeDot) { - if (node.expression.kind === 8 /* NumericLiteral */) { - // check if numeric literal was originally written with a dot - var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); - shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; - } - else { - // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(node.expression); - // isFinite handles cases when constantValue is undefined - shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; - } - } - if (shouldEmitSpace) { - write(" ."); - } - else { - write("."); - } - var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); - emit(node.name); - decreaseIndentIf(indentedBeforeDot, indentedAfterDot); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitQualifiedNameAsExpression(node, useFallback) { - if (node.left.kind === 69 /* Identifier */) { - emitEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = createAndRecordTempVariable(0 /* Auto */); - write("("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(node.left, /*useFallback*/ true); - write(") && "); - emitNodeWithoutSourceMap(temp); - } - else { - emitEntityNameAsExpression(node.left, /*useFallback*/ false); - } - write("."); - emit(node.right); - } - function emitEntityNameAsExpression(node, useFallback) { - switch (node.kind) { - case 69 /* Identifier */: - if (useFallback) { - write("typeof "); - emitExpressionIdentifier(node); - write(" !== 'undefined' && "); - } - emitExpressionIdentifier(node); - break; - case 139 /* QualifiedName */: - emitQualifiedNameAsExpression(node, useFallback); - break; - default: - emitNodeWithoutSourceMap(node); - break; - } - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - if (languageVersion === 2 /* ES6 */ && - node.expression.kind === 95 /* SuperKeyword */ && - isInAsyncMethodWithSuperInES6(node)) { - emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 191 /* SpreadElementExpression */; }); - } - function skipParentheses(node) { - while (node.kind === 178 /* ParenthesizedExpression */ || - node.kind === 177 /* TypeAssertionExpression */ || - node.kind === 195 /* AsExpression */ || - node.kind === 196 /* NonNullExpression */) { - node = node.expression; - } - return node; - } - function emitCallTarget(node) { - if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || node.kind === 95 /* SuperKeyword */) { - emit(node); - return node; - } - var temp = createAndRecordTempVariable(0 /* Auto */); - write("("); - emit(temp); - write(" = "); - emit(node); - write(")"); - return temp; - } - function emitCallWithSpread(node) { - var target; - var expr = skipParentheses(node.expression); - if (expr.kind === 172 /* PropertyAccessExpression */) { - // Target will be emitted as "this" argument - target = emitCallTarget(expr.expression); - write("."); - emit(expr.name); - } - else if (expr.kind === 173 /* ElementAccessExpression */) { - // Target will be emitted as "this" argument - target = emitCallTarget(expr.expression); - write("["); - emit(expr.argumentExpression); - write("]"); - } - else if (expr.kind === 95 /* SuperKeyword */) { - target = expr; - write("_super"); - } - else { - emit(node.expression); - } - write(".apply("); - if (target) { - if (target.kind === 95 /* SuperKeyword */) { - // Calls of form super(...) and super.foo(...) - emitThis(target); - } - else { - // Calls of form obj.foo(...) - emit(target); - } - } - else { - // Calls of form foo(...) - write("void 0"); - } - write(", "); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true); - write(")"); - } - function isInAsyncMethodWithSuperInES6(node) { - if (languageVersion === 2 /* ES6 */) { - var container = ts.getSuperContainer(node, /*includeFunctions*/ false); - if (container && resolver.getNodeCheckFlags(container) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */)) { - return true; - } - } - return false; - } - function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { - var container = ts.getSuperContainer(superNode, /*includeFunctions*/ false); - var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096 /* AsyncMethodWithSuperBinding */; - write("_super("); - emit(argumentExpression); - write(isSuperBinding ? ").value" : ")"); - } - function emitCallExpression(node) { - if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) { - emitCallWithSpread(node); - return; - } - var expression = node.expression; - var superCall = false; - var isAsyncMethodWithSuper = false; - if (expression.kind === 95 /* SuperKeyword */) { - emitSuper(expression); - superCall = true; - } - else { - superCall = ts.isSuperPropertyOrElementAccess(expression); - isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); - emit(expression); - } - if (superCall && (languageVersion < 2 /* ES6 */ || isAsyncMethodWithSuper)) { - write(".call("); - emitThis(expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - // Spread operator logic is supported in new expressions in ES5 using a combination - // of Function.prototype.bind() and Function.prototype.apply(). - // - // Example: - // - // var args = [1, 2, 3, 4, 5]; - // new Array(...args); - // - // is compiled into the following ES5: - // - // var args = [1, 2, 3, 4, 5]; - // new (Array.bind.apply(Array, [void 0].concat(args))); - // - // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new', - // Thus, we set it to undefined ('void 0'). - if (languageVersion === 1 /* ES5 */ && - node.arguments && - hasSpreadElement(node.arguments)) { - write("("); - var target = emitCallTarget(node.expression); - write(".bind.apply("); - emit(target); - write(", [void 0].concat("); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false); - write(")))"); - write("()"); - } - else { - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - } - function emitTaggedTemplateExpression(node) { - if (languageVersion >= 2 /* ES6 */) { - emit(node.tag); - write(" "); - emit(node.template); - } - else { - emitDownlevelTaggedTemplate(node); - } - } - function emitParenExpression(node) { - // If the node is synthesized, it means the emitter put the parentheses there, - // not the user. If we didn't want them, the emitter would not have put them - // there. - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 180 /* ArrowFunction */) { - if (node.expression.kind === 177 /* TypeAssertionExpression */ || - node.expression.kind === 195 /* AsExpression */ || - node.expression.kind === 196 /* NonNullExpression */) { - var operand = node.expression.expression; - // Make sure we consider all nested cast expressions, e.g.: - // (-A).x; - while (operand.kind === 177 /* TypeAssertionExpression */ || - operand.kind === 195 /* AsExpression */ || - operand.kind === 196 /* NonNullExpression */) { - operand = operand.expression; - } - // We have an expression of the form: (SubExpr) - // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is. - // Omitting the parentheses, however, could cause change in the semantics of the generated - // code if the casted expression has a lower precedence than the rest of the expression, e.g.: - // (new A).foo should be emitted as (new A).foo and not new A.foo - // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() - // new (A()) should be emitted as new (A()) and not new A() - // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () - if (operand.kind !== 185 /* PrefixUnaryExpression */ && - operand.kind !== 183 /* VoidExpression */ && - operand.kind !== 182 /* TypeOfExpression */ && - operand.kind !== 181 /* DeleteExpression */ && - operand.kind !== 186 /* PostfixUnaryExpression */ && - operand.kind !== 175 /* NewExpression */ && - !(operand.kind === 174 /* CallExpression */ && node.parent.kind === 175 /* NewExpression */) && - !(operand.kind === 179 /* FunctionExpression */ && node.parent.kind === 174 /* CallExpression */) && - !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 172 /* PropertyAccessExpression */)) { - emit(operand); - return; - } - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(78 /* DeleteKeyword */)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(103 /* VoidKeyword */)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(101 /* TypeOfKeyword */)); - write(" "); - emit(node.expression); - } - function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) { - if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { - return false; - } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 218 /* VariableDeclaration */ || node.parent.kind === 169 /* BindingElement */); - var targetDeclaration = isVariableDeclarationOrBindingElement - ? node.parent - : resolver.getReferencedValueDeclaration(node); - return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); - } - function isNameOfExportedDeclarationInNonES6Module(node) { - if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { - return false; - } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); - } - function emitPrefixUnaryExpression(node) { - var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ - || node.operator === 42 /* MinusMinusToken */); - var externalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - if (externalExportChanged) { - // emit - // ++x - // as - // exports('x', ++x) - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - } - var internalExportChanged = isPlusPlusOrMinusMinus && - isNameOfExportedDeclarationInNonES6Module(node.operand); - if (internalExportChanged) { - emitAliasEqual(node.operand); - } - write(ts.tokenToString(node.operator)); - // In some cases, we need to emit a space between the operator and the operand. One obvious case - // is when the operator is an identifier, like delete or typeof. We also need to do this for plus - // and minus expressions in certain cases. Specifically, consider the following two cases (parens - // are just for clarity of exposition, and not part of the source code): - // - // (+(+1)) - // (+(++1)) - // - // We need to emit a space in both cases. In the first case, the absence of a space will make - // the resulting expression a prefix increment operation. And in the second, it will make the resulting - // expression a prefix increment whose operand is a plus expression - (++(+x)) - // The same is true of minus of course. - if (node.operand.kind === 185 /* PrefixUnaryExpression */) { - var operand = node.operand; - if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { - write(" "); - } - else if (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */)) { - write(" "); - } - } - emit(node.operand); - if (externalExportChanged) { - write(")"); - } - } - function emitPostfixUnaryExpression(node) { - var externalExportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - var internalExportChanged = isNameOfExportedDeclarationInNonES6Module(node.operand); - if (externalExportChanged) { - // export function returns the value that was passes as the second argument - // however for postfix unary expressions result value should be the value before modification. - // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' - write("(" + exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - write(ts.tokenToString(node.operator)); - emit(node.operand); - if (node.operator === 41 /* PlusPlusToken */) { - write(") - 1)"); - } - else { - write(") + 1)"); - } - } - else if (internalExportChanged) { - emitAliasEqual(node.operand); - emit(node.operand); - if (node.operator === 41 /* PlusPlusToken */) { - write(" += 1"); - } - else { - write(" -= 1"); - } - } - else { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - } - function shouldHoistDeclarationInSystemJsModule(node) { - return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false); - } - /* - * Checks if given node is a source file level declaration (not nested in module/function). - * If 'isExported' is true - then declaration must also be exported. - * This function is used in two cases: - * - check if node is a exported source file level value to determine - * if we should also export the value after its it changed - * - check if node is a source level declaration to emit it differently, - * i.e non-exported variable statement 'var x = 1' is hoisted so - * we we emit variable statement 'var' should be dropped. - */ - function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { - if (!node || !isCurrentFileSystemExternalModule()) { - return false; - } - var current = ts.getRootDeclaration(node).parent; - while (current) { - if (current.kind === 256 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); - } - else if (ts.isDeclaration(current)) { - return false; - } - else { - current = current.parent; - } - } - } - /** - * Emit ES7 exponentiation operator downlevel using Math.pow - * @param node a binary expression node containing exponentiationOperator (**, **=) - */ - function emitExponentiationOperator(node) { - var leftHandSideExpression = node.left; - if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - var synthesizedLHS = void 0; - var shouldEmitParentheses = false; - if (ts.isElementAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(173 /* ElementAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); - synthesizedLHS.expression = identifier; - if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ && - leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) { - var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */); - synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true, leftHandSideExpression.expression); - } - else { - synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; - } - write(", "); - } - else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { - shouldEmitParentheses = true; - write("("); - synthesizedLHS = ts.createSynthesizedNode(172 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); - synthesizedLHS.expression = identifier; - synthesizedLHS.name = leftHandSideExpression.name; - write(", "); - } - emit(synthesizedLHS || leftHandSideExpression); - write(" = "); - write("Math.pow("); - emit(synthesizedLHS || leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - if (shouldEmitParentheses) { - write(")"); - } - } - else { - write("Math.pow("); - emit(leftHandSideExpression); - write(", "); - emit(node.right); - write(")"); - } - } - function emitAliasEqual(name) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - emitStart(specifier.name); - emitContainingModuleName(specifier); - if (languageVersion === 0 /* ES3 */ && name.text === "default") { - write('["default"]'); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - } - emitEnd(specifier.name); - write(" = "); - } - return true; - } - function emitBinaryExpression(node) { - if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ && - (node.left.kind === 171 /* ObjectLiteralExpression */ || node.left.kind === 170 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 202 /* ExpressionStatement */); - } - else { - var isAssignment = ts.isAssignmentOperator(node.operatorToken.kind); - var externalExportChanged = isAssignment && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left); - if (externalExportChanged) { - // emit assignment 'x y' as 'exports("x", x y)' - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.left); - write("\", "); - } - var internalExportChanged = isAssignment && - isNameOfExportedDeclarationInNonES6Module(node.left); - if (internalExportChanged) { - // export { foo } - // emit foo = 2 as exports.foo = foo = 2 - emitAliasEqual(node.left); - } - if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */ || node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - // Downleveled emit exponentiation operator using Math.pow - emitExponentiationOperator(node); - } - else { - emit(node.left); - // Add indentation before emit the operator if the operator is on different line - // For example: - // 3 - // + 2; - // emitted as - // 3 - // + 2; - var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 /* CommaToken */ ? " " : undefined); - write(ts.tokenToString(node.operatorToken.kind)); - var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); - emit(node.right); - decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); - } - if (externalExportChanged) { - write(")"); - } - } - } - function synthesizedNodeStartsOnNewLine(node) { - return ts.nodeIsSynthesized(node) && node.startsOnNewLine; - } - function emitConditionalExpression(node) { - emit(node.condition); - var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); - write("?"); - var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); - emit(node.whenTrue); - decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); - write(":"); - var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); - emit(node.whenFalse); - decreaseIndentIf(indentedBeforeColon, indentedAfterColon); - } - // Helper function to decrease the indent if we previously indented. Allows multiple - // previous indent values to be considered at a time. This also allows caller to just - // call this once, passing in all their appropriate indent values, instead of needing - // to call this helper function multiple times. - function decreaseIndentIf(value1, value2) { - if (value1) { - decreaseIndent(); - } - if (value2) { - decreaseIndent(); - } - } - function isSingleLineEmptyBlock(node) { - if (node && node.kind === 199 /* Block */) { - var block = node; - return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); - } - } - function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - emitToken(15 /* OpenBraceToken */, node.pos); - write(" "); - emitToken(16 /* CloseBraceToken */, node.statements.end); - return; - } - emitToken(15 /* OpenBraceToken */, node.pos); - increaseIndent(); - if (node.kind === 226 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 225 /* ModuleDeclaration */); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 226 /* ModuleBlock */) { - emitTempDeclarations(/*newLine*/ true); - } - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.statements.end); - } - function emitEmbeddedStatement(node) { - if (node.kind === 199 /* Block */) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 180 /* ArrowFunction */); - write(";"); - } - function emitIfStatement(node) { - var endPos = emitToken(88 /* IfKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - emit(node.expression); - emitToken(18 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(80 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 203 /* IfStatement */) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - } - function emitDoStatement(node) { - emitLoop(node, emitDoStatementWorker); - } - function emitDoStatementWorker(node, loop) { - write("do"); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - if (node.statement.kind === 199 /* Block */) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - emitLoop(node, emitWhileStatementWorker); - } - function emitWhileStatementWorker(node, loop) { - write("while ("); - emit(node.expression); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - } - /** - * Returns true if start of variable declaration list was emitted. - * Returns false if nothing was written - this can happen for source file level variable declarations - * in system modules where such variable declarations are hoisted. - */ - function tryEmitStartOfVariableDeclarationList(decl) { - if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) { - // variables in variable declaration list were already hoisted - return false; - } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072 /* BlockScoped */) === 0) { - // we are inside a converted loop - this can only happen in downlevel scenarios - // record names for all variable declarations - for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { - var varDecl = _b[_a]; - hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); - } - return false; - } - emitStart(decl); - if (decl && languageVersion >= 2 /* ES6 */) { - if (ts.isLet(decl)) { - write("let "); - } - else if (ts.isConst(decl)) { - write("const "); - } - else { - write("var "); - } - } - else { - write("var "); - } - // Note here we specifically dont emit end so that if we are going to emit binding pattern - // we can alter the source map correctly - return true; - } - function emitVariableDeclarationListSkippingUninitializedEntries(list) { - var started = false; - for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) { - var decl = _b[_a]; - if (!decl.initializer) { - continue; - } - if (!started) { - started = true; - } - else { - write(", "); - } - emit(decl); - } - return started; - } - function shouldConvertLoopBody(node) { - return languageVersion < 2 /* ES6 */ && - (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; - } - function emitLoop(node, loopEmitter) { - var shouldConvert = shouldConvertLoopBody(node); - if (!shouldConvert) { - loopEmitter(node, /* convertedLoop*/ undefined); - } - else { - var loop = convertLoopBody(node); - if (node.parent.kind === 214 /* LabeledStatement */) { - // if parent of the loop was labeled statement - attach the label to loop skipping converted loop body - emitLabelAndColon(node.parent); - } - loopEmitter(node, loop); - } - } - function convertLoopBody(node) { - var functionName = makeUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - var initializer = node.initializer; - if (initializer && initializer.kind === 219 /* VariableDeclarationList */) { - loopInitializer = node.initializer; - } - break; - } - var loopParameters; - var loopOutParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072 /* BlockScoped */)) { - // if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters - loopParameters = []; - for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { - var varDeclaration = _b[_a]; - processVariableDeclaration(varDeclaration.name); - } - } - var bodyIsBlock = node.statement.kind === 199 /* Block */; - var paramList = loopParameters ? loopParameters.join(", ") : ""; - writeLine(); - write("var " + functionName + " = function(" + paramList + ")"); - var convertedOuterLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (convertedOuterLoopState) { - // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. - // if outer converted loop has already accumulated some state - pass it through - if (convertedOuterLoopState.argumentsName) { - // outer loop has already used 'arguments' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; - } - if (convertedOuterLoopState.thisName) { - // outer loop has already used 'this' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.thisName = convertedOuterLoopState.thisName; - } - if (convertedOuterLoopState.hoistedLocalVariables) { - // we've already collected some non-block scoped variable declarations in enclosing loop - // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; - } - } - write(" {"); - writeLine(); - increaseIndent(); - if (bodyIsBlock) { - emitLines(node.statement.statements); - } - else { - emit(node.statement); - } - writeLine(); - // end of loop body -> copy out parameter - copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ true); - decreaseIndent(); - writeLine(); - write("};"); - writeLine(); - if (loopOutParameters) { - // declare variables to hold out params for loop body - write("var "); - for (var i = 0; i < loopOutParameters.length; i++) { - if (i !== 0) { - write(", "); - } - write(loopOutParameters[i].outParamName); - } - write(";"); - writeLine(); - } - if (convertedLoopState.argumentsName) { - // if alias for arguments is set - if (convertedOuterLoopState) { - // pass it to outer converted loop - convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; - } - else { - // this is top level converted loop and we need to create an alias for 'arguments' object - write("var " + convertedLoopState.argumentsName + " = arguments;"); - writeLine(); - } - } - if (convertedLoopState.thisName) { - // if alias for this is set - if (convertedOuterLoopState) { - // pass it to outer converted loop - convertedOuterLoopState.thisName = convertedLoopState.thisName; - } - else { - // this is top level converted loop so we need to create an alias for 'this' here - // NOTE: - // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. - // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - write("var " + convertedLoopState.thisName + " = this;"); - writeLine(); - } - } - if (convertedLoopState.hoistedLocalVariables) { - // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (convertedOuterLoopState) { - // pass them to outer converted loop - convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; - } - else { - // deduplicate and hoist collected variable declarations - write("var "); - var seen = void 0; - for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { - var id = _d[_c]; - // Don't initialize seen unless we have at least one element. - // Emit a comma to separate for all but the first element. - if (!seen) { - seen = {}; - } - else { - write(", "); - } - if (!ts.hasProperty(seen, id.text)) { - emit(id); - seen[id.text] = id.text; - } - } - write(";"); - writeLine(); - } - } - var currentLoopState = convertedLoopState; - convertedLoopState = convertedOuterLoopState; - return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function processVariableDeclaration(name) { - if (name.kind === 69 /* Identifier */) { - var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) - ? getGeneratedNameForNode(name) - : name.text; - loopParameters.push(nameText); - if (resolver.getNodeCheckFlags(name.parent) & 2097152 /* NeedsLoopOutParameter */) { - var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; - (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); - } - } - else { - for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { - var element = _b[_a]; - processVariableDeclaration(element.name); - } - } - } - } - function emitNormalLoopBody(node, emitAsEmbeddedStatement) { - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - // we get here if we are trying to emit normal loop loop inside converted loop - // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; - } - if (emitAsEmbeddedStatement) { - emitEmbeddedStatement(node.statement); - } - else if (node.statement.kind === 199 /* Block */) { - emitLines(node.statement.statements); - } - else { - writeLine(); - emit(node.statement); - } - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function copyLoopOutParameters(state, copyDirection, emitAsStatements) { - if (state.loopOutParameters) { - for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { - var outParam = _b[_a]; - if (copyDirection === 0 /* ToOriginal */) { - emitIdentifier(outParam.originalName); - write(" = " + outParam.outParamName); - } - else { - write(outParam.outParamName + " = "); - emitIdentifier(outParam.originalName); - } - if (emitAsStatements) { - write(";"); - writeLine(); - } - else { - write(", "); - } - } - } - } - function emitConvertedLoopCall(loop, emitAsBlock) { - if (emitAsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } - // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop - // simple loops are emitted as just 'loop()'; - // NOTE: if loop uses only 'continue' it still will be emitted as simple loop - var isSimpleLoop = !(loop.state.nonLocalJumps & ~4 /* Continue */) && - !loop.state.labeledNonLocalBreaks && - !loop.state.labeledNonLocalContinues; - var loopResult = makeUniqueName("state"); - if (!isSimpleLoop) { - write("var " + loopResult + " = "); - } - write(loop.functionName + "(" + loop.paramList + ");"); - writeLine(); - copyLoopOutParameters(loop.state, 0 /* ToOriginal */, /*emitAsStatements*/ true); - if (!isSimpleLoop) { - // for non simple loops we need to store result returned from converted loop function and use it to do dispatching - // converted loop function can return: - // - object - used when body of the converted loop contains return statement. Property "value" of this object stores retuned value - // - string - used to dispatch jumps. "break" and "continue" are used to non-labeled jumps, other values are used to transfer control to - // different labels - writeLine(); - if (loop.state.nonLocalJumps & 8 /* Return */) { - write("if (typeof " + loopResult + " === \"object\") "); - if (convertedLoopState) { - // we are currently nested in another converted loop - return unwrapped result - write("return " + loopResult + ";"); - // propagate 'hasReturn' flag to outer loop - convertedLoopState.nonLocalJumps |= 8 /* Return */; - } - else { - // top level converted loop - return unwrapped value - write("return " + loopResult + ".value;"); - } - writeLine(); - } - if (loop.state.nonLocalJumps & 2 /* Break */) { - write("if (" + loopResult + " === \"break\") break;"); - writeLine(); - } - // in case of labeled breaks emit code that either breaks to some known label inside outer loop or delegates jump decision to outer loop - emitDispatchTableForLabeledJumps(loopResult, loop.state, convertedLoopState); - } - if (emitAsBlock) { - writeLine(); - decreaseIndent(); - write("}"); - } - function emitDispatchTableForLabeledJumps(loopResultVariable, currentLoop, outerLoop) { - if (!currentLoop.labeledNonLocalBreaks && !currentLoop.labeledNonLocalContinues) { - return; - } - write("switch(" + loopResultVariable + ") {"); - increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop); - decreaseIndent(); - writeLine(); - write("}"); - } - function emitDispatchEntriesForLabeledJumps(table, isBreak, loopResultVariable, outerLoop) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - writeLine(); - write("case \"" + labelMarker + "\": "); - // if there are no outer converted loop or outer label in question is located inside outer converted loop - // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - if (isBreak) { - write("break "); - } - else { - write("continue "); - } - write(labelText + ";"); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - write("return " + loopResultVariable + ";"); - } - } - } - } - function emitForStatement(node) { - emitLoop(node, emitForStatementWorker); - } - function emitForStatementWorker(node, loop) { - var endPos = emitToken(86 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 219 /* VariableDeclarationList */) { - var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); - if (startIsEmitted) { - emitCommaList(variableDeclarationList.declarations); - } - else { - emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList); - } - } - else if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.incrementor); - write(")"); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - } - function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 208 /* ForOfStatement */) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } - else { - emitLoop(node, emitForInOrForOfStatementWorker); - } - } - function emitForInOrForOfStatementWorker(node, loop) { - var endPos = emitToken(86 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer.kind === 219 /* VariableDeclarationList */) { - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList); - emit(variableDeclarationList.declarations[0]); - } - } - else { - emit(node.initializer); - } - if (node.kind === 207 /* ForInStatement */) { - write(" in "); - } - else { - write(" of "); - } - emit(node.expression); - emitToken(18 /* CloseParenToken */, node.expression.end); - if (loop) { - emitConvertedLoopCall(loop, /*emitAsBlock*/ true); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); - } - } - function emitDownLevelForOfStatementWorker(node, loop) { - // The following ES6 code: - // - // for (let v of expr) { } - // - // should be emitted as - // - // for (let _i = 0, _a = expr; _i < _a.length; _i++) { - // let v = _a[_i]; - // } - // - // where _a and _i are temps emitted to capture the RHS and the counter, - // respectively. - // When the left hand side is an expression instead of a let declaration, - // the "let v" is not emitted. - // When the left hand side is a let/const, the v is renamed if there is - // another v in scope. - // Note that all assignments to the LHS are emitted in the body, including - // all destructuring. - // Note also that because an extra statement is needed to assign to the LHS, - // for-of bodies are always emitted as blocks. - var endPos = emitToken(86 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(17 /* OpenParenToken */, endPos); - // Do not emit the LHS let declaration yet, because it might contain destructuring. - // Do not call recordTempDeclaration because we are declaring the temps - // right here. Recording means they will be declared later. - // In the case where the user wrote an identifier as the RHS, like this: - // - // for (let v of arr) { } - // - // we can't reuse 'arr' because it might be modified within the body of the loop. - var counter = createTempVariable(268435456 /* _i */); - var rhsReference = ts.createSynthesizedNode(69 /* Identifier */); - rhsReference.text = node.expression.kind === 69 /* Identifier */ ? - makeUniqueName(node.expression.text) : - makeTempVariableName(0 /* Auto */); - // This is the let keyword for the counter and rhsReference. The let keyword for - // the LHS will be emitted inside the body. - emitStart(node.expression); - write("var "); - // _i = 0 - emitNodeWithoutSourceMap(counter); - write(" = 0"); - emitEnd(node.expression); - // , _a = expr - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - write("; "); - // _i < _a.length; - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write(" < "); - emitNodeWithCommentsAndWithoutSourcemap(rhsReference); - write(".length"); - emitEnd(node.expression); - write("; "); - // _i++) - emitStart(node.expression); - emitNodeWithoutSourceMap(counter); - write("++"); - emitEnd(node.expression); - emitToken(18 /* CloseParenToken */, node.expression.end); - // Body - write(" {"); - writeLine(); - increaseIndent(); - // Initialize LHS - // let v = _a[_i]; - var rhsIterationValue = createElementAccessExpression(rhsReference, counter); - emitStart(node.initializer); - if (node.initializer.kind === 219 /* VariableDeclarationList */) { - write("var "); - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length > 0) { - var declaration = variableDeclarationList.declarations[0]; - if (ts.isBindingPattern(declaration.name)) { - // This works whether the declaration is a var, let, or const. - // It will use rhsIterationValue _a[_i] as the initializer. - emitDestructuring(declaration, /*isAssignmentExpressionStatement*/ false, rhsIterationValue); - } - else { - // The following call does not include the initializer, so we have - // to emit it separately. - emitNodeWithCommentsAndWithoutSourcemap(declaration); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - // It's an empty declaration list. This can only happen in an error case, if the user wrote - // for (let of []) {} - emitNodeWithoutSourceMap(createTempVariable(0 /* Auto */)); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - // Initializer is an expression. Emit the expression in the body, so that it's - // evaluated on every iteration. - var assignmentExpression = createBinaryExpression(node.initializer, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false); - if (node.initializer.kind === 170 /* ArrayLiteralExpression */ || node.initializer.kind === 171 /* ObjectLiteralExpression */) { - // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause - // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. - emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression); - } - } - emitEnd(node.initializer); - write(";"); - if (loop) { - writeLine(); - emitConvertedLoopCall(loop, /*emitAsBlock*/ false); - } - else { - emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false); - } - writeLine(); - decreaseIndent(); - write("}"); - } - function emitBreakOrContinueStatement(node) { - if (convertedLoopState) { - // check if we can emit break\continue as is - // it is possible if either - // - break\continue is statement labeled and label is located inside the converted loop - // - break\continue is non-labeled and located in non-converted loop\switch statement - var jump = node.kind === 210 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - write("return "); - // explicit exit from loop -> copy out parameters - copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ false); - if (!node.label) { - if (node.kind === 210 /* BreakStatement */) { - convertedLoopState.nonLocalJumps |= 2 /* Break */; - write("\"break\";"); - } - else { - convertedLoopState.nonLocalJumps |= 4 /* Continue */; - // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. - write("\"continue\";"); - } - } - else { - var labelMarker = void 0; - if (node.kind === 210 /* BreakStatement */) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); - } - write("\"" + labelMarker + "\";"); - } - return; - } - } - emitToken(node.kind === 210 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - if (convertedLoopState) { - convertedLoopState.nonLocalJumps |= 8 /* Return */; - write("return { value: "); - if (node.expression) { - emit(node.expression); - } - else { - write("void 0"); - } - write(" };"); - return; - } - emitToken(94 /* ReturnKeyword */, node.pos); - emitOptional(" ", node.expression); - write(";"); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(96 /* SwitchKeyword */, node.pos); - write(" "); - emitToken(17 /* OpenParenToken */, endPos); - emit(node.expression); - endPos = emitToken(18 /* CloseParenToken */, node.expression.end); - write(" "); - var saveAllowedNonLabeledJumps; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - // for switch statement allow only non-labeled break - convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; - } - emitCaseBlock(node.caseBlock, endPos); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - } - function emitCaseBlock(node, startPos) { - emitToken(15 /* OpenBraceToken */, startPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.clauses.end); - } - function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); - } - function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === - ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 249 /* CaseClause */) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(72 /* CatchKeyword */, node.pos); - write(" "); - emitToken(17 /* OpenParenToken */, endPos); - emit(node.variableDeclaration); - emitToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : endPos); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(76 /* DebuggerKeyword */, node.pos); - write(";"); - } - function emitLabelAndColon(node) { - emit(node.label); - write(": "); - } - function emitLabeledStatement(node) { - if (!ts.isIterationStatement(node.statement, /* lookInLabeledStatements */ false) || !shouldConvertLoopBody(node.statement)) { - emitLabelAndColon(node); - } - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - emit(node.statement); - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 225 /* ModuleDeclaration */); - return node; - } - function emitContainingModuleName(node) { - var container = getContainingModule(node); - write(container ? getGeneratedNameForNode(container) : "exports"); - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { - var container = getContainingModule(node); - if (container) { - write(getGeneratedNameForNode(container)); - write("."); - } - else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { - write("exports."); - } - } - emitNodeWithCommentsAndWithoutSourcemap(node.name); - emitEnd(node.name); - } - function createVoidZero() { - var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); - zero.text = "0"; - var result = ts.createSynthesizedNode(183 /* VoidExpression */); - result.expression = zero; - return result; - } - function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 256 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 235 /* ExportAssignment */); - // only allow export default at a source file level - if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { - if (!isEs6Module) { - if (languageVersion !== 0 /* ES3 */) { - // default value of configurable, enumerable, writable are `false`. - write('Object.defineProperty(exports, "__esModule", { value: true });'); - writeLine(); - } - else { - write("exports.__esModule = true;"); - writeLine(); - } - } - } - } - } - function emitExportMemberAssignment(node) { - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - // emit call to exporter only for top level nodes - if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { - // emit export default as - // export("default", ) - write(exportFunctionForFile + "(\""); - if (node.flags & 512 /* Default */) { - write("default"); - } - else { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - write("\", "); - emitDeclarationName(node); - write(")"); - } - else { - if (node.flags & 512 /* Default */) { - emitEs6ExportDefaultCompat(node); - if (languageVersion === 0 /* ES3 */) { - write('exports["default"]'); - } - else { - write("exports.default"); - } - } - else { - emitModuleMemberName(node); - } - write(" = "); - emitDeclarationName(node); - } - emitEnd(node); - write(";"); - } - } - function emitExportMemberAssignments(name) { - if (modulekind === ts.ModuleKind.System) { - return; - } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { - var specifier = _b[_a]; - writeLine(); - emitStart(specifier.name); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - emitEnd(specifier.name); - write(" = "); - emitExpressionIdentifier(name); - write(";"); - } - } - } - function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === ts.ModuleKind.System); - if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { - return; - } - writeLine(); - emitStart(specifier.name); - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write("\", "); - emitExpressionIdentifier(specifier.propertyName || specifier.name); - write(")"); - emitEnd(specifier.name); - write(";"); - } - /** - * Emit an assignment to a given identifier, 'name', with a given expression, 'value'. - * @param name an identifier as a left-hand-side operand of the assignment - * @param value an expression as a right-hand-side operand of the assignment - * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma - */ - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { - if (shouldEmitCommaBeforeAssignment) { - write(", "); - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(name); - write("\", "); - } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 218 /* VariableDeclaration */ || name.parent.kind === 169 /* BindingElement */); - // If this is first var declaration, we need to start at var/let/const keyword instead - // otherwise use nodeForSourceMap as the start position - emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); - withTemporaryNoSourceMap(function () { - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - }); - emitEnd(nodeForSourceMap, /*stopOverridingSpan*/ true); - if (exportChanged) { - write(")"); - } - } - /** - * Create temporary variable, emit an assignment of the variable the given expression - * @param expression an expression to assign to the newly created temporary variable - * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location - * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma - */ - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { - var identifier = createTempVariable(0 /* Auto */); - if (!canDefineTempVariablesInPlace) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); - return identifier; - } - function isFirstVariableDeclaration(root) { - return root.kind === 218 /* VariableDeclaration */ && - root.parent.kind === 219 /* VariableDeclarationList */ && - root.parent.declarations[0] === root; - } - function emitDestructuring(root, isAssignmentExpressionStatement, value) { - var emitCount = 0; - // An exported declaration is actually emitted as an assignment (to a property on the module object), so - // temporary variables in an exported declaration need to have real declarations elsewhere - // Also temporary variables should be explicitly allocated for source level declarations when module target is system - // because actual variable declarations are hoisted - var canDefineTempVariablesInPlace = false; - if (root.kind === 218 /* VariableDeclaration */) { - var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; - var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); - canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; - } - else if (root.kind === 142 /* Parameter */) { - canDefineTempVariablesInPlace = true; - } - if (root.kind === 187 /* BinaryExpression */) { - emitAssignmentExpression(root); - } - else { - ts.Debug.assert(!isAssignmentExpressionStatement); - // If first variable declaration of variable statement correct the start location - if (isFirstVariableDeclaration(root)) { - // Use emit location of "var " as next emit start entry - sourceMap.changeEmitSourcePos(); - } - emitBindingElement(root, value); - } - /** - * Ensures that there exists a declared identifier whose value holds the given expression. - * This function is useful to ensure that the expression's value can be read from in subsequent expressions. - * Unless 'reuseIdentifierExpressions' is false, 'expr' will be returned if it is just an identifier. - * - * @param expr the expression whose value needs to be bound. - * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; - * false if it is necessary to always emit an identifier. - */ - function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { - if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) { - return expr; - } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); - emitCount++; - return identifier; - } - function createDefaultValueCheck(value, defaultValue, sourceMapNode) { - // The value expression will be evaluated twice, so for anything but a simple identifier - // we need to generate a temporary variable - // If the temporary variable needs to be emitted use the source Map node for assignment of that statement - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); - // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(187 /* BinaryExpression */); - equals.left = value; - equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */); - equals.right = createVoidZero(); - return createConditionalExpression(equals, defaultValue, value); - } - function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(188 /* ConditionalExpression */); - cond.condition = condition; - cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); - cond.whenTrue = whenTrue; - cond.colonToken = ts.createSynthesizedNode(54 /* ColonToken */); - cond.whenFalse = whenFalse; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createSynthesizedNode(8 /* NumericLiteral */); - node.text = "" + value; - return node; - } - function createPropertyAccessForDestructuringProperty(object, propName) { - var index; - var nameIsComputed = propName.kind === 140 /* ComputedPropertyName */; - if (nameIsComputed) { - // TODO to handle when we look into sourcemaps for computed properties, for now use propName - index = ensureIdentifier(propName.expression, /*reuseIdentifierExpressions*/ false, propName); - } - else { - // We create a synthetic copy of the identifier in order to avoid the rewriting that might - // otherwise occur when the identifier is emitted. - index = ts.createSynthesizedNode(propName.kind); - // We need to unescape identifier here because when parsing an identifier prefixing with "__" - // the parser need to append "_" in order to escape colliding with magic identifiers such as "__proto__" - // Therefore, in order to correctly emit identifiers that are written in original TypeScript file, - // we will unescapeIdentifier to remove additional underscore (if no underscore is added, the function will return original input string) - index.text = ts.unescapeIdentifier(propName.text); - } - return !nameIsComputed && index.kind === 69 /* Identifier */ - ? createPropertyAccessExpression(object, index) - : createElementAccessExpression(object, index); - } - function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(174 /* CallExpression */); - var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); - sliceIdentifier.text = "slice"; - call.expression = createPropertyAccessExpression(value, sliceIdentifier); - call.arguments = ts.createSynthesizedNodeArray(); - call.arguments[0] = createNumericLiteral(sliceIndex); - return call; - } - function emitObjectLiteralAssignment(target, value, sourceMapNode) { - var properties = target.properties; - if (properties.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); - } - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var p = properties_5[_a]; - if (p.kind === 253 /* PropertyAssignment */ || p.kind === 254 /* ShorthandPropertyAssignment */) { - var propName = p.name; - var target_1 = p.kind === 254 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; - // Assignment for target = value.propName should highlight whole property, hence use p as source map node - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, sourceMapNode) { - var elements = target.elements; - if (elements.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 193 /* OmittedExpression */) { - // Assignment for target = value.propName should highlight whole property, hence use e as source map node - if (e.kind !== 191 /* SpreadElementExpression */) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); - } - else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); - } - } - } - } - function emitDestructuringAssignment(target, value, sourceMapNode) { - // When emitting target = value use source map node to highlight, including any temporary assignments needed for this - if (target.kind === 254 /* ShorthandPropertyAssignment */) { - if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); - } - target = target.name; - } - else if (target.kind === 187 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right, sourceMapNode); - target = target.left; - } - if (target.kind === 171 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value, sourceMapNode); - } - else if (target.kind === 170 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value, sourceMapNode); - } - else { - emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, sourceMapNode); - emitCount++; - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) { - emit(value); - } - else if (isAssignmentExpressionStatement) { - // Source map node for root.left = root.right is root - // but if root is synthetic, which could be in below case, use the target which is { a } - // for ({a} of {a: string}) { - // } - emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); - } - else { - if (root.parent.kind !== 178 /* ParenthesizedExpression */) { - write("("); - } - // Temporary assignment needed to emit root should highlight whole binary expression - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, root); - // Source map node for root.left = root.right is root - emitDestructuringAssignment(target, value, root); - write(", "); - emit(value); - if (root.parent.kind !== 178 /* ParenthesizedExpression */) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - // Any temporary assignments needed to emit target = value should point to target - if (target.initializer) { - // Combine value and initializer - value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; - } - else if (!value) { - // Use 'void 0' in absence of value and initializer - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - var numElements = elements.length; - if (numElements !== 1) { - // For anything other than a single-element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. Additionally, if we have zero elements - // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, - // so in that case, we'll intentionally create that temporary. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (pattern.kind === 167 /* ObjectBindingPattern */) { - // Rewrite element to a declaration with an initializer that fetches property - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); - } - else if (element.kind !== 193 /* OmittedExpression */) { - if (!element.dotDotDotToken) { - // Rewrite element to a declaration that accesses array element at index i - emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); - } - else if (i === numElements - 1) { - emitBindingElement(element, createSliceCall(value, i)); - } - } - } - } - else { - emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, target); - emitCount++; - } - } - } - function emitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name)) { - var isExported = ts.getCombinedNodeFlags(node) & 1 /* Export */; - if (languageVersion >= 2 /* ES6 */ && (!isExported || modulekind === ts.ModuleKind.ES6)) { - // emit ES6 destructuring only if target module is ES6 or variable is not exported - // exported variables in CJS/AMD are prefixed with 'exports.' so result javascript { exports.toString } = 1; is illegal - var isTopLevelDeclarationInSystemModule = modulekind === ts.ModuleKind.System && - shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); - if (isTopLevelDeclarationInSystemModule) { - // In System modules top level variables are hoisted - // so variable declarations with destructuring are turned into destructuring assignments. - // As a result, they will need parentheses to disambiguate object binding assignments from blocks. - write("("); - } - emit(node.name); - emitOptional(" = ", node.initializer); - if (isTopLevelDeclarationInSystemModule) { - write(")"); - } - } - else { - emitDestructuring(node, /*isAssignmentExpressionStatement*/ false); - } - } - else { - var initializer = node.initializer; - if (!initializer && - languageVersion < 2 /* ES6 */ && - // for names - binding patterns that lack initializer there is no point to emit explicit initializer - // since downlevel codegen for destructuring will fail in the absence of initializer so all binding elements will say uninitialized - node.name.kind === 69 /* Identifier */) { - var container = ts.getEnclosingBlockScopeContainer(node); - var flags = resolver.getNodeCheckFlags(node); - // nested let bindings might need to be initialized explicitly to preserve ES6 semantic - // { let x = 1; } - // { let x; } // x here should be undefined. not 1 - // NOTES: - // Top level bindings never collide with anything and thus don't require explicit initialization. - // As for nested let bindings there are two cases: - // - nested let bindings that were not renamed definitely should be initialized explicitly - // { let x = 1; } - // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } - // Without explicit initialization code in /*1*/ can be executed even if some-condition is evaluated to false - // - renaming introduces fresh name that should not collide with any existing names, however renamed bindings sometimes also should be - // explicitly initialized. One particular case: non-captured binding declared inside loop body (but not in loop initializer) - // let x; - // for (;;) { - // let x; - // } - // in downlevel codegen inner 'x' will be renamed so it won't collide with outer 'x' however it will should be reset on every iteration - // as if it was declared anew. - // * Why non-captured binding - because if loop contains block scoped binding captured in some function then loop body will be rewritten - // to have a fresh scope on every iteration so everything will just work. - // * Why loop initializer is excluded - since we've introduced a fresh name it already will be undefined. - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || - (isCapturedInFunction && isDeclaredInLoop && container.kind === 199 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false)); - var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 /* Let */ && - !emittedAsTopLevel; - var emitExplicitInitializer = emittedAsNestedLetDeclaration && - container.kind !== 207 /* ForInStatement */ && - container.kind !== 208 /* ForOfStatement */ && - (!resolver.isDeclarationWithCollidingName(node) || - (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, /*lookInLabeledStatements*/ false))); - if (emitExplicitInitializer) { - initializer = createVoidZero(); - } - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithCommentsAndWithoutSourcemap(node.name); - write("\", "); - } - emitModuleMemberName(node); - emitOptional(" = ", initializer); - if (exportChanged) { - write(")"); - } - } - } - function emitExportVariableAssignments(node) { - if (node.kind === 193 /* OmittedExpression */) { - return; - } - var name = node.name; - if (name.kind === 69 /* Identifier */) { - emitExportMemberAssignments(name); - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, emitExportVariableAssignments); - } - } - function isES6ExportedDeclaration(node) { - return !!(node.flags & 1 /* Export */) && - modulekind === ts.ModuleKind.ES6 && - node.parent.kind === 256 /* SourceFile */; - } - function emitVariableStatement(node) { - var startIsEmitted = false; - if (node.flags & 1 /* Export */) { - if (isES6ExportedDeclaration(node)) { - // Exported ES6 module member - write("export "); - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - } - else { - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - if (startIsEmitted) { - emitCommaList(node.declarationList.declarations); - write(";"); - } - else { - var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); - if (atLeastOneItem) { - write(";"); - } - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); - } - } - function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - // If we're not exporting the variables, there's nothing special here. - // Always emit comments for these nodes. - if (!(node.flags & 1 /* Export */)) { - return true; - } - // If we are exporting, but it's a top-level ES6 module exports, - // we'll emit the declaration list verbatim, so emit comments too. - if (isES6ExportedDeclaration(node)) { - return true; - } - // Otherwise, only emit if we have at least one initializer present. - for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { - var declaration = _b[_a]; - if (declaration.initializer) { - return true; - } - } - return false; - } - function emitParameter(node) { - if (languageVersion < 2 /* ES6 */) { - if (ts.isBindingPattern(node.name)) { - var name_29 = createTempVariable(0 /* Auto */); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name_29); - emit(name_29); - } - else { - emit(node.name); - } - } - else { - if (node.dotDotDotToken) { - write("..."); - } - emit(node.name); - emitOptional(" = ", node.initializer); - } - } - function emitDefaultValueAssignments(node) { - if (languageVersion < 2 /* ES6 */) { - var tempIndex_1 = 0; - ts.forEach(node.parameters, function (parameter) { - // A rest parameter cannot have a binding pattern or an initializer, - // so let's just ignore it. - if (parameter.dotDotDotToken) { - return; - } - var paramName = parameter.name, initializer = parameter.initializer; - if (ts.isBindingPattern(paramName)) { - // In cases where a binding pattern is simply '[]' or '{}', - // we usually don't want to emit a var declaration; however, in the presence - // of an initializer, we must emit that expression to preserve side effects. - var hasBindingElements = paramName.elements.length > 0; - if (hasBindingElements || initializer) { - writeLine(); - write("var "); - if (hasBindingElements) { - emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex_1]); - } - else { - emit(tempParameters[tempIndex_1]); - write(" = "); - emit(initializer); - } - write(";"); - } - // Regardless of whether we will emit a var declaration for the binding pattern, we generate the temporary - // variable for the parameter (see: emitParameter) - tempIndex_1++; - } - else if (initializer) { - writeLine(); - emitStart(parameter); - write("if ("); - emitNodeWithoutSourceMap(paramName); - write(" === void 0)"); - emitEnd(parameter); - write(" { "); - emitStart(parameter); - emitNodeWithCommentsAndWithoutSourcemap(paramName); - write(" = "); - emitNodeWithCommentsAndWithoutSourcemap(initializer); - emitEnd(parameter); - write("; }"); - } - }); - } - } - function emitRestParameter(node) { - if (languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. - if (ts.isBindingPattern(restParam.name)) { - return; - } - var tempName = createTempVariable(268435456 /* _i */).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNodeWithCommentsAndWithoutSourcemap(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - write(node.kind === 149 /* GetAccessor */ ? "get " : "set "); - emit(node.name); - emitSignatureAndBody(node); - } - function shouldEmitAsArrowFunction(node) { - return node.kind === 180 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; - } - function emitDeclarationName(node) { - if (node.name) { - emitNodeWithCommentsAndWithoutSourcemap(node.name); - } - else { - write(getGeneratedNameForNode(node)); - } - } - function shouldEmitFunctionName(node) { - if (node.kind === 179 /* FunctionExpression */) { - // Emit name if one is present - return !!node.name; - } - if (node.kind === 220 /* FunctionDeclaration */) { - // Emit name if one is present, or emit generated name in down-level case (for export default case) - return !!node.name || modulekind !== ts.ModuleKind.ES6; - } - } - function emitFunctionDeclaration(node) { - if (ts.nodeIsMissing(node.body)) { - return emitCommentsOnNotEmittedNode(node); - } - // TODO (yuisu) : we should not have special cases to condition emitting comments - // but have one place to fix check for these conditions. - var kind = node.kind, parent = node.parent; - if (kind !== 147 /* MethodDeclaration */ && - kind !== 146 /* MethodSignature */ && - parent && - parent.kind !== 253 /* PropertyAssignment */ && - parent.kind !== 174 /* CallExpression */ && - parent.kind !== 170 /* ArrayLiteralExpression */) { - // 1. Methods will emit comments at their assignment declaration sites. - // - // 2. If the function is a property of object literal, emitting leading-comments - // is done by emitNodeWithoutSourceMap which then call this function. - // In particular, we would like to avoid emit comments twice in following case: - // - // var obj = { - // id: - // /*comment*/ () => void - // } - // - // 3. If the function is an argument in call expression, emitting of comments will be - // taken care of in emit list of arguments inside of 'emitCallExpression'. - // - // 4. If the function is in an array literal, 'emitLinePreservingList' will take care - // of leading comments. - emitLeadingComments(node); - } - emitStart(node); - // For targeting below es6, emit functions-like declaration including arrow function using function keyword. - // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead - if (!shouldEmitAsArrowFunction(node)) { - if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512 /* Default */) { - write("default "); - } - } - write("function"); - if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { - write("*"); - } - write(" "); - } - if (shouldEmitFunctionName(node)) { - emitDeclarationName(node); - } - emitSignatureAndBody(node); - if (modulekind !== ts.ModuleKind.ES6 && kind === 220 /* FunctionDeclaration */ && parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - emitEnd(node); - if (kind !== 147 /* MethodDeclaration */ && - kind !== 146 /* MethodSignature */ && - kind !== 180 /* ArrowFunction */) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; - var omitCount = languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node) ? 1 : 0; - emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false); - } - write(")"); - decreaseIndent(); - } - function emitSignatureParametersForArrow(node) { - // Check whether the parameter list needs parentheses and preserve no-parenthesis - if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { - emit(node.parameters[0]); - return; - } - emitSignatureParameters(node); - } - function emitAsyncFunctionBodyForES6(node) { - var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 180 /* ArrowFunction */; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; - // An async function is emit as an outer function that calls an inner - // generator function. To preserve lexical bindings, we pass the current - // `this` and `arguments` objects to `__awaiter`. The generator function - // passed to `__awaiter` is executed inside of the callback to the - // promise constructor. - // - // The emit for an async arrow without a lexical `arguments` binding might be: - // - // // input - // let a = async (b) => { await b; } - // - // // output - // let a = (b) => __awaiter(this, void 0, void 0, function* () { - // yield b; - // }); - // - // The emit for an async arrow with a lexical `arguments` binding might be: - // - // // input - // let a = async (b) => { await arguments[0]; } - // - // // output - // let a = (b) => __awaiter(this, arguments, void 0, function* (arguments) { - // yield arguments[0]; - // }); - // - // The emit for an async function expression without a lexical `arguments` binding - // might be: - // - // // input - // let a = async function (b) { - // await b; - // } - // - // // output - // let a = function (b) { - // return __awaiter(this, void 0, void 0, function* () { - // yield b; - // }); - // } - // - // The emit for an async function expression with a lexical `arguments` binding - // might be: - // - // // input - // let a = async function (b) { - // await arguments[0]; - // } - // - // // output - // let a = function (b) { - // return __awaiter(this, arguments, void 0, function* (_arguments) { - // yield _arguments[0]; - // }); - // } - // - // The emit for an async function expression with a lexical `arguments` binding - // and a return type annotation might be: - // - // // input - // let a = async function (b): MyPromise { - // await arguments[0]; - // } - // - // // output - // let a = function (b) { - // return __awaiter(this, arguments, MyPromise, function* (_arguments) { - // yield _arguments[0]; - // }); - // } - // - // If this is not an async arrow, emit the opening brace of the function body - // and the start of the return statement. - if (!isArrowFunction) { - write(" {"); - increaseIndent(); - writeLine(); - if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); - writeLine(); - } - else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - write("const _super = name => super[name];"); - writeLine(); - } - write("return"); - } - write(" __awaiter(this"); - if (hasLexicalArguments) { - write(", arguments, "); - } - else { - write(", void 0, "); - } - if (languageVersion >= 2 /* ES6 */ || !promiseConstructor) { - write("void 0"); - } - else { - emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false); - } - // Emit the call to __awaiter. - write(", function* ()"); - // Emit the signature and body for the inner generator function. - emitFunctionBody(node); - write(")"); - // If this is not an async arrow, emit the closing brace of the outer function body. - if (!isArrowFunction) { - write(";"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitFunctionBody(node) { - if (!node.body) { - // There can be no body when there are parse errors. Just emit an empty block - // in that case. - write(" { }"); - } - else { - if (node.body.kind === 199 /* Block */) { - emitBlockFunctionBody(node, node.body); - } - else { - emitExpressionFunctionBody(node, node.body); - } - } - } - function emitSignatureAndBody(node) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - // When targeting ES6, emit arrow function natively in ES6 - if (shouldEmitAsArrowFunction(node)) { - emitSignatureParametersForArrow(node); - write(" =>"); - } - else { - emitSignatureParameters(node); - } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAsyncFunctionBodyForES6(node); - } - else { - emitFunctionBody(node); - } - if (!isES6ExportedDeclaration(node)) { - emitExportMemberAssignment(node); - } - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - // Returns true if any preamble code was emitted. - function emitFunctionBodyPreamble(node) { - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - } - function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 /* ES6 */ || node.flags & 256 /* Async */) { - emitDownLevelExpressionFunctionBody(node, body); - return; - } - // For es6 and higher we can emit the expression as is. However, in the case - // where the expression might end up looking like a block when emitted, we'll - // also wrap it in parentheses first. For example if you have: a => {} - // then we need to generate: a => ({}) - write(" "); - // Unwrap all type assertions. - var current = body; - while (current.kind === 177 /* TypeAssertionExpression */) { - current = current.expression; - } - emitParenthesizedIf(body, current.kind === 171 /* ObjectLiteralExpression */); - } - function emitDownLevelExpressionFunctionBody(node, body) { - write(" {"); - increaseIndent(); - var outPos = writer.getTextPos(); - emitDetachedCommentsAndUpdateCommentsInfo(node.body); - emitFunctionBodyPreamble(node); - var preambleEmitted = writer.getTextPos() !== outPos; - decreaseIndent(); - // If we didn't have to emit any preamble code, then attempt to keep the arrow - // function on one line. - if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) { - write(" "); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTempDeclarations(/*newLine*/ false); - write(" "); - } - else { - increaseIndent(); - writeLine(); - emitLeadingComments(node.body); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTrailingComments(node.body); - emitTempDeclarations(/*newLine*/ true); - decreaseIndent(); - writeLine(); - } - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - function emitBlockFunctionBody(node, body) { - write(" {"); - var initialTextPos = writer.getTextPos(); - increaseIndent(); - emitDetachedCommentsAndUpdateCommentsInfo(body.statements); - // Emit all the directive prologues (like "use strict"). These have to come before - // any other preamble code we write (like parameter initializers). - var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); - emitFunctionBodyPreamble(node); - decreaseIndent(); - var preambleEmitted = writer.getTextPos() !== initialTextPos; - if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { - var statement = _b[_a]; - write(" "); - emit(statement); - } - emitTempDeclarations(/*newLine*/ false); - write(" "); - emitLeadingCommentsOfPosition(body.statements.end); - } - else { - increaseIndent(); - emitLinesStartingAt(body.statements, startIndex); - emitTempDeclarations(/*newLine*/ true); - writeLine(); - emitLeadingCommentsOfPosition(body.statements.end); - decreaseIndent(); - } - emitToken(16 /* CloseBraceToken */, body.statements.end); - } - /** - * Return the statement at a given index if it is a super-call statement - * @param ctor a constructor declaration - * @param index an index to constructor's body to check - */ - function getSuperCallAtGivenIndex(ctor, index) { - if (!ctor.body) { - return undefined; - } - var statements = ctor.body.statements; - if (!statements || index >= statements.length) { - return undefined; - } - var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */) { - return ts.isSuperCallExpression(statement.expression) ? statement : undefined; - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 92 /* ParameterPropertyModifier */) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNodeWithoutSourceMap(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - // This does not emit source map because it is emitted by caller as caller - // is aware how the property name changes to the property access - // eg. public x = 10; becomes this.x and static x = 10 becomes className.x - if (memberName.kind === 9 /* StringLiteral */ || memberName.kind === 8 /* NumericLiteral */) { - write("["); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - write("]"); - } - else if (memberName.kind === 140 /* ComputedPropertyName */) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNodeWithCommentsAndWithoutSourcemap(memberName); - } - } - function getInitializedProperties(node, isStatic) { - var properties = []; - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 145 /* PropertyDeclaration */ && isStatic === ((member.flags & 32 /* Static */) !== 0) && member.initializer) { - properties.push(member); - } - } - return properties; - } - function emitPropertyDeclarations(node, properties) { - for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { - var property = properties_6[_a]; - emitPropertyDeclaration(node, property); - } - } - function emitPropertyDeclaration(node, property, receiver, isExpression) { - writeLine(); - emitLeadingComments(property); - emitStart(property); - emitStart(property.name); - if (receiver) { - write(receiver); - } - else { - if (property.flags & 32 /* Static */) { - emitDeclarationName(node); - } - else { - write("this"); - } - } - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - emit(property.initializer); - if (!isExpression) { - write(";"); - } - emitEnd(property); - emitTrailingComments(property); - } - function emitMemberFunctionsForES5AndLower(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 198 /* SemicolonClassElement */) { - writeLine(); - write(";"); - } - else if (member.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) { - if (!member.body) { - return emitCommentsOnNotEmittedNode(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitClassMemberPrefix(node, member); - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitFunctionDeclaration(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 149 /* GetAccessor */ || member.kind === 150 /* SetAccessor */) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitMemberFunctionsForES6AndHigher(node) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if ((member.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - else if (member.kind === 147 /* MethodDeclaration */ || - member.kind === 149 /* GetAccessor */ || - member.kind === 150 /* SetAccessor */) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - if (member.flags & 32 /* Static */) { - write("static "); - } - if (member.kind === 149 /* GetAccessor */) { - write("get "); - } - else if (member.kind === 150 /* SetAccessor */) { - write("set "); - } - if (member.asteriskToken) { - write("*"); - } - emit(member.name); - emitSignatureAndBody(member); - emitEnd(member); - emitTrailingComments(member); - } - else if (member.kind === 198 /* SemicolonClassElement */) { - writeLine(); - write(";"); - } - } - } - function emitConstructor(node, baseTypeElement) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - emitConstructorWorker(node, baseTypeElement); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitConstructorWorker(node, baseTypeElement) { - // 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 - var hasInstancePropertyWithInitializer = false; - // Emit the constructor overload pinned comments - ts.forEach(node.members, function (member) { - if (member.kind === 148 /* Constructor */ && !member.body) { - emitCommentsOnNotEmittedNode(member); - } - // Check if there is any non-static property assignment - if (member.kind === 145 /* PropertyDeclaration */ && member.initializer && (member.flags & 32 /* Static */) === 0) { - hasInstancePropertyWithInitializer = true; - } - }); - var ctor = ts.getFirstConstructorWithBody(node); - // For target ES6 and above, if there is no user-defined constructor and there is no property assignment - // do not emit constructor in class declaration. - if (languageVersion >= 2 /* ES6 */ && !ctor && !hasInstancePropertyWithInitializer) { - return; - } - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - if (languageVersion < 2 /* ES6 */) { - write("function "); - emitDeclarationName(node); - emitSignatureParameters(ctor); - } - else { - write("constructor"); - if (ctor) { - emitSignatureParameters(ctor); - } - else { - // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation. - // If constructor is empty, then, - // If ClassHeritageopt is present, then - // Let constructor be the result of parsing the String "constructor(... args){ super (...args);}" using the syntactic grammar with the goal symbol MethodDefinition. - // Else, - // Let constructor be the result of parsing the String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } - } - } - var startIndex = 0; - write(" {"); - increaseIndent(); - if (ctor) { - // Emit all the directive prologues (like "use strict"). These have to come before - // any other preamble code we write (like parameter initializers). - startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true); - emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - var superCall; - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeElement) { - superCall = getSuperCallAtGivenIndex(ctor, startIndex); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeElement) { - writeLine(); - emitStart(baseTypeElement); - if (languageVersion < 2 /* ES6 */) { - write("_super.apply(this, arguments);"); - } - else { - write("super(...args);"); - } - emitEnd(baseTypeElement); - } - } - emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false)); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) { - statements = statements.slice(1); - } - emitLinesStartingAt(statements, startIndex); - } - emitTempDeclarations(/*newLine*/ true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - } - function emitClassExpression(node) { - return emitClassLikeDeclaration(node); - } - function emitClassDeclaration(node) { - return emitClassLikeDeclaration(node); - } - function emitClassLikeDeclaration(node) { - if (languageVersion < 2 /* ES6 */) { - emitClassLikeDeclarationBelowES6(node); - } - else { - emitClassLikeDeclarationForES6AndHigher(node); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - } - function emitClassLikeDeclarationForES6AndHigher(node) { - var decoratedClassAlias; - var isHoistedDeclarationInSystemModule = shouldHoistDeclarationInSystemJsModule(node); - var isDecorated = ts.nodeIsDecorated(node); - var rewriteAsClassExpression = isDecorated || isHoistedDeclarationInSystemModule; - if (node.kind === 221 /* ClassDeclaration */) { - if (rewriteAsClassExpression) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------|------------------------------------ - // @dec | export let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // [Example 1] - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); - // --------------------------------|------------------------------------ - // @dec | let C_1 = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | export let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); - // --------------------------------------------------------------------- - // [Example 2] - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------|------------------------------------ - // @dec | let C = class C { - // export default class { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // [Example 3] - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // TypeScript | Javascript - // --------------------------------|------------------------------------ - // @dec | let C_1 = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | }; - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // [Example 4] - // - // NOTE: we reuse the same rewriting logic for cases when targeting ES6 and module kind is System. - // Because of hoisting top level class declaration need to be emitted as class expressions. - // Double bind case is only required if node is decorated. - if (isDecorated && resolver.getNodeCheckFlags(node) & 524288 /* ClassWithBodyScopedClassBinding */) { - decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); - decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; - } - if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) { - write("export "); - } - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } - if (decoratedClassAlias !== undefined) { - write("" + decoratedClassAlias); - } - else { - emitDeclarationName(node); - } - write(" = "); - } - else if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 512 /* Default */) { - write("default "); - } - } - } - // If the class has static properties, and it's a class expression, then we'll need - // to specialize the emit a bit. for a class expression of the form: - // - // class C { static a = 1; static b = 2; ... } - // - // We'll emit: - // - // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp) - // - // This keeps the expression as an expression, while ensuring that the static parts - // of it have been initialized by the time it is used. - var staticProperties = getInitializedProperties(node, /*isStatic*/ true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192 /* ClassExpression */; - var generatedName; - if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); - var synthesizedNode = ts.createSynthesizedNode(69 /* Identifier */); - synthesizedNode.text = generatedName; - recordTempDeclaration(synthesizedNode); - write("("); - increaseIndent(); - emit(synthesizedNode); - write(" = "); - } - write("class"); - // emit name if - // - node has a name - // - this is default export with static initializers - if (node.name || (node.flags & 512 /* Default */ && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !rewriteAsClassExpression)) { - write(" "); - emitDeclarationName(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write(" extends "); - emit(baseTypeNode.expression); - } - write(" {"); - increaseIndent(); - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES6AndHigher(node); - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end); - if (rewriteAsClassExpression) { - if (decoratedClassAlias !== undefined) { - write(";"); - writeLine(); - if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */)) { - write("export "); - } - write("let "); - emitDeclarationName(node); - write(" = " + decoratedClassAlias); - } - decoratedClassAliases[ts.getNodeId(node)] = undefined; - write(";"); - } - // Emit static property assignment. Because classDeclaration is lexically evaluated, - // it is safe to emit static property assignment after classDeclaration - // From ES6 specification: - // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using - // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - if (isClassExpressionWithStaticProperties) { - for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { - var property = staticProperties_1[_a]; - write(","); - writeLine(); - emitPropertyDeclaration(node, property, /*receiver*/ generatedName, /*isExpression*/ true); - } - write(","); - writeLine(); - write(generatedName); - decreaseIndent(); - write(")"); - } - else { - writeLine(); - emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node, decoratedClassAlias); - } - if (!(node.flags & 1 /* Export */)) { - return; - } - if (modulekind !== ts.ModuleKind.ES6) { - emitExportMemberAssignment(node); - } - else { - // If this is an exported class, but not on the top level (i.e. on an internal - // module), export it - if (node.flags & 512 /* Default */) { - // if this is a top level default export of decorated class, write the export after the declaration. - if (isDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - else if (node.parent.kind !== 256 /* SourceFile */) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); - } - } - } - function emitClassLikeDeclarationBelowES6(node) { - var isES6ExportedClass = isES6ExportedDeclaration(node); - if (node.kind === 221 /* ClassDeclaration */) { - if (isES6ExportedClass && !(node.flags & 512 /* Default */)) { - write("export "); - } - // source file level classes in system modules are hoisted so 'var's for them are already defined - if (!shouldHoistDeclarationInSystemJsModule(node)) { - write("var "); - } - emitDeclarationName(node); - write(" = "); - } - write("(function ("); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - var saveConvertedLoopState = convertedLoopState; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - computedPropertyNamesToGeneratedNames = undefined; - increaseIndent(); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emitDeclarationName(node); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true)); - writeLine(); - emitDecoratorsOfClass(node, /*decoratedClassAlias*/ undefined); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end, function () { - write("return "); - emitDeclarationName(node); - }); - write(";"); - emitTempDeclarations(/*newLine*/ true); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames; - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end); - emitStart(node); - write("("); - if (baseTypeNode) { - emit(baseTypeNode.expression); - } - write("))"); - if (node.kind === 221 /* ClassDeclaration */) { - write(";"); - } - emitEnd(node); - if (node.kind === 221 /* ClassDeclaration */ && !isES6ExportedClass) { - emitExportMemberAssignment(node); - } - else if (isES6ExportedClass && (node.flags & 512 /* Default */)) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - function emitClassMemberPrefix(node, member) { - emitDeclarationName(node); - if (!(member.flags & 32 /* Static */)) { - write(".prototype"); - } - } - function emitDecoratorsOfClass(node, decoratedClassAlias) { - emitDecoratorsOfMembers(node, /*staticFlag*/ 0); - emitDecoratorsOfMembers(node, 32 /* Static */); - emitDecoratorsOfConstructor(node, decoratedClassAlias); - } - function emitDecoratorsOfConstructor(node, decoratedClassAlias) { - var decorators = node.decorators; - var constructor = ts.getFirstConstructorWithBody(node); - var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); - // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !firstParameterDecorator) { - return; - } - // Emit the call to __decorate. Given the class: - // - // @dec - // class C { - // } - // - // The emit for the class is: - // - // C = __decorate([dec], C); - // - writeLine(); - emitStart(node.decorators || firstParameterDecorator); - emitDeclarationName(node); - if (decoratedClassAlias !== undefined) { - write(" = " + decoratedClassAlias); - } - write(" = __decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); - } - emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); - decreaseIndent(); - writeLine(); - write("], "); - emitDeclarationName(node); - write(")"); - emitEnd(node.decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - function emitDecoratorsOfMembers(node, staticFlag) { - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - // only emit members in the correct group - if ((member.flags & 32 /* Static */) !== staticFlag) { - continue; - } - // skip members that cannot be decorated (such as the constructor) - if (!ts.nodeCanBeDecorated(member)) { - continue; - } - // skip an accessor declaration if it is not the first accessor - var decorators = void 0; - var functionLikeMember = void 0; - if (ts.isAccessor(member)) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member !== accessors.firstAccessor) { - continue; - } - // get the decorators from the first accessor with decorators - decorators = accessors.firstAccessor.decorators; - if (!decorators && accessors.secondAccessor) { - decorators = accessors.secondAccessor.decorators; - } - // we only decorate parameters of the set accessor - functionLikeMember = accessors.setAccessor; - } - else { - decorators = member.decorators; - // we only decorate the parameters here if this is a method - if (member.kind === 147 /* MethodDeclaration */) { - functionLikeMember = member; - } - } - var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); - // skip a member if it or any of its parameters are not decorated - if (!decorators && !firstParameterDecorator) { - continue; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", undefined); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", undefined); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - writeLine(); - emitStart(decorators || firstParameterDecorator); - write("__decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); - if (firstParameterDecorator) { - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); - } - emitSerializedTypeMetadata(member, argumentsWritten > 0); - decreaseIndent(); - writeLine(); - write("], "); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - if (languageVersion > 0 /* ES3 */) { - if (member.kind !== 145 /* PropertyDeclaration */) { - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - write(", null"); - } - else { - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - write(", void 0"); - } - } - write(")"); - emitEnd(decorators || firstParameterDecorator); - write(";"); - writeLine(); - } - } - function emitDecoratorsOfParameters(node, leadingComma) { - var argumentsWritten = 0; - if (node) { - var parameterIndex_1 = 0; - for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { - var parameter = _b[_a]; - if (ts.nodeIsDecorated(parameter)) { - var decorators = parameter.decorators; - argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) { - write("__param(" + parameterIndex_1 + ", "); - emit(decorator.expression); - write(")"); - }); - leadingComma = true; - } - parameterIndex_1++; - } - } - return argumentsWritten; - } - function shouldEmitTypeMetadata(node) { - // This method determines whether to emit the "design:type" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 145 /* PropertyDeclaration */: - return true; - } - return false; - } - function shouldEmitReturnTypeMetadata(node) { - // This method determines whether to emit the "design:returntype" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 147 /* MethodDeclaration */: - return true; - } - return false; - } - function shouldEmitParamTypesMetadata(node) { - // This method determines whether to emit the "design:paramtypes" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 221 /* ClassDeclaration */: - case 147 /* MethodDeclaration */: - case 150 /* SetAccessor */: - return true; - } - return false; - } - /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */ - function emitSerializedTypeOfNode(node) { - // serialization of the type of a declaration uses the following rules: - // - // * The serialized type of a ClassDeclaration is "Function" - // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation. - // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation. - // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter. - // * The serialized type of any other FunctionLikeDeclaration is "Function". - // * The serialized type of any other node is "void 0". - // - // For rules on serializing type annotations, see `serializeTypeNode`. - switch (node.kind) { - case 221 /* ClassDeclaration */: - write("Function"); - return; - case 145 /* PropertyDeclaration */: - emitSerializedTypeNode(node.type); - return; - case 142 /* Parameter */: - emitSerializedTypeNode(node.type); - return; - case 149 /* GetAccessor */: - emitSerializedTypeNode(node.type); - return; - case 150 /* SetAccessor */: - emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - return; - } - if (ts.isFunctionLike(node)) { - write("Function"); - return; - } - write("void 0"); - } - function emitSerializedTypeNode(node) { - if (node) { - switch (node.kind) { - case 103 /* VoidKeyword */: - write("void 0"); - return; - case 164 /* ParenthesizedType */: - emitSerializedTypeNode(node.type); - return; - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - write("Function"); - return; - case 160 /* ArrayType */: - case 161 /* TupleType */: - write("Array"); - return; - case 154 /* TypePredicate */: - case 120 /* BooleanKeyword */: - write("Boolean"); - return; - case 132 /* StringKeyword */: - case 166 /* StringLiteralType */: - write("String"); - return; - case 130 /* NumberKeyword */: - write("Number"); - return; - case 133 /* SymbolKeyword */: - write("Symbol"); - return; - case 155 /* TypeReference */: - emitSerializedTypeReferenceNode(node); - return; - case 158 /* TypeQuery */: - case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 117 /* AnyKeyword */: - case 165 /* ThisType */: - break; - default: - ts.Debug.fail("Cannot serialize unexpected type node."); - break; - } - } - write("Object"); - } - /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function emitSerializedTypeReferenceNode(node) { - var location = node.parent; - while (ts.isDeclaration(location) || ts.isTypeNode(location)) { - location = location.parent; - } - // Clone the type name and parent it to a location outside of the current declaration. - var typeName = ts.cloneEntityName(node.typeName, location); - var result = resolver.getTypeReferenceSerializationKind(typeName); - switch (result) { - case ts.TypeReferenceSerializationKind.Unknown: - var temp = createAndRecordTempVariable(0 /* Auto */); - write("(typeof ("); - emitNodeWithoutSourceMap(temp); - write(" = "); - emitEntityNameAsExpression(typeName, /*useFallback*/ true); - write(") === 'function' && "); - emitNodeWithoutSourceMap(temp); - write(") || Object"); - break; - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - emitEntityNameAsExpression(typeName, /*useFallback*/ false); - break; - case ts.TypeReferenceSerializationKind.VoidType: - write("void 0"); - break; - case ts.TypeReferenceSerializationKind.BooleanType: - write("Boolean"); - break; - case ts.TypeReferenceSerializationKind.NumberLikeType: - write("Number"); - break; - case ts.TypeReferenceSerializationKind.StringLikeType: - write("String"); - break; - case ts.TypeReferenceSerializationKind.ArrayLikeType: - write("Array"); - break; - case ts.TypeReferenceSerializationKind.ESSymbolType: - if (languageVersion < 2 /* ES6 */) { - write("typeof Symbol === 'function' ? Symbol : Object"); - } - else { - write("Symbol"); - } - break; - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - write("Function"); - break; - case ts.TypeReferenceSerializationKind.ObjectType: - write("Object"); - break; - } - } - /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ - function emitSerializedParameterTypesOfNode(node) { - // serialization of parameter types uses the following rules: - // - // * If the declaration is a class, the parameters of the first constructor with a body are used. - // * If the declaration is function-like and has a body, the parameters of the function are used. - // - // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. - if (node) { - var valueDeclaration = void 0; - if (node.kind === 221 /* ClassDeclaration */) { - valueDeclaration = ts.getFirstConstructorWithBody(node); - } - else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { - valueDeclaration = node; - } - if (valueDeclaration) { - var parameters = valueDeclaration.parameters; - var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { - write(", "); - } - if (parameters[i].dotDotDotToken) { - var parameterType = parameters[i].type; - if (parameterType && parameterType.kind === 160 /* ArrayType */) { - parameterType = parameterType.elementType; - } - else if (parameterType && parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { - parameterType = parameterType.typeArguments[0]; - } - else { - parameterType = undefined; - } - emitSerializedTypeNode(parameterType); - } - else { - emitSerializedTypeOfNode(parameters[i]); - } - } - } - } - } - } - /** Serializes the return type of function. Used by the __metadata decorator for a method. */ - function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node)) { - if (node.type) { - emitSerializedTypeNode(node.type); - return; - } - else if (ts.isAsyncFunctionLike(node)) { - write("Promise"); - return; - } - } - write("void 0"); - } - function emitSerializedTypeMetadata(node, writeComma) { - // This method emits the serialized type metadata for a decorator target. - // The caller should have already tested whether the node has decorators. - var argumentsWritten = 0; - if (compilerOptions.emitDecoratorMetadata) { - if (shouldEmitTypeMetadata(node)) { - if (writeComma) { - write(", "); - } - writeLine(); - write("__metadata('design:type', "); - emitSerializedTypeOfNode(node); - write(")"); - argumentsWritten++; - } - if (shouldEmitParamTypesMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:paramtypes', ["); - emitSerializedParameterTypesOfNode(node); - write("])"); - argumentsWritten++; - } - if (shouldEmitReturnTypeMetadata(node)) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:returntype', "); - emitSerializedReturnTypeOfNode(node); - write(")"); - argumentsWritten++; - } - } - return argumentsWritten; - } - function emitInterfaceDeclaration(node) { - emitCommentsOnNotEmittedNode(node); - } - function shouldEmitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; - } - function emitEnumDeclaration(node) { - // const enums are completely erased during compilation. - if (!shouldEmitEnumDeclaration(node)) { - return; - } - if (!shouldHoistDeclarationInSystemJsModule(node)) { - // do not emit var if variable was already hoisted - var isES6ExportedEnum = isES6ExportedDeclaration(node); - if (!(node.flags & 1 /* Export */) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 224 /* EnumDeclaration */))) { - emitStart(node); - if (isES6ExportedEnum) { - write("export "); - } - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - writeLine(); - emitToken(16 /* CloseBraceToken */, node.members.end); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { - // do not emit var if variable was already hoisted - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { - // write the call to exporter for enum - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - function emitEnumMember(node) { - var enumParent = node.parent; - emitStart(node); - write(getGeneratedNameForNode(enumParent)); - write("["); - write(getGeneratedNameForNode(enumParent)); - write("["); - emitExpressionForPropertyName(node.name); - write("] = "); - writeEnumMemberDeclarationValue(node); - write("] = "); - emitExpressionForPropertyName(node.name); - emitEnd(node); - write(";"); - } - function writeEnumMemberDeclarationValue(member) { - var value = resolver.getConstantValue(member); - if (value !== undefined) { - write(value.toString()); - return; - } - else if (member.initializer) { - emit(member.initializer); - } - else { - write("undefined"); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); - } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); - } - function isFirstDeclarationOfKind(node, declarations, kind) { - return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); - } - function emitModuleDeclaration(node) { - // Emit only if this module is non-ambient. - var shouldEmit = shouldEmitModuleDeclaration(node); - if (!shouldEmit) { - return emitCommentsOnNotEmittedNode(node); - } - var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); - var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); - if (emitVarForModule) { - var isES6ExportedNamespace = isES6ExportedDeclaration(node); - if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 225 /* ModuleDeclaration */)) { - emitStart(node); - if (isES6ExportedNamespace) { - write("export "); - } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - } - } - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") "); - ts.Debug.assert(node.body !== undefined); // node.body must exist, as this is a non-ambient module - if (node.body.kind === 226 /* ModuleBlock */) { - var saveConvertedLoopState = convertedLoopState; - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - convertedLoopState = undefined; - tempFlags = 0; - tempVariables = undefined; - emit(node.body); - ts.Debug.assert(convertedLoopState === undefined); - convertedLoopState = saveConvertedLoopState; - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end); - } - write(")("); - // write moduleDecl = containingModule.m only if it is not exported es6 module member - if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { - if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(");"); - } - emitExportMemberAssignments(node.name); - } - } - /* - * Some bundlers (SystemJS builder) sometimes want to rename dependencies. - * Here we check if alternative name was provided for a given moduleName and return it if possible. - */ - function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { - return "\"" + renamedDependencies[moduleName.text] + "\""; - } - return undefined; - } - function emitRequire(moduleName) { - if (moduleName.kind === 9 /* StringLiteral */) { - write("require("); - var text = tryRenameExternalModule(moduleName); - if (text) { - write(text); - } - else { - emitStart(moduleName); - emitLiteral(moduleName); - emitEnd(moduleName); - } - emitToken(18 /* CloseParenToken */, moduleName.end); - } - else { - write("require()"); - } - } - function getNamespaceDeclarationNode(node) { - if (node.kind === 229 /* ImportEqualsDeclaration */) { - return node; - } - var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232 /* NamespaceImport */) { - return importClause.namedBindings; - } - } - function isDefaultImport(node) { - return node.kind === 230 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; - } - function emitExportImportAssignments(node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - emitExportMemberAssignments(node.name); - } - ts.forEachChild(node, emitExportImportAssignments); - } - function emitImportDeclaration(node) { - if (modulekind !== ts.ModuleKind.ES6) { - return emitExternalImportDeclaration(node); - } - // ES6 import - if (node.importClause) { - var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true); - if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { - write("import "); - emitStart(node.importClause); - if (shouldEmitDefaultBindings) { - emit(node.importClause.name); - if (shouldEmitNamedBindings) { - write(", "); - } - } - if (shouldEmitNamedBindings) { - emitLeadingComments(node.importClause.namedBindings); - emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 232 /* NamespaceImport */) { - write("* as "); - emit(node.importClause.namedBindings.name); - } - else { - write("{ "); - emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration); - write(" }"); - } - emitEnd(node.importClause.namedBindings); - emitTrailingComments(node.importClause.namedBindings); - } - emitEnd(node.importClause); - write(" from "); - emit(node.moduleSpecifier); - write(";"); - } - } - else { - write("import "); - emit(node.moduleSpecifier); - write(";"); - } - } - function emitExternalImportDeclaration(node) { - if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 229 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; - var namespaceDeclaration = getNamespaceDeclarationNode(node); - var varOrConst = (languageVersion <= 1 /* ES5 */) ? "var " : "const "; - if (modulekind !== ts.ModuleKind.AMD) { - emitLeadingComments(node); - emitStart(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - // import x = require("foo") - // import * as x from "foo" - if (!isExportedImport) { - write(varOrConst); - } - ; - emitModuleMemberName(namespaceDeclaration); - write(" = "); - } - else { - // import "foo" - // import x from "foo" - // import { x, y } from "foo" - // import d, * as x from "foo" - // import d, { x, y } from "foo" - var isNakedImport = 230 /* ImportDeclaration */ && !node.importClause; - if (!isNakedImport) { - write(varOrConst); - write(getGeneratedNameForNode(node)); - write(" = "); - } - } - emitRequire(ts.getExternalModuleName(node)); - if (namespaceDeclaration && isDefaultImport(node)) { - // import d, * as x from "foo" - write(", "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - else { - if (isExportedImport) { - emitModuleMemberName(namespaceDeclaration); - write(" = "); - emit(namespaceDeclaration.name); - write(";"); - } - else if (namespaceDeclaration && isDefaultImport(node)) { - // import d, * as x from "foo" - write(varOrConst); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - write(";"); - } - emitExportImportAssignments(node); - } - } - } - function emitImportEqualsDeclaration(node) { - if (ts.isExternalModuleImportEqualsDeclaration(node)) { - emitExternalImportDeclaration(node); - return; - } - // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when - // - current file is not external module - // - import declaration is top level and target is value imported by entity name - if (resolver.isReferencedAliasDeclaration(node) || - (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { - emitLeadingComments(node); - emitStart(node); - // variable declaration for import-equals declaration can be hoisted in system modules - // in this case 'var' should be omitted and emit should contain only initialization - var variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); - // is it top level export import v = a.b.c in system module? - // if yes - it needs to be rewritten as exporter('v', v = a.b.c) - var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); - if (!variableDeclarationIsHoisted) { - ts.Debug.assert(!isExported); - if (isES6ExportedDeclaration(node)) { - write("export "); - write("var "); - } - else if (!(node.flags & 1 /* Export */)) { - write("var "); - } - } - if (isExported) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.name); - write("\", "); - } - emitModuleMemberName(node); - write(" = "); - emit(node.moduleReference); - if (isExported) { - write(")"); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - } - function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== ts.ModuleKind.System); - if (modulekind !== ts.ModuleKind.ES6) { - if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { - emitStart(node); - var generatedName = getGeneratedNameForNode(node); - if (node.exportClause) { - // export { x, y, ... } from "foo" - if (modulekind !== ts.ModuleKind.AMD) { - write("var "); - write(generatedName); - write(" = "); - emitRequire(ts.getExternalModuleName(node)); - write(";"); - } - for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) { - var specifier = _b[_a]; - if (resolver.isValueAliasDeclaration(specifier)) { - writeLine(); - emitStart(specifier); - emitContainingModuleName(specifier); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.name); - write(" = "); - write(generatedName); - write("."); - emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name); - write(";"); - emitEnd(specifier); - } - } - } - else { - // export * from "foo" - if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - writeLine(); - write("__export("); - if (modulekind !== ts.ModuleKind.AMD) { - emitRequire(ts.getExternalModuleName(node)); - } - else { - write(generatedName); - } - write(");"); - } - } - emitEnd(node); - } - } - else { - if (!node.exportClause || resolver.isValueAliasDeclaration(node)) { - write("export "); - if (node.exportClause) { - // export { x, y, ... } - write("{ "); - emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emit(node.moduleSpecifier); - } - write(";"); - } - } - } - function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === ts.ModuleKind.ES6); - var needsComma = false; - for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { - var specifier = specifiers_1[_a]; - if (shouldEmit(specifier)) { - if (needsComma) { - write(", "); - } - if (specifier.propertyName) { - emit(specifier.propertyName); - write(" as "); - } - emit(specifier.name); - needsComma = true; - } - } - } - function emitExportAssignment(node) { - if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === ts.ModuleKind.ES6) { - writeLine(); - emitStart(node); - write("export default "); - var expression = node.expression; - emit(expression); - if (expression.kind !== 220 /* FunctionDeclaration */ && - expression.kind !== 221 /* ClassDeclaration */) { - write(";"); - } - emitEnd(node); - } - else { - writeLine(); - emitStart(node); - if (modulekind === ts.ModuleKind.System) { - write(exportFunctionForFile + "(\"default\","); - emit(node.expression); - write(")"); - } - else { - emitEs6ExportDefaultCompat(node); - emitContainingModuleName(node); - if (languageVersion === 0 /* ES3 */) { - write('["default"] = '); - } - else { - write(".default = "); - } - emit(node.expression); - } - write(";"); - emitEnd(node); - } - } - } - function collectExternalModuleInfo(sourceFile) { - externalImports = []; - exportSpecifiers = {}; - exportEquals = undefined; - hasExportStarsToExportValues = false; - for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { - var node = _b[_a]; - switch (node.kind) { - case 230 /* ImportDeclaration */: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { - // import "mod" - // import x from "mod" where x is referenced - // import * as x from "mod" where x is referenced - // import { x, y } from "mod" where at least one import is referenced - externalImports.push(node); - } - break; - case 229 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 240 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { - // import x = require("mod") where x is referenced - externalImports.push(node); - } - break; - case 236 /* ExportDeclaration */: - if (node.moduleSpecifier) { - if (!node.exportClause) { - // export * from "mod" - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - // export { x, y } from "mod" where at least one export is a value symbol - externalImports.push(node); - } - } - else { - // export { x, y } - for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { - var specifier = _d[_c]; - var name_30 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_30] || (exportSpecifiers[name_30] = [])).push(specifier); - } - } - break; - case 235 /* ExportAssignment */: - if (node.isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; - } - } - } - function emitExportStarHelper() { - if (hasExportStarsToExportValues) { - writeLine(); - write("function __export(m) {"); - increaseIndent(); - writeLine(); - write("for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function getLocalNameForExternalImport(node) { - var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); - } - if (node.kind === 230 /* ImportDeclaration */ && node.importClause) { - return getGeneratedNameForNode(node); - } - if (node.kind === 236 /* ExportDeclaration */ && node.moduleSpecifier) { - return getGeneratedNameForNode(node); - } - } - function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { - if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - return "\"" + name_31 + "\""; - } - } - var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 9 /* StringLiteral */) { - return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); - } - return undefined; - } - function emitVariableDeclarationsForImports() { - if (externalImports.length === 0) { - return; - } - writeLine(); - var started = false; - for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { - var importNode = externalImports_1[_a]; - // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 236 /* ExportDeclaration */ || - (importNode.kind === 230 /* ImportDeclaration */ && !importNode.importClause); - if (skipNode) { - continue; - } - if (!started) { - write("var "); - started = true; - } - else { - write(", "); - } - write(getLocalNameForExternalImport(importNode)); - } - if (started) { - write(";"); - } - } - function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - // 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 exports. - if (!hasExportStarsToExportValues) { - // 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 && ts.isEmpty(exportSpecifiers)) { - // no exported declarations (export var ...) or export specifiers (export {x}) - // check if we have any non star export declarations. - var hasExportDeclarationWithExportClause = false; - for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { - var externalImport = externalImports_2[_a]; - if (externalImport.kind === 236 /* ExportDeclaration */ && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - // we still need to emit exportStar helper - return emitExportStarFunction(/*localNames*/ undefined); - } - } - var exportedNamesStorageRef = makeUniqueName("exportedNames"); - writeLine(); - write("var " + exportedNamesStorageRef + " = {"); - increaseIndent(); - var started = false; - if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; i++) { - // write name of exported declaration, i.e 'export var x...' - writeExportedName(exportedDeclarations[i]); - } - } - if (exportSpecifiers) { - for (var n in exportSpecifiers) { - for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) { - var specifier = _c[_b]; - // write name of export specified, i.e. 'export {x}' - writeExportedName(specifier.name); - } - } - } - for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { - var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 236 /* ExportDeclaration */) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - // export * from ... - continue; - } - for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) { - var element = _f[_e]; - // 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) { - var exportStarFunction = makeUniqueName("exportStar"); - writeLine(); - // define an export star helper function - write("function " + exportStarFunction + "(m) {"); - increaseIndent(); - writeLine(); - write("var exports = {};"); - writeLine(); - write("for(var n in m) {"); - increaseIndent(); - writeLine(); - write("if (n !== \"default\""); - if (localNames) { - write("&& !" + localNames + ".hasOwnProperty(n)"); - } - write(") exports[n] = m[n];"); - decreaseIndent(); - writeLine(); - write("}"); - writeLine(); - write(exportFunctionForFile + "(exports);"); - decreaseIndent(); - writeLine(); - write("}"); - return exportStarFunction; - } - function writeExportedName(node) { - // do not record default exports - // they are local to module and never overwritten (explicitly skipped) by star export - if (node.kind !== 69 /* Identifier */ && node.flags & 512 /* Default */) { - return; - } - if (started) { - write(","); - } - else { - started = true; - } - writeLine(); - write("'"); - if (node.kind === 69 /* Identifier */) { - emitNodeWithCommentsAndWithoutSourcemap(node); - } - else { - emitDeclarationName(node); - } - write("': true"); - } - } - function processTopLevelVariableAndFunctionDeclarations(node) { - // per ES6 spec: - // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method - // - var declarations are initialized to undefined - 14.a.ii - // - function/generator declarations are instantiated - 16.a.iv - // this means that after module is instantiated but before its evaluation - // exported functions are already accessible at import sites - // in theory we should hoist only exported functions and its dependencies - // in practice to simplify things we'll hoist all source level functions and variable declaration - // including variables declarations for module and class declarations - var hoistedVars; - var hoistedFunctionDeclarations; - var exportedDeclarations; - visit(node); - if (hoistedVars) { - writeLine(); - write("var "); - var seen = {}; - for (var i = 0; i < hoistedVars.length; i++) { - var local = hoistedVars[i]; - var name_32 = local.kind === 69 /* Identifier */ - ? local - : local.name; - if (name_32) { - // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_32.text); - if (ts.hasProperty(seen, text)) { - continue; - } - else { - seen[text] = text; - } - } - if (i !== 0) { - write(", "); - } - if (local.kind === 221 /* ClassDeclaration */ || local.kind === 225 /* ModuleDeclaration */ || local.kind === 224 /* EnumDeclaration */) { - emitDeclarationName(local); - } - else { - emit(local); - } - var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); - if (flags & 1 /* Export */) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(local); - } - } - write(";"); - } - if (hoistedFunctionDeclarations) { - for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { - var f = hoistedFunctionDeclarations_1[_a]; - writeLine(); - emit(f); - if (f.flags & 1 /* Export */) { - if (!exportedDeclarations) { - exportedDeclarations = []; - } - exportedDeclarations.push(f); - } - } - } - return exportedDeclarations; - function visit(node) { - if (node.flags & 2 /* Ambient */) { - return; - } - if (node.kind === 220 /* FunctionDeclaration */) { - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = []; - } - hoistedFunctionDeclarations.push(node); - return; - } - if (node.kind === 221 /* ClassDeclaration */) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - return; - } - if (node.kind === 224 /* EnumDeclaration */) { - if (shouldEmitEnumDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 225 /* ModuleDeclaration */) { - if (shouldEmitModuleDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - } - return; - } - if (node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) { - if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - var name_33 = node.name; - if (name_33.kind === 69 /* Identifier */) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(name_33); - } - else { - ts.forEachChild(name_33, visit); - } - } - return; - } - if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node.name); - return; - } - if (ts.isBindingPattern(node)) { - ts.forEach(node.elements, visit); - return; - } - if (!ts.isDeclaration(node)) { - ts.forEachChild(node, visit); - } - } - } - function shouldHoistVariable(node, checkIfSourceFileLevelDecl) { - if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { - return false; - } - // hoist variable if - // - it is not block scoped - // - it is top level block scoped - // if block scoped variables are nested in some another block then - // no other functions can use them except ones that are defined at least in the same block - return (ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 256 /* SourceFile */; - } - function isCurrentFileSystemExternalModule() { - return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; - } - function emitSystemModuleBody(node, dependencyGroups, startIndex) { - // shape of the body in system modules: - // function (exports) { - // - // - // - // return { - // setters: [ - // - // ], - // execute: function() { - // - // } - // } - // - // } - // I.e: - // import {x} from 'file1' - // var y = 1; - // export function foo() { return y + x(); } - // console.log(y); - // will be transformed to - // function(exports) { - // var file1; // local alias - // var y; - // function foo() { return y + file1.x(); } - // exports("foo", foo); - // return { - // setters: [ - // function(v) { file1 = v } - // ], - // execute(): function() { - // y = 1; - // console.log(y); - // } - // }; - // } - emitVariableDeclarationsForImports(); - writeLine(); - var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); - writeLine(); - write("return {"); - increaseIndent(); - writeLine(); - emitSetters(exportStarFunction, dependencyGroups); - writeLine(); - emitExecute(node, startIndex); - decreaseIndent(); - writeLine(); - write("}"); // return - emitTempDeclarations(/*newLine*/ true); - } - function emitSetters(exportStarFunction, dependencyGroups) { - write("setters:["); - for (var i = 0; i < dependencyGroups.length; i++) { - if (i !== 0) { - write(","); - } - writeLine(); - increaseIndent(); - var group = dependencyGroups[i]; - // derive a unique name for parameter from the first named entry in the group - var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); - write("function (" + parameterName + ") {"); - increaseIndent(); - for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { - var entry = group_1[_a]; - var importVariableName = getLocalNameForExternalImport(entry) || ""; - switch (entry.kind) { - case 230 /* ImportDeclaration */: - if (!entry.importClause) { - // 'import "..."' case - // module is imported only for side-effects, no emit required - break; - } - // fall-through - case 229 /* ImportEqualsDeclaration */: - ts.Debug.assert(importVariableName !== ""); - writeLine(); - // save import into the local - write(importVariableName + " = " + parameterName + ";"); - writeLine(); - break; - case 236 /* ExportDeclaration */: - ts.Debug.assert(importVariableName !== ""); - if (entry.exportClause) { - // export {a, b as c} from 'foo' - // emit as: - // exports_({ - // "a": _["a"], - // "c": _["b"] - // }); - writeLine(); - write(exportFunctionForFile + "({"); - writeLine(); - increaseIndent(); - for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { - if (i_1 !== 0) { - write(","); - writeLine(); - } - var e = entry.exportClause.elements[i_1]; - write("\""); - emitNodeWithCommentsAndWithoutSourcemap(e.name); - write("\": " + parameterName + "[\""); - emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name); - write("\"]"); - } - decreaseIndent(); - writeLine(); - write("});"); - } - else { - // collectExternalModuleInfo prefilters star exports to keep only ones that export values - // this means that check 'resolver.moduleExportsSomeValue' is redundant and can be omitted here - writeLine(); - // export * from 'foo' - // emit as: - // exportStar(_foo); - write(exportStarFunction + "(" + parameterName + ");"); - } - writeLine(); - break; - } - } - decreaseIndent(); - write("}"); - decreaseIndent(); - } - write("],"); - } - function emitExecute(node, startIndex) { - write("execute: function() {"); - increaseIndent(); - writeLine(); - for (var i = startIndex; i < node.statements.length; i++) { - var statement = node.statements[i]; - switch (statement.kind) { - // - function declarations are not emitted because they were already hoisted - // - import declarations are not emitted since they are already handled in setters - // - export declarations with module specifiers are not emitted since they were already written in setters - // - export declarations without module specifiers are emitted preserving the order - case 220 /* FunctionDeclaration */: - case 230 /* ImportDeclaration */: - continue; - case 236 /* ExportDeclaration */: - if (!statement.moduleSpecifier) { - for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { - var element = _b[_a]; - // write call to exporter function for every export specifier in exports list - emitExportSpecifierInSystemModule(element); - } - } - continue; - case 229 /* ImportEqualsDeclaration */: - if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { - // - import equals declarations that import external modules are not emitted - continue; - } - // fall-though for import declarations that import internal modules - default: - writeLine(); - emit(statement); - } - } - decreaseIndent(); - writeLine(); - write("}"); // execute - } - function writeModuleName(node, emitRelativePathAsModuleName) { - var moduleName = node.moduleName; - if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { - write("\"" + moduleName + "\", "); - } - } - function emitSystemModule(node, emitRelativePathAsModuleName) { - collectExternalModuleInfo(node); - // System modules has the following shape - // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) - // 'exports' here is a function 'exports(name: string, value: T): T' that is used to publish exported values. - // 'exports' returns its 'value' argument so in most cases expressions - // that mutate exported values can be rewritten as: - // expr -> exports('name', expr). - // The only exception in this rule is postfix unary operators, - // see comment to 'emitPostfixUnaryExpression' for more details - ts.Debug.assert(!exportFunctionForFile); - // make sure that name of 'exports' function does not conflict with existing identifiers - exportFunctionForFile = makeUniqueName("exports"); - contextObjectForFile = makeUniqueName("context"); - writeLine(); - write("System.register("); - writeModuleName(node, emitRelativePathAsModuleName); - write("["); - var groupIndices = {}; - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); - if (text === undefined) { - continue; - } - // text should be quoted string - // for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same - var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { - // deduplicate/group entries in dependency list by the dependency name - var groupIndex = groupIndices[key]; - dependencyGroups[groupIndex].push(externalImports[i]); - continue; - } - else { - groupIndices[key] = dependencyGroups.length; - dependencyGroups.push([externalImports[i]]); - } - if (i !== 0) { - write(", "); - } - write(text); - } - write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); - writeLine(); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - writeLine(); - write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); - writeLine(); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitSystemModuleBody(node, dependencyGroups, startIndex); - decreaseIndent(); - writeLine(); - write("});"); - } - function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - // names of modules with corresponding parameter in the factory function - var aliasedModuleNames = []; - // names of modules with no corresponding parameters in factory function - var unaliasedModuleNames = []; - var importAliasNames = []; // names of the parameters in the factory function; these - // parameters need to match the indexes of the corresponding - // module names in aliasedModuleNames. - // Fill in amd-dependency tags - for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) { - var amdDependency = _b[_a]; - if (amdDependency.name) { - aliasedModuleNames.push('"' + amdDependency.path + '"'); - importAliasNames.push(amdDependency.name); - } - else { - unaliasedModuleNames.push('"' + amdDependency.path + '"'); - } - } - for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { - var importNode = externalImports_4[_c]; - // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); - // Find the name of the module alias, if there is one - var importAliasName = getLocalNameForExternalImport(importNode); - if (includeNonAmdDependencies && importAliasName) { - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(importAliasName); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { - // An AMD define function has the following shape: - // define(id?, dependencies?, factory); - // - // This has the shape of - // define(name, ["module1", "module2"], function (module1Alias) { - // The location of the alias in the parameter list in the factory function needs to - // match the position of the module name in the dependency list. - // - // To ensure this is true in cases of modules with no aliases, e.g.: - // `import "module"` or `` - // we need to add modules without alias names to the end of the dependencies list - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); - emitAMDDependencyList(dependencyNames); - write(", "); - emitAMDFactoryHeader(dependencyNames); - } - function emitAMDDependencyList(_a) { - var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames; - write('["require", "exports"'); - if (aliasedModuleNames.length) { - write(", "); - write(aliasedModuleNames.join(", ")); - } - if (unaliasedModuleNames.length) { - write(", "); - write(unaliasedModuleNames.join(", ")); - } - write("]"); - } - function emitAMDFactoryHeader(_a) { - var importAliasNames = _a.importAliasNames; - write("function (require, exports"); - if (importAliasNames.length) { - write(", "); - write(importAliasNames.join(", ")); - } - write(") {"); - } - function emitAMDModule(node, emitRelativePathAsModuleName) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - writeLine(); - write("define("); - writeModuleName(node, emitRelativePathAsModuleName); - emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(/*emitAsReturn*/ true); - emitTempDeclarations(/*newLine*/ true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - emitEmitHelpers(node); - collectExternalModuleInfo(node); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(/*emitAsReturn*/ false); - emitTempDeclarations(/*newLine*/ true); - } - function emitUMDModule(node) { - emitEmitHelpers(node); - collectExternalModuleInfo(node); - var dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false); - // Module is detected first to support Browserify users that load into a browser with an AMD loader - writeLines("(function (factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define("); - emitAMDDependencyList(dependencyNames); - write(", factory);"); - writeLines(" }\n})("); - emitAMDFactoryHeader(dependencyNames); - increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitExportEquals(/*emitAsReturn*/ true); - emitTempDeclarations(/*newLine*/ true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitES6Module(node) { - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(/*newLine*/ true); - // Emit exportDefault if it exists will happen as part - // or normal statement emit. - } - function emitExportEquals(emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - writeLine(); - emitStart(exportEquals); - write(emitAsReturn ? "return " : "module.exports = "); - emit(exportEquals.expression); - write(";"); - emitEnd(exportEquals); - } - } - function emitJsxElement(node) { - switch (compilerOptions.jsx) { - case 2 /* React */: - jsxEmitReact(node); - break; - case 1 /* Preserve */: - // Fall back to preserve if None was specified (we'll error earlier) - default: - jsxEmitPreserve(node); - break; - } - } - function trimReactWhitespaceAndApplyEntities(node) { - var result = undefined; - var text = ts.getTextOfNode(node, /*includeTrivia*/ true); - var firstNonWhitespace = 0; - var lastNonWhitespace = -1; - // JSX trims whitespace at the end and beginning of lines, except that the - // start/end of a tag is considered a start/end of a line only if that line is - // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx - for (var i = 0; i < text.length; i++) { - var c = text.charCodeAt(i); - if (ts.isLineBreak(c)) { - if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { - var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - firstNonWhitespace = -1; - } - else if (!ts.isWhiteSpaceSingleLine(c)) { - lastNonWhitespace = i; - if (firstNonWhitespace === -1) { - firstNonWhitespace = i; - } - } - } - if (firstNonWhitespace !== -1) { - var part = text.substr(firstNonWhitespace); - result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); - } - if (result) { - // Replace entities like   - result = result.replace(/&(\w+);/g, function (s, m) { - if (entities[m] !== undefined) { - var ch = String.fromCharCode(entities[m]); - // " needs to be escaped - return ch === '"' ? "\\\"" : ch; - } - else { - return s; - } - }); - } - return result; - } - function isJsxChildEmittable(child) { - if (child.kind === 248 /* JsxExpression */) { - // Don't emit empty expressions - return !!child.expression; - } - else if (child.kind === 244 /* JsxText */) { - // Don't emit empty strings - return !!getTextToEmit(child); - } - return true; - } - ; - function getTextToEmit(node) { - switch (compilerOptions.jsx) { - case 2 /* React */: - var text = trimReactWhitespaceAndApplyEntities(node); - if (text === undefined || text.length === 0) { - return undefined; - } - else { - return text; - } - case 1 /* Preserve */: - default: - return ts.getTextOfNode(node, /*includeTrivia*/ true); - } - } - function emitJsxText(node) { - switch (compilerOptions.jsx) { - case 2 /* React */: - write('"'); - write(trimReactWhitespaceAndApplyEntities(node)); - write('"'); - break; - case 1 /* Preserve */: - default: - writer.writeLiteral(ts.getTextOfNode(node, /*includeTrivia*/ true)); - break; - } - } - function emitJsxExpression(node) { - if (node.expression) { - switch (compilerOptions.jsx) { - case 1 /* Preserve */: - default: - write("{"); - emit(node.expression); - write("}"); - break; - case 2 /* React */: - emit(node.expression); - break; - } - } - } - function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; - } - function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { - if (writeUseStrict) { - if (startWithNewLine) { - writeLine(); - } - write("\"use strict\";"); - } - } - function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { - var foundUseStrict = false; - for (var i = 0; i < statements.length; i++) { - if (ts.isPrologueDirective(statements[i])) { - if (isUseStrictPrologue(statements[i])) { - foundUseStrict = true; - } - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); - // return index of the first non prologue directive - return i; - } - } - ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); - return statements.length; - } - function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line.length) { - writeLine(); - write(line); - } - } - } - function emitEmitHelpers(node) { - // 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 < 2 /* ES6 */ && !extendsEmitted && node.flags & 262144 /* HasClassExtends */) { - writeLines(extendsHelper); - extendsEmitted = true; - } - if (compilerOptions.jsx !== 1 /* Preserve */ && !assignEmitted && (node.flags & 1073741824 /* HasJsxSpreadAttribute */)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 524288 /* HasDecorators */) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); - } - decorateEmitted = true; - } - if (!paramEmitted && node.flags & 1048576 /* HasParamDecorators */) { - writeLines(paramHelper); - paramEmitted = true; - } - if (!awaiterEmitted && node.flags & 2097152 /* HasAsyncFunctions */) { - writeLines(awaiterHelper); - awaiterEmitted = true; - } - } - } - function emitSourceFileNode(node) { - // Start new file on new line - writeLine(); - emitShebang(); - emitDetachedCommentsAndUpdateCommentsInfo(node); - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; - emitModule(node); - } - else { - bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/ true); - } - } - else { - // emit prologue directives prior to __extends - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - emitEmitHelpers(node); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(/*newLine*/ true); - } - emitLeadingComments(node.endOfFileToken); - } - function emit(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - function emitNodeWithCommentsAndWithoutSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); - } - function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { - if (node) { - if (node.flags & 2 /* Ambient */) { - return emitCommentsOnNotEmittedNode(node); - } - if (isSpecializedCommentHandling(node)) { - // This is the node that will handle its own comments and sourcemap - return emitNodeWithoutSourceMap(node); - } - var emitComments_1 = shouldEmitLeadingAndTrailingComments(node); - if (emitComments_1) { - emitLeadingComments(node); - } - emitNodeConsideringSourcemap(node); - if (emitComments_1) { - emitTrailingComments(node); - } - } - } - function emitNodeWithSourceMap(node) { - if (node) { - emitStart(node); - emitNodeWithoutSourceMap(node); - emitEnd(node); - } - } - function emitNodeWithoutSourceMap(node) { - if (node) { - emitJavaScriptWorker(node); - } - } - function changeSourceMapEmit(writer) { - sourceMap = writer; - emitStart = writer.emitStart; - emitEnd = writer.emitEnd; - emitPos = writer.emitPos; - setSourceFile = writer.setSourceFile; - } - function withTemporaryNoSourceMap(callback) { - var prevSourceMap = sourceMap; - setSourceMapWriterEmit(ts.getNullSourceMapWriter()); - callback(); - setSourceMapWriterEmit(prevSourceMap); - } - function isSpecializedCommentHandling(node) { - switch (node.kind) { - // All of these entities are emitted in a specialized fashion. As such, we allow - // the specialized methods for each to handle the comments on the nodes. - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 235 /* ExportAssignment */: - return true; - } - } - function shouldEmitLeadingAndTrailingComments(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 225 /* ModuleDeclaration */: - // Only emit the leading/trailing comments for a module if we're actually - // emitting the module as well. - return shouldEmitModuleDeclaration(node); - case 224 /* EnumDeclaration */: - // Only emit the leading/trailing comments for an enum if we're actually - // emitting the module as well. - return shouldEmitEnumDeclaration(node); - } - // If the node is emitted in specialized fashion, dont emit comments as this node will handle - // emitting comments when emitting itself - ts.Debug.assert(!isSpecializedCommentHandling(node)); - // If this is the expression body of an arrow function that we're down-leveling, - // then we don't want to emit comments when we emit the body. It will have already - // been taken care of when we emitted the 'return' statement for the function - // expression body. - if (node.kind !== 199 /* Block */ && - node.parent && - node.parent.kind === 180 /* ArrowFunction */ && - node.parent.body === node && - languageVersion <= 1 /* ES5 */) { - return false; - } - // Emit comments for everything else. - return true; - } - function emitJavaScriptWorker(node) { - // Check if the node can be emitted regardless of the ScriptTarget - switch (node.kind) { - case 69 /* Identifier */: - return emitIdentifier(node); - case 142 /* Parameter */: - return emitParameter(node); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return emitMethod(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return emitAccessor(node); - case 97 /* ThisKeyword */: - return emitThis(node); - case 95 /* SuperKeyword */: - return emitSuper(node); - case 93 /* NullKeyword */: - return write("null"); - case 99 /* TrueKeyword */: - return write("true"); - case 84 /* FalseKeyword */: - return write("false"); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 10 /* RegularExpressionLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: - return emitLiteral(node); - case 189 /* TemplateExpression */: - return emitTemplateExpression(node); - case 197 /* TemplateSpan */: - return emitTemplateSpan(node); - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - return emitJsxElement(node); - case 244 /* JsxText */: - return emitJsxText(node); - case 248 /* JsxExpression */: - return emitJsxExpression(node); - case 139 /* QualifiedName */: - return emitQualifiedName(node); - case 167 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 168 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 169 /* BindingElement */: - return emitBindingElement(node); - case 170 /* ArrayLiteralExpression */: - return emitArrayLiteral(node); - case 171 /* ObjectLiteralExpression */: - return emitObjectLiteral(node); - case 253 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 254 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 140 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - case 172 /* PropertyAccessExpression */: - return emitPropertyAccess(node); - case 173 /* ElementAccessExpression */: - return emitIndexedAccess(node); - case 174 /* CallExpression */: - return emitCallExpression(node); - case 175 /* NewExpression */: - return emitNewExpression(node); - case 176 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: - case 196 /* NonNullExpression */: - return emit(node.expression); - case 178 /* ParenthesizedExpression */: - return emitParenExpression(node); - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - return emitFunctionDeclaration(node); - case 181 /* DeleteExpression */: - return emitDeleteExpression(node); - case 182 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 183 /* VoidExpression */: - return emitVoidExpression(node); - case 184 /* AwaitExpression */: - return emitAwaitExpression(node); - case 185 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 186 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 187 /* BinaryExpression */: - return emitBinaryExpression(node); - case 188 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 191 /* SpreadElementExpression */: - return emitSpreadElementExpression(node); - case 190 /* YieldExpression */: - return emitYieldExpression(node); - case 193 /* OmittedExpression */: - return; - case 199 /* Block */: - case 226 /* ModuleBlock */: - return emitBlock(node); - case 200 /* VariableStatement */: - return emitVariableStatement(node); - case 201 /* EmptyStatement */: - return write(";"); - case 202 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 203 /* IfStatement */: - return emitIfStatement(node); - case 204 /* DoStatement */: - return emitDoStatement(node); - case 205 /* WhileStatement */: - return emitWhileStatement(node); - case 206 /* ForStatement */: - return emitForStatement(node); - case 208 /* ForOfStatement */: - case 207 /* ForInStatement */: - return emitForInOrForOfStatement(node); - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: - return emitBreakOrContinueStatement(node); - case 211 /* ReturnStatement */: - return emitReturnStatement(node); - case 212 /* WithStatement */: - return emitWithStatement(node); - case 213 /* SwitchStatement */: - return emitSwitchStatement(node); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: - return emitCaseOrDefaultClause(node); - case 214 /* LabeledStatement */: - return emitLabeledStatement(node); - case 215 /* ThrowStatement */: - return emitThrowStatement(node); - case 216 /* TryStatement */: - return emitTryStatement(node); - case 252 /* CatchClause */: - return emitCatchClause(node); - case 217 /* DebuggerStatement */: - return emitDebuggerStatement(node); - case 218 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 192 /* ClassExpression */: - return emitClassExpression(node); - case 221 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 222 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 224 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 255 /* EnumMember */: - return emitEnumMember(node); - case 225 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 230 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 235 /* ExportAssignment */: - return emitExportAssignment(node); - case 256 /* SourceFile */: - return emitSourceFileNode(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - **/ - function isTripleSlashComment(comment) { - // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text - // so that we don't end up computing comment string and doing match for all // comments - if (currentText.charCodeAt(comment.pos + 1) === 47 /* slash */ && - comment.pos + 2 < comment.end && - currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) { - var textSubStr = currentText.substring(comment.pos, comment.end); - return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || - textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? - true : false; - } - return false; - } - function getLeadingCommentsToEmit(node) { - // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments - if (node.parent) { - if (node.parent.kind === 256 /* SourceFile */ || node.pos !== node.parent.pos) { - if (hasDetachedComments(node.pos)) { - // get comments without detached comments - return getLeadingCommentsWithoutDetachedComments(); - } - else { - // get the leading comments from the node - return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); - } - } - } - } - function getTrailingCommentsToEmit(node) { - // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments - if (node.parent) { - if (node.parent.kind === 256 /* SourceFile */ || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentText, node.end); - } - } - } - /** - * Emit comments associated with node that will not be emitted into JS file - */ - function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, /*isEmittedNode*/ false); - } - function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true); - } - function emitLeadingCommentsWorker(node, isEmittedNode) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (isEmittedNode) { - leadingComments = getLeadingCommentsToEmit(node); - } - else { - // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, - // unless it is a triple slash comment at the top of the file. - // For Example: - // /// - // declare var x; - // /// - // interface F {} - // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted - if (node.pos === 0) { - leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); - } - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); - } - function emitTrailingComments(node) { - if (compilerOptions.removeComments) { - return; - } - // Emit the trailing comments only if the parent's end doesn't match - var trailingComments = getTrailingCommentsToEmit(node); - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); - } - /** - * Emit trailing comments at the position. The term trailing comment is used here to describe following comment: - * x, /comment1/ y - * ^ => pos; the function will emit "comment1" in the emitJS - */ - function emitTrailingCommentsOfPosition(pos) { - if (compilerOptions.removeComments) { - return; - } - var trailingComments = ts.getTrailingCommentRanges(currentText, pos); - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); - } - function emitLeadingCommentsOfPositionWorker(pos) { - if (compilerOptions.removeComments) { - return; - } - var leadingComments; - if (hasDetachedComments(pos)) { - // get comments without detached comments - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - // get the leading comments from the node - leadingComments = ts.getLeadingCommentRanges(currentText, pos); - } - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); - } - function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); - if (currentDetachedCommentInfo) { - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - function writeComment(text, lineMap, writer, comment, newLine) { - emitPos(comment.pos); - ts.writeCommentRange(text, lineMap, writer, comment, newLine); - emitPos(comment.end); - } - function emitShebang() { - var shebang = ts.getShebang(currentText); - if (shebang) { - write(shebang); - writeLine(); - } - } - var _a, _b; - } - function emitFile(_a, sourceFiles, isBundledEmit) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - // Make sure not to write js File and source map file if any of them cannot be written + function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { + // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { emittedFilesList.push(jsFilePath); @@ -42923,25 +54486,2342 @@ var ts; } } } + function printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNameSet = ts.createMap(); + isOwnFileEmit = !isBundledEmit; + // Emit helpers from all the files + if (isBundledEmit && moduleKind) { + for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { + var sourceFile = sourceFiles_4[_a]; + emitEmitHelpers(sourceFile); + } + } + // Print each transformed source file. + ts.forEach(sourceFiles, printSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + } + // Write the source map + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); + } + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); + } + // Write the output file + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + // Reset state + sourceMap.reset(); + comments.reset(); + writer.reset(); + tempFlags = 0 /* Auto */; + currentSourceFile = undefined; + currentText = undefined; + extendsEmitted = false; + assignEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + isOwnFileEmit = false; + } + function printSourceFile(node) { + currentSourceFile = node; + currentText = node.text; + currentFileIdentifiers = node.identifiers; + sourceMap.setSourceFile(node); + comments.setSourceFile(node); + emitNodeWithNotification(node, emitWorker); + } + /** + * Emits a node. + */ + function emit(node) { + emitNodeWithNotification(node, emitWithComments); + } + /** + * Emits a node with comments. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from emit. + */ + function emitWithComments(node) { + emitNodeWithComments(node, emitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from emitWithComments. + */ + function emitWithSourceMap(node) { + emitNodeWithSourceMap(node, emitWorker); + } + function emitIdentifierName(node) { + if (node) { + emitNodeWithNotification(node, emitIdentifierNameWithComments); + } + } + function emitIdentifierNameWithComments(node) { + emitNodeWithComments(node, emitWorker); + } + /** + * Emits an expression node. + */ + function emitExpression(node) { + emitNodeWithNotification(node, emitExpressionWithComments); + } + /** + * Emits an expression with comments. + * + * NOTE: Do not call this method directly. It is part of the emitExpression pipeline + * and should only be called indirectly from emitExpression. + */ + function emitExpressionWithComments(node) { + emitNodeWithComments(node, emitExpressionWithSourceMap); + } + /** + * Emits an expression with source maps. + * + * NOTE: Do not call this method directly. It is part of the emitExpression pipeline + * and should only be called indirectly from emitExpressionWithComments. + */ + function emitExpressionWithSourceMap(node) { + emitNodeWithSourceMap(node, emitExpressionWorker); + } + /** + * Emits a node with emit notification if available. + */ + function emitNodeWithNotification(node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(node, emitCallback); + } + else { + emitCallback(node); + } + } + } + function emitNodeWithSourceMap(node, emitCallback) { + if (node) { + emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + emitCallback(node); + emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function getSourceMapRange(node) { + return node.sourceMapRange || node; + } + /** + * Determines whether to skip leading comment emit for a node. + * + * We do not emit comments for NotEmittedStatement nodes or any node that has + * NodeEmitFlags.NoLeadingComments. + * + * @param node A Node. + */ + function shouldSkipLeadingCommentsForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; + } + /** + * Determines whether to skip source map emit for the start position of a node. + * + * We do not emit source maps for NotEmittedStatement nodes or any node that + * has NodeEmitFlags.NoLeadingSourceMap. + * + * @param node A Node. + */ + function shouldSkipLeadingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; + } + /** + * Determines whether to skip source map emit for the end position of a node. + * + * We do not emit source maps for NotEmittedStatement nodes or any node that + * has NodeEmitFlags.NoTrailingSourceMap. + * + * @param node A Node. + */ + function shouldSkipTrailingSourceMapForNode(node) { + return ts.isNotEmittedStatement(node) + || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; + } + /** + * Determines whether to skip source map emit for a node and its children. + * + * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. + */ + function shouldSkipSourceMapForChildren(node) { + return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; + } + function emitWorker(node) { + if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + return; + } + var kind = node.kind; + switch (kind) { + // Pseudo-literals + case 12 /* TemplateHead */: + case 13 /* TemplateMiddle */: + case 14 /* TemplateTail */: + return emitLiteral(node); + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 74 /* ConstKeyword */: + case 77 /* DefaultKeyword */: + case 82 /* ExportKeyword */: + case 103 /* VoidKeyword */: + // Strict mode reserved words + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 112 /* PublicKeyword */: + case 113 /* StaticKeyword */: + // Contextual keywords + case 115 /* AbstractKeyword */: + case 117 /* AnyKeyword */: + case 118 /* AsyncKeyword */: + case 120 /* BooleanKeyword */: + case 122 /* DeclareKeyword */: + case 130 /* NumberKeyword */: + case 128 /* ReadonlyKeyword */: + case 132 /* StringKeyword */: + case 133 /* SymbolKeyword */: + case 137 /* GlobalKeyword */: + return writeTokenNode(node); + // Parse tree nodes + // Names + case 139 /* QualifiedName */: + return emitQualifiedName(node); + case 140 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 141 /* TypeParameter */: + return emitTypeParameter(node); + case 142 /* Parameter */: + return emitParameter(node); + case 143 /* Decorator */: + return emitDecorator(node); + // Type members + case 144 /* PropertySignature */: + return emitPropertySignature(node); + case 145 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 146 /* MethodSignature */: + return emitMethodSignature(node); + case 147 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 148 /* Constructor */: + return emitConstructor(node); + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 151 /* CallSignature */: + return emitCallSignature(node); + case 152 /* ConstructSignature */: + return emitConstructSignature(node); + case 153 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 154 /* TypePredicate */: + return emitTypePredicate(node); + case 155 /* TypeReference */: + return emitTypeReference(node); + case 156 /* FunctionType */: + return emitFunctionType(node); + case 157 /* ConstructorType */: + return emitConstructorType(node); + case 158 /* TypeQuery */: + return emitTypeQuery(node); + case 159 /* TypeLiteral */: + return emitTypeLiteral(node); + case 160 /* ArrayType */: + return emitArrayType(node); + case 161 /* TupleType */: + return emitTupleType(node); + case 162 /* UnionType */: + return emitUnionType(node); + case 163 /* IntersectionType */: + return emitIntersectionType(node); + case 164 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 194 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 165 /* ThisType */: + return emitThisType(node); + case 166 /* LiteralType */: + return emitLiteralType(node); + // Binding patterns + case 167 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 168 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 169 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 197 /* TemplateSpan */: + return emitTemplateSpan(node); + case 198 /* SemicolonClassElement */: + return emitSemicolonClassElement(node); + // Statements + case 199 /* Block */: + return emitBlock(node); + case 200 /* VariableStatement */: + return emitVariableStatement(node); + case 201 /* EmptyStatement */: + return emitEmptyStatement(node); + case 202 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 203 /* IfStatement */: + return emitIfStatement(node); + case 204 /* DoStatement */: + return emitDoStatement(node); + case 205 /* WhileStatement */: + return emitWhileStatement(node); + case 206 /* ForStatement */: + return emitForStatement(node); + case 207 /* ForInStatement */: + return emitForInStatement(node); + case 208 /* ForOfStatement */: + return emitForOfStatement(node); + case 209 /* ContinueStatement */: + return emitContinueStatement(node); + case 210 /* BreakStatement */: + return emitBreakStatement(node); + case 211 /* ReturnStatement */: + return emitReturnStatement(node); + case 212 /* WithStatement */: + return emitWithStatement(node); + case 213 /* SwitchStatement */: + return emitSwitchStatement(node); + case 214 /* LabeledStatement */: + return emitLabeledStatement(node); + case 215 /* ThrowStatement */: + return emitThrowStatement(node); + case 216 /* TryStatement */: + return emitTryStatement(node); + case 217 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 218 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 219 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 220 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 221 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 222 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 223 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 224 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 225 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 226 /* ModuleBlock */: + return emitModuleBlock(node); + case 227 /* CaseBlock */: + return emitCaseBlock(node); + case 229 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 230 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 231 /* ImportClause */: + return emitImportClause(node); + case 232 /* NamespaceImport */: + return emitNamespaceImport(node); + case 233 /* NamedImports */: + return emitNamedImports(node); + case 234 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 235 /* ExportAssignment */: + return emitExportAssignment(node); + case 236 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 237 /* NamedExports */: + return emitNamedExports(node); + case 238 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 239 /* MissingDeclaration */: + return; + // Module references + case 240 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 244 /* JsxText */: + return emitJsxText(node); + case 243 /* JsxOpeningElement */: + return emitJsxOpeningElement(node); + case 245 /* JsxClosingElement */: + return emitJsxClosingElement(node); + case 246 /* JsxAttribute */: + return emitJsxAttribute(node); + case 247 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 248 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 249 /* CaseClause */: + return emitCaseClause(node); + case 250 /* DefaultClause */: + return emitDefaultClause(node); + case 251 /* HeritageClause */: + return emitHeritageClause(node); + case 252 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 253 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 254 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + // Enum + case 255 /* EnumMember */: + return emitEnumMember(node); + // Top-level nodes + case 256 /* SourceFile */: + return emitSourceFile(node); + } + if (ts.isExpression(node)) { + return emitExpressionWorker(node); + } + } + function emitExpressionWorker(node) { + if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { + return; + } + var kind = node.kind; + switch (kind) { + // Literals + case 8 /* NumericLiteral */: + return emitNumericLiteral(node); + case 9 /* StringLiteral */: + case 10 /* RegularExpressionLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 84 /* FalseKeyword */: + case 93 /* NullKeyword */: + case 95 /* SuperKeyword */: + case 99 /* TrueKeyword */: + case 97 /* ThisKeyword */: + return writeTokenNode(node); + // Expressions + case 170 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 171 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 172 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 174 /* CallExpression */: + return emitCallExpression(node); + case 175 /* NewExpression */: + return emitNewExpression(node); + case 176 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 177 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 178 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 179 /* FunctionExpression */: + return emitFunctionExpression(node); + case 180 /* ArrowFunction */: + return emitArrowFunction(node); + case 181 /* DeleteExpression */: + return emitDeleteExpression(node); + case 182 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 183 /* VoidExpression */: + return emitVoidExpression(node); + case 184 /* AwaitExpression */: + return emitAwaitExpression(node); + case 185 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 186 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 187 /* BinaryExpression */: + return emitBinaryExpression(node); + case 188 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 189 /* TemplateExpression */: + return emitTemplateExpression(node); + case 190 /* YieldExpression */: + return emitYieldExpression(node); + case 191 /* SpreadElementExpression */: + return emitSpreadElementExpression(node); + case 192 /* ClassExpression */: + return emitClassExpression(node); + case 193 /* OmittedExpression */: + return; + case 195 /* AsExpression */: + return emitAsExpression(node); + case 196 /* NonNullExpression */: + return emitNonNullExpression(node); + // JSX + case 241 /* JsxElement */: + return emitJsxElement(node); + case 242 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + // Transformation nodes + case 288 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + } + } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral + function emitNumericLiteral(node) { + emitLiteral(node); + if (node.trailingComment) { + write(" /*" + node.trailingComment + "*/"); + } + } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node) { + var text = getLiteralTextOfNode(node); + if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) + && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else { + write(text); + } + } + // + // Identifiers + // + function emitIdentifier(node) { + if (node.emitFlags & 16 /* UMDDefine */) { + writeLines(umdHelper); + } + else { + write(getTextOfNode(node, /*includeTrivia*/ false)); + } + } + // + // Names + // + function emitQualifiedName(node) { + emitEntityName(node.left); + write("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 69 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitComputedPropertyName(node) { + write("["); + emitExpression(node.expression); + write("]"); + } + // + // Signature elements + // + function emitTypeParameter(node) { + emit(node.name); + emitWithPrefix(" extends ", node.constraint); + } + function emitParameter(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitExpressionWithPrefix(" = ", node.initializer); + emitWithPrefix(": ", node.type); + } + function emitDecorator(decorator) { + write("@"); + emitExpression(decorator.expression); + } + // + // Type members + // + function emitPropertySignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitPropertyDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emitWithPrefix(": ", node.type); + emitExpressionWithPrefix(" = ", node.initializer); + write(";"); + } + function emitMethodSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitMethodDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.asteriskToken, "*"); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitConstructor(node) { + emitModifiers(node, node.modifiers); + write("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.kind === 149 /* GetAccessor */ ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitConstructSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitIndexSignature(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + function emitSemicolonClassElement(node) { + write(";"); + } + // + // Types + // + function emitTypePredicate(node) { + emit(node.parameterName); + write(" is "); + emit(node.type); + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitConstructorType(node) { + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + function emitTypeQuery(node) { + write("typeof "); + emit(node.exprName); + } + function emitTypeLiteral(node) { + write("{"); + emitList(node, node.members, 65 /* TypeLiteralMembers */); + write("}"); + } + function emitArrayType(node) { + emit(node.elementType); + write("[]"); + } + function emitTupleType(node) { + write("["); + emitList(node, node.elementTypes, 336 /* TupleTypeElements */); + write("]"); + } + function emitUnionType(node) { + emitList(node, node.types, 260 /* UnionTypeConstituents */); + } + function emitIntersectionType(node) { + emitList(node, node.types, 264 /* IntersectionTypeConstituents */); + } + function emitParenthesizedType(node) { + write("("); + emit(node.type); + write(")"); + } + function emitThisType(node) { + write("this"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + // + // Binding patterns + // + function emitObjectBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("{}"); + } + else { + write("{"); + emitList(node, elements, 432 /* ObjectBindingPatternElements */); + write("}"); + } + } + function emitArrayBindingPattern(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + write("["); + emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); + write("]"); + } + } + function emitBindingElement(node) { + emitWithSuffix(node.propertyName, ": "); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + // + // Expressions + // + function emitArrayLiteralExpression(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); + } + } + function emitObjectLiteralExpression(node) { + var properties = node.properties; + if (properties.length === 0) { + write("{}"); + } + else { + var indentedFlag = node.emitFlags & 524288 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, properties, 978 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + } + } + function emitPropertyAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + var indentBeforeDot = false; + var indentAfterDot = false; + if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + var dotRangeStart = node.expression.end; + var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot); + write(shouldEmitDotDot ? ".." : "."); + increaseIndentIf(indentAfterDot); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression) { + if (expression.kind === 8 /* NumericLiteral */) { + // check if numeric literal was originally written with a dot + var text = getLiteralTextOfNode(expression); + return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; + } + else { + // check if constant enum value is integer + var constantValue = tryGetConstEnumValue(expression); + // isFinite handles cases when constantValue is undefined + return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + function emitElementAccessExpression(node) { + if (tryEmitConstantValue(node)) { + return; + } + emitExpression(node.expression); + write("["); + emitExpression(node.argumentExpression); + write("]"); + } + function emitCallExpression(node) { + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); + } + function emitNewExpression(node) { + write("new "); + emitExpression(node.expression); + emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); + } + function emitTaggedTemplateExpression(node) { + emitExpression(node.tag); + write(" "); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + if (node.type) { + write("<"); + emit(node.type); + write(">"); + } + emitExpression(node.expression); + } + function emitParenthesizedExpression(node) { + write("("); + emitExpression(node.expression); + write(")"); + } + function emitFunctionExpression(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitWithPrefix(": ", node.type); + write(" =>"); + } + function emitDeleteExpression(node) { + write("delete "); + emitExpression(node.expression); + } + function emitTypeOfExpression(node) { + write("typeof "); + emitExpression(node.expression); + } + function emitVoidExpression(node) { + write("void "); + emitExpression(node.expression); + } + function emitAwaitExpression(node) { + write("await "); + emitExpression(node.expression); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + write(" "); + } + emitExpression(node.operand); + } + function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + var operand = node.operand; + return operand.kind === 185 /* PrefixUnaryExpression */ + && ((node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) + || (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */))); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand); + writeTokenText(node.operator); + } + function emitBinaryExpression(node) { + var isCommaOperator = node.operatorToken.kind !== 24 /* CommaToken */; + var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + writeTokenText(node.operatorToken.kind); + increaseIndentIf(indentAfterOperator, " "); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + function emitConditionalExpression(node) { + var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, " "); + write("?"); + increaseIndentIf(indentAfterQuestion, " "); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + increaseIndentIf(indentBeforeColon, " "); + write(":"); + increaseIndentIf(indentAfterColon, " "); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + write(node.asteriskToken ? "yield*" : "yield"); + emitExpressionWithPrefix(" ", node.expression); + } + function emitSpreadElementExpression(node) { + write("..."); + emitExpression(node.expression); + } + function emitClassExpression(node) { + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression(node.expression); + if (node.type) { + write(" as "); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression); + write("!"); + } + // + // Misc + // + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + // + // Statements + // + function emitBlock(node, format) { + if (isSingleLineEmptyBlock(node)) { + writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + write(" "); + writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + } + else { + writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + emitBlockStatements(node); + writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + } + } + function emitBlockStatements(node) { + if (node.emitFlags & 32 /* SingleLine */) { + emitList(node, node.statements, 384 /* SingleLineBlockStatements */); + } + else { + emitList(node, node.statements, 65 /* MultiLineBlockStatements */); + } + } + function emitVariableStatement(node) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + write(";"); + } + function emitEmptyStatement(node) { + write(";"); + } + function emitExpressionStatement(node) { + emitExpression(node.expression); + write(";"); + } + function emitIfStatement(node) { + var openParenPos = writeToken(88 /* IfKeyword */, node.pos, node); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos, node); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end, node); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + writeToken(80 /* ElseKeyword */, node.thenStatement.end, node); + if (node.elseStatement.kind === 203 /* IfStatement */) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (ts.isBlock(node.statement)) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emitExpression(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + emitForBinding(node.initializer); + write(";"); + emitExpressionWithPrefix(" ", node.condition); + write(";"); + emitExpressionWithPrefix(" ", node.incrementor); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emitForBinding(node.initializer); + write(" in "); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForOfStatement(node) { + var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emitForBinding(node.initializer); + write(" of "); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitForBinding(node) { + if (node !== undefined) { + if (node.kind === 219 /* VariableDeclarationList */) { + emit(node); + } + else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + writeToken(75 /* ContinueKeyword */, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitBreakStatement(node) { + writeToken(70 /* BreakKeyword */, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + writeToken(94 /* ReturnKeyword */, node.pos, /*contextNode*/ node); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitWithStatement(node) { + write("with ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var openParenPos = writeToken(96 /* SwitchKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emitExpression(node.expression); + writeToken(18 /* CloseParenToken */, node.expression.end); + write(" "); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function emitThrowStatement(node) { + write("throw"); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(76 /* DebuggerKeyword */, node.pos); + write(";"); + } + // + // Declarations + // + function emitVariableDeclaration(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + function emitVariableDeclarationList(node) { + write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + emitList(node, node.declarations, 272 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.asteriskToken ? "function* " : "function "); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitSignatureAndBody(node, emitSignatureHead) { + var body = node.body; + if (body) { + if (ts.isBlock(body)) { + var indentedFlag = node.emitFlags & 524288 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + tempFlags = savedTempFlags; + } + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + write(" "); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + write(";"); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (body.emitFlags & 32 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + return false; + } + var previousStatement; + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(parentNode, body) { + write(" {"); + increaseIndent(); + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker); + decreaseIndent(); + writeToken(16 /* CloseBraceToken */, body.statements.end, body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var helpersEmitted = emitHelpers(body); + if (statementOffset === 0 && !helpersEmitted && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } + else { + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("class"); + emitNodeWithPrefix(" ", node.name, emitIdentifierName); + var indentedFlag = node.emitFlags & 524288 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 65 /* ClassMembers */); + write("}"); + if (indentedFlag) { + decreaseIndent(); + } + tempFlags = savedTempFlags; + } + function emitInterfaceDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("interface "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 256 /* HeritageClauses */); + write(" {"); + emitList(node, node.members, 65 /* InterfaceMembers */); + write("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("type "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + write(" = "); + emit(node.type); + write(";"); + } + function emitEnumDeclaration(node) { + emitModifiers(node, node.modifiers); + write("enum "); + emit(node.name); + var savedTempFlags = tempFlags; + tempFlags = 0; + write(" {"); + emitList(node, node.members, 81 /* EnumMembers */); + write("}"); + tempFlags = savedTempFlags; + } + function emitModuleDeclaration(node) { + emitModifiers(node, node.modifiers); + write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + emit(node.name); + var body = node.body; + while (body.kind === 225 /* ModuleDeclaration */) { + write("."); + emit(body.name); + body = body.body; + } + write(" "); + emit(body); + } + function emitModuleBlock(node) { + if (isSingleLineEmptyBlock(node)) { + write("{ }"); + } + else { + var savedTempFlags = tempFlags; + tempFlags = 0; + write("{"); + increaseIndent(); + emitBlockStatements(node); + write("}"); + tempFlags = savedTempFlags; + } + } + function emitCaseBlock(node) { + writeToken(15 /* OpenBraceToken */, node.pos); + emitList(node, node.clauses, 65 /* CaseBlockClauses */); + writeToken(16 /* CloseBraceToken */, node.clauses.end); + } + function emitImportEqualsDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + emit(node.name); + write(" = "); + emitModuleReference(node.moduleReference); + write(";"); + } + function emitModuleReference(node) { + if (node.kind === 69 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitModifiers(node, node.modifiers); + write("import "); + if (node.importClause) { + emit(node.importClause); + write(" from "); + } + emitExpression(node.moduleSpecifier); + write(";"); + } + function emitImportClause(node) { + emit(node.name); + if (node.name && node.namedBindings) { + write(", "); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + write("* as "); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + write(node.isExportEquals ? "export = " : "export default "); + emitExpression(node.expression); + write(";"); + } + function emitExportDeclaration(node) { + write("export "); + if (node.exportClause) { + emit(node.exportClause); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + emitExpression(node.moduleSpecifier); + } + write(";"); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + write("{"); + emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); + write("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + emit(node.propertyName); + write(" as "); + } + emit(node.name); + } + // + // Module references + // + function emitExternalModuleReference(node) { + write("require("); + emitExpression(node.expression); + write(")"); + } + // + // JSX + // + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 131072 /* JsxElementChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + write("<"); + emitJsxTagName(node.tagName); + write(" "); + emitList(node, node.attributes, 131328 /* JsxElementAttributes */); + write("/>"); + } + function emitJsxOpeningElement(node) { + write("<"); + emitJsxTagName(node.tagName); + writeIfAny(node.attributes, " "); + emitList(node, node.attributes, 131328 /* JsxElementAttributes */); + write(">"); + } + function emitJsxText(node) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + function emitJsxClosingElement(node) { + write(""); + } + function emitJsxAttribute(node) { + emit(node.name); + emitWithPrefix("=", node.initializer); + } + function emitJsxSpreadAttribute(node) { + write("{..."); + emitExpression(node.expression); + write("}"); + } + function emitJsxExpression(node) { + if (node.expression) { + write("{"); + emitExpression(node.expression); + write("}"); + } + } + function emitJsxTagName(node) { + if (node.kind === 69 /* Identifier */) { + emitExpression(node); + } + else { + emit(node); + } + } + // + // Clauses + // + function emitCaseClause(node) { + write("case "); + emitExpression(node.expression); + write(":"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitDefaultClause(node) { + write("default:"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + function emitCaseOrDefaultClauseStatements(parentNode, statements) { + var emitAsSingleStatement = statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || + ts.nodeIsSynthesized(statements[0]) || + ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (emitAsSingleStatement) { + write(" "); + emit(statements[0]); + } + else { + emitList(parentNode, statements, 81985 /* CaseOrDefaultClauseStatements */); + } + } + function emitHeritageClause(node) { + write(" "); + writeTokenText(node.token); + write(" "); + emitList(node, node.types, 272 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + writeLine(); + var openParenPos = writeToken(72 /* CatchKeyword */, node.pos); + write(" "); + writeToken(17 /* OpenParenToken */, openParenPos); + emit(node.variableDeclaration); + writeToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + write(" "); + emit(node.block); + } + // + // Property assignments + // + function emitPropertyAssignment(node) { + emit(node.name); + write(": "); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + var initializer = node.initializer; + if (!shouldSkipLeadingCommentsForNode(initializer)) { + var commentRange = initializer.commentRange || initializer; + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + write(" = "); + emitExpression(node.objectAssignmentInitializer); + } + } + // + // Enum + // + function emitEnumMember(node) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + // + // Top-level nodes + // + function emitSourceFile(node) { + writeLine(); + emitShebang(); + emitBodyWithDetachedComments(node, node.statements, emitSourceFileWorker); + } + function emitSourceFileWorker(node) { + var statements = node.statements; + var statementOffset = emitPrologueDirectives(statements); + var savedTempFlags = tempFlags; + tempFlags = 0; + emitHelpers(node); + emitList(node, statements, 1 /* MultiLine */, statementOffset); + tempFlags = savedTempFlags; + } + // Transformation nodes + function emitPartiallyEmittedExpression(node) { + emitExpression(node.expression); + } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements, startWithNewLine) { + for (var i = 0; i < statements.length; i++) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function emitHelpers(node) { + var emitFlags = node.emitFlags; + var helpersEmitted = false; + if (emitFlags & 1 /* EmitEmitHelpers */) { + helpersEmitted = emitEmitHelpers(currentSourceFile); + } + if (emitFlags & 2 /* EmitExportStar */) { + writeLines(exportStarHelper); + helpersEmitted = true; + } + if (emitFlags & 4 /* EmitSuperHelper */) { + writeLines(superHelper); + helpersEmitted = true; + } + if (emitFlags & 8 /* EmitAdvancedSuperHelper */) { + writeLines(advancedSuperHelper); + helpersEmitted = true; + } + return helpersEmitted; + } + function emitEmitHelpers(node) { + // Only emit helpers if the user did not say otherwise. + if (compilerOptions.noEmitHelpers) { + return false; + } + // Don't emit helpers if we can import them. + if (compilerOptions.importHelpers + && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + return false; + } + var helpersEmitted = false; + // Only Emit __extends function when target ES5. + // For target ES6 and above, we can emit classDeclaration as is. + if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && node.flags & 1024 /* HasClassExtends */)) { + writeLines(extendsHelper); + extendsEmitted = true; + helpersEmitted = true; + } + if (compilerOptions.jsx !== 1 /* Preserve */ && !assignEmitted && (node.flags & 16384 /* HasJsxSpreadAttributes */)) { + writeLines(assignHelper); + assignEmitted = true; + } + if (!decorateEmitted && node.flags & 2048 /* HasDecorators */) { + writeLines(decorateHelper); + if (compilerOptions.emitDecoratorMetadata) { + writeLines(metadataHelper); + } + decorateEmitted = true; + helpersEmitted = true; + } + if (!paramEmitted && node.flags & 4096 /* HasParamDecorators */) { + writeLines(paramHelper); + paramEmitted = true; + helpersEmitted = true; + } + if (!awaiterEmitted && node.flags & 8192 /* HasAsyncFunctions */) { + writeLines(awaiterHelper); + if (languageVersion < 2 /* ES6 */) { + writeLines(generatorHelper); + } + awaiterEmitted = true; + helpersEmitted = true; + } + if (helpersEmitted) { + writeLine(); + } + return helpersEmitted; + } + function writeLines(text) { + var lines = text.split(/\r\n|\r|\n/g); + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line.length) { + if (i > 0) { + writeLine(); + } + write(line); + } + } + } + // + // Helpers + // + function emitShebang() { + var shebang = ts.getShebang(currentText); + if (shebang) { + write(shebang); + writeLine(); + } + } + function emitModifiers(node, modifiers) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, 256 /* Modifiers */); + write(" "); + } + } + function emitWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emit); + } + function emitExpressionWithPrefix(prefix, node) { + emitNodeWithPrefix(prefix, node, emitExpression); + } + function emitNodeWithPrefix(prefix, node, emit) { + if (node) { + write(prefix); + emit(node); + } + } + function emitWithSuffix(node, suffix) { + if (node) { + emit(node); + write(suffix); + } + } + function tryEmitSubstitute(node, emitNode, isExpression) { + if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { + var substitute = onSubstituteNode(node, isExpression); + if (substitute !== node) { + substitute.emitFlags |= 128 /* NoSubstitution */; + emitNode(substitute); + return true; + } + } + return false; + } + function tryEmitConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + write(String(constantValue)); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : getTextOfNode(node.argumentExpression); + write(" /* " + propertyName + " */"); + } + return true; + } + return false; + } + function emitEmbeddedStatement(node) { + if (ts.isBlock(node)) { + write(" "); + emit(node); + } + else { + writeLine(); + increaseIndent(); + emit(node); + decreaseIndent(); + } + } + function emitDecorators(parentNode, decorators) { + emitList(parentNode, decorators, 24577 /* Decorators */); + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + } + function emitTypeParameters(parentNode, typeParameters) { + emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 1360 /* Parameters */); + } + function emitParametersForArrow(parentNode, parameters) { + if (parameters && + parameters.length === 1 && + parameters[0].type === undefined && + parameters[0].pos === parentNode.pos) { + emit(parameters[0]); + } + else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); + } + function emitList(parentNode, children, format, start, count) { + emitNodeList(emit, parentNode, children, format, start, count); + } + function emitExpressionList(parentNode, children, format, start, count) { + emitNodeList(emitExpression, parentNode, children, format, start, count); + } + function emitNodeList(emit, parentNode, children, format, start, count) { + if (start === void 0) { start = 0; } + if (count === void 0) { count = children ? children.length - start : 0; } + var isUndefined = children === undefined; + if (isUndefined && format & 8192 /* OptionalIfUndefined */) { + return; + } + var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + return; + } + if (format & 7680 /* BracketsMask */) { + write(getOpeningBracket(format)); + } + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { + writeLine(); + } + else if (format & 128 /* SpaceBetweenBraces */) { + write(" "); + } + } + else { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & 128 /* SpaceBetweenBraces */) { + write(" "); + } + // Increase the indent, if requested. + if (format & 64 /* Indented */) { + increaseIndent(); + } + // Emit each child. + var previousSibling = void 0; + var shouldDecreaseIndentAfterEmit = void 0; + var delimiter = getDelimiter(format); + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (previousSibling) { + write(delimiter); + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { + write(" "); + } + } + if (shouldEmitInterveningComments) { + var commentRange = child.commentRange || child; + emitTrailingCommentsOfPosition(commentRange.pos); + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + // Emit this child. + emit(child); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { + write(","); + } + // Decrease the indent, if requested. + if (format & 64 /* Indented */) { + decreaseIndent(); + } + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & 128 /* SpaceBetweenBraces */) { + write(" "); + } + } + if (format & 7680 /* BracketsMask */) { + write(getClosingBracket(format)); + } + } + function writeIfAny(nodes, text) { + if (nodes && nodes.length > 0) { + write(text); + } + } + function writeIfPresent(node, text) { + if (node !== undefined) { + write(text); + } + } + function writeToken(token, pos, contextNode) { + var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); + var tokenEndPos = writeTokenText(token, tokenStartPos); + return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); + } + function shouldSkipLeadingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; + } + function shouldSkipTrailingSourceMapForToken(contextNode) { + return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + } + function writeTokenText(token, pos) { + var tokenString = ts.tokenToString(token); + write(tokenString); + return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; + } + function writeTokenNode(node) { + if (node) { + emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + writeTokenText(node.kind); + emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + function increaseIndentIf(value, valueToWriteWhenNotIndenting) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (valueToWriteWhenNotIndenting) { + write(valueToWriteWhenNotIndenting); + } + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function shouldWriteLeadingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return true; + } + if (format & 2 /* PreserveLines */) { + if (format & 32768 /* PreferNewLine */) { + return true; + } + var firstChild = children[0]; + if (firstChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { + if (format & 1 /* MultiLine */) { + return true; + } + else if (format & 2 /* PreserveLines */) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return nextNode.startsOnNewLine; + } + } + function shouldWriteClosingLineTerminator(parentNode, children, format) { + if (format & 1 /* MultiLine */) { + return (format & 65536 /* NoTrailingNewLine */) === 0; + } + else if (format & 2 /* PreserveLines */) { + if (format & 32768 /* PreferNewLine */) { + return true; + } + var lastChild = ts.lastOrUndefined(children); + if (lastChild === undefined) { + return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (ts.nodeIsSynthesized(node)) { + var startsOnNewLine = node.startsOnNewLine; + if (startsOnNewLine === undefined) { + return (format & 32768 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 32768 /* PreferNewLine */) !== 0; + } + function needsIndentation(parent, node1, node2) { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + // Always use a newline for synthesized code if the synthesizer desires it. + if (node2.startsOnNewLine) { + return true; + } + return !ts.nodeIsSynthesized(parent) + && !ts.nodeIsSynthesized(node1) + && !ts.nodeIsSynthesized(node2) + && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 178 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode(node, includeTrivia) { + if (ts.isGeneratedIdentifier(node)) { + return getGeneratedIdentifier(node); + } + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return ts.unescapeIdentifier(node.text); + } + else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + return getTextOfNode(node.textSourceNode, includeTrivia); + } + else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node) { + if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { + var textSourceNode = node.textSourceNode; + if (ts.isIdentifier(textSourceNode)) { + return "\"" + ts.escapeNonAsciiCharacters(ts.escapeString(getTextOfNode(textSourceNode))) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode); + } + } + return ts.getLiteralText(node, currentSourceFile, languageVersion); + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } + function isSingleLineEmptyBlock(block) { + return !block.multiLine + && block.statements.length === 0 + && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + function isUniqueName(name) { + return !resolver.hasGlobalName(name) && + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); + } + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals && ts.hasProperty(node.locals, name)) { + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { + return false; + } + } + } + return true; + } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ + function makeTempVariableName(flags) { + if (flags && !(tempFlags & flags)) { + var name_41 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_41)) { + tempFlags |= flags; + return name_41; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name_42 = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) + : "_" + (count - 26); + if (isUniqueName(name_42)) { + return name_42; + } + } + } + } + // Generate a name that is unique within the current file and doesn't conflict with any names + // in global scope. The name is formed by adding an '_n' suffix to the specified base name, + // where n is a positive integer. Note that names generated by makeTempVariableName and + // makeUniqueName are guaranteed to never conflict. + function makeUniqueName(baseName) { + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (isUniqueName(generatedName)) { + return generatedNameSet[generatedName] = generatedName; + } + i++; + } + } + function generateNameForModuleOrEnum(node) { + var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); + var baseName = expr.kind === 9 /* StringLiteral */ ? + ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + return makeUniqueName(baseName); + } + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + /** + * Generates a unique name from a node. + * + * @param node A node. + */ + function generateNameForNode(node) { + switch (node.kind) { + case 69 /* Identifier */: + return makeUniqueName(getTextOfNode(node)); + case 225 /* ModuleDeclaration */: + case 224 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 230 /* ImportDeclaration */: + case 236 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 220 /* FunctionDeclaration */: + case 221 /* ClassDeclaration */: + case 235 /* ExportAssignment */: + return generateNameForExportDefault(); + case 192 /* ClassExpression */: + return generateNameForClassExpression(); + default: + return makeTempVariableName(0 /* Auto */); + } + } + /** + * Generates a unique identifier for a node. + * + * @param name A generated name. + */ + function generateName(name) { + switch (name.autoGenerateKind) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */); + case 3 /* Unique */: + return makeUniqueName(name.text); + } + ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + } + /** + * Gets the node from which a name should be generated. + * + * @param name A generated name wrapper. + */ + function getNodeForGeneratedName(name) { + var autoGenerateId = name.autoGenerateId; + var node = name; + var original = node.original; + while (original) { + node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. + if (ts.isIdentifier(node) + && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateId !== autoGenerateId) { + break; + } + original = node.original; + } + // otherwise, return the original node for the source; + return node; + } + /** + * Gets the generated identifier text from a generated identifier. + * + * @param name The generated identifier. + */ + function getGeneratedIdentifier(name) { + if (name.autoGenerateKind === 4 /* Node */) { + // Generated names generate unique names based on their original node + // and are cached based on that node's id + var node = getNodeForGeneratedName(name); + var nodeId = ts.getNodeId(node); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + } + else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. + var autoGenerateId = name.autoGenerateId; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(generateName(name))); + } + } + function createDelimiterMap() { + var delimiters = []; + delimiters[0 /* None */] = ""; + delimiters[16 /* CommaDelimited */] = ","; + delimiters[4 /* BarDelimited */] = " |"; + delimiters[8 /* AmpersandDelimited */] = " &"; + return delimiters; + } + function getDelimiter(format) { + return delimiters[format & 28 /* DelimitersMask */]; + } + function createBracketsMap() { + var brackets = []; + brackets[512 /* Braces */] = ["{", "}"]; + brackets[1024 /* Parenthesis */] = ["(", ")"]; + brackets[2048 /* AngleBrackets */] = ["<", ">"]; + brackets[4096 /* SquareBrackets */] = ["[", "]"]; + return brackets; + } + function getOpeningBracket(format) { + return brackets[format & 7680 /* BracketsMask */][0]; + } + function getClosingBracket(format) { + return brackets[format & 7680 /* BracketsMask */][1]; + } } ts.emitFiles = emitFiles; + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["TypeLiteralMembers"] = 65] = "TypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); /// /// /// var ts; (function (ts) { - /* @internal */ ts.programTime = 0; - /* @internal */ ts.emitTime = 0; - /* @internal */ ts.ioReadTime = 0; - /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - ts.version = "2.0.0"; + ts.version = "2.1.0"; var emptyArray = []; - var defaultTypeRoots = ["node_modules/@types"]; - function findConfigFile(searchPath, fileExists) { + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } while (true) { - var fileName = ts.combinePaths(searchPath, "tsconfig.json"); + var fileName = ts.combinePaths(searchPath, configName); if (fileExists(fileName)) { return fileName; } @@ -43025,54 +56905,29 @@ var ts; return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; } function moduleHasNonRelativeName(moduleName) { - if (ts.isRootedDiskPath(moduleName)) { - return false; - } - var i = moduleName.lastIndexOf("./", 1); - var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */); - return !startsWithDotSlashOrDotDotSlash; + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent; - try { - var jsonText = state.host.readFile(packageJsonPath); - jsonContent = jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - jsonContent = {}; - } - var typesFile; - var fieldName; - // first try to read content of 'typings' section (backward compatibility) - if (jsonContent.typings) { - if (typeof jsonContent.typings === "string") { - fieldName = "typings"; - typesFile = jsonContent.typings; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } } } } - // then read 'types' - if (!typesFile && jsonContent.types) { - if (typeof jsonContent.types === "string") { - fieldName = "types"; - typesFile = jsonContent.types; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); - } - } - } - if (typesFile) { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { return typesFilePath; } // Use the main module for inferring types if no types package specified and the allowJs is set @@ -43085,6 +56940,16 @@ var ts; } return undefined; } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -43097,11 +56962,32 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - if (!currentDirectory) { - return undefined; - } - return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); + return currentDirectory && getDefaultTypeRoots(currentDirectory, host); } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_15 = ts.getDirectoryPath(currentDirectory); + if (parent_15 === currentDirectory) { + break; + } + currentDirectory = parent_15; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -43381,7 +57267,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); @@ -43512,7 +57398,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } /* @internal */ @@ -43526,22 +57412,24 @@ var ts; * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First try to keep/add an extension: importing "./foo.ts" can be matched by a file "./foo.ts", and "./foo" by "./foo.d.ts" - var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingOrKeepingExtension) { - return resolvedByAddingOrKeepingExtension; + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; } - // Then try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one, e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" if (ts.hasJavaScriptFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); } } - function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); @@ -43549,29 +57437,28 @@ var ts; onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } - return ts.forEach(extensions, tryLoad); - function tryLoad(ext) { - if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { - return undefined; + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } - var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } + failedLookupLocation.push(fileName); + return undefined; } } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var packageJsonPath = pathToPackageJson(candidate); var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { @@ -43579,7 +57466,10 @@ var ts; } var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); if (typesFile) { - var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); if (result) { return result; } @@ -43599,6 +57489,9 @@ var ts; } return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); @@ -43674,15 +57567,8 @@ var ts; : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } ts.classicNameResolver = classicNameResolver; - /* @internal */ - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1 /* ES5 */, - noImplicitAny: false, - sourceMap: false - }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = {}; + var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. @@ -43693,9 +57579,10 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - var start = new Date().getTime(); + ts.performance.mark("beforeIORead"); text = ts.sys.readFile(fileName, options.charset); - ts.ioReadTime += new Date().getTime() - start; + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } catch (e) { if (onError) { @@ -43708,7 +57595,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (ts.hasProperty(existingDirectories, directoryPath)) { + if (directoryPath in existingDirectories) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -43727,11 +57614,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = {}; + outputFingerprints = ts.createMap(); } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { + if (mtimeBefore && fileName in outputFingerprints) { var fingerprint = outputFingerprints[fileName]; // If output has not been changed, and the file has no external modification if (fingerprint.byteOrderMark === writeByteOrderMark && @@ -43750,7 +57637,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - var start = new Date().getTime(); + ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -43758,7 +57645,8 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.ioWriteTime += new Date().getTime() - start; + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } catch (e) { if (onError) { @@ -43784,6 +57672,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -43797,6 +57686,22 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; + } + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -43825,33 +57730,25 @@ var ts; return []; } var resolutions = []; - var cache = {}; - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_34 = names_1[_i]; - var result = void 0; - if (ts.hasProperty(cache, name_34)) { - result = cache[name_34]; - } - else { - result = loader(name_34, containingFile); - cache[name_34] = result; - } + var cache = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_43 = names_2[_i]; + var result = name_43 in cache + ? cache[name_43] + : cache[name_43] = loader(name_43, containingFile); resolutions.push(result); } return resolutions; } - function getInferredTypesRoot(options, rootFiles, host) { - return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - } /** - * Given a set of options and a set of root files, returns the set of type directive names + * Given a set of options, returns the set of type directive names * that should be included for this program automatically. * This list could either come from the config file, * or from enumerating the types root + initial secondary types lookup location. * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options, rootFiles, host) { + function getAutomaticTypeDirectiveNames(options, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; @@ -43864,7 +57761,17 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - result = result.concat(host.getDirectories(root)); + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } } } } @@ -43879,7 +57786,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. // This works as imported modules are discovered recursively in a depth first manner, specifically: @@ -43888,14 +57795,14 @@ var ts; // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; - var currentNodeModulesJsDepth = 0; + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. - var modulesWithElidedImports = {}; - // Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled. - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -43926,10 +57833,10 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, host); if (typeReferences) { - var inferredRoot = getInferredTypesRoot(options, rootNames, host); - var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + // This containingFilename needs to match with the one used in managed-side + var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -43980,7 +57887,8 @@ var ts; getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.programTime += new Date().getTime() - start; + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -44004,10 +57912,10 @@ var ts; if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); - classifiableNames = {}; + classifiableNames = ts.createMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyMap(sourceFile.classifiableNames, classifiableNames); + ts.copyProperties(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -44032,7 +57940,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { + !ts.equalOwnProperties(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -44138,7 +58046,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, + isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -44150,8 +58058,7 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken) { - var _this = this; - return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); @@ -44187,9 +58094,10 @@ var ts; // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - var start = new Date().getTime(); + ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); - ts.emitTime += new Date().getTime() - start; + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; } function getSourceFile(fileName) { @@ -44341,16 +58249,16 @@ var ts; case 175 /* NewExpression */: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start_2 = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142 /* Parameter */: var parameter = node; if (parameter.modifiers) { - var start_3 = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -44394,8 +58302,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start_4 = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -44477,6 +58385,16 @@ var ts; var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + var externalHelpersModuleReference = ts.createNode(9 /* StringLiteral */); + externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; + externalHelpersModuleReference.parent = file; + imports = [externalHelpersModuleReference]; + } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); @@ -44507,7 +58425,7 @@ var ts; } break; case 225 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -44603,9 +58521,19 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - // See if we need to reprocess the imports due to prior skipped imports - if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { - if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { + sourceFilesFoundSearchingNodeModules[file_1.path] = false; + if (!options.noResolve) { + processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processTypeReferenceDirectives(file_1); + } + modulesWithElidedImports[file_1.path] = false; + processImportedModules(file_1, ts.getDirectoryPath(fileName)); + } + else if (file_1 && modulesWithElidedImports[file_1.path]) { + if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -44623,6 +58551,7 @@ var ts; }); filesByName.set(path, file); if (file) { + sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -44658,14 +58587,16 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; // store resolved type directive on the file - ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -44686,7 +58617,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } // don't overwrite previous resolution result saveResolution = false; @@ -44722,7 +58653,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = {}; + file.resolvedModules = ts.createMap(); var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -44737,12 +58668,9 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - sourceFilesFoundSearchingNodeModules[resolvedPath] = true; + currentNodeModulesDepth++; } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth++; - } - var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -44751,8 +58679,8 @@ var ts; findSourceFile(resolution.resolvedFileName, resolvedPath, /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isJsFileFromNodeModules) { - currentNodeModulesJsDepth--; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; } } } @@ -44764,8 +58692,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var file = sourceFiles_5[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -44776,8 +58704,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -44824,6 +58752,9 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { + if (options.paths[key].length === 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; @@ -44870,30 +58801,30 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -44915,7 +58846,7 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files @@ -44982,6 +58913,11 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean", + experimental: true + }, { name: "emitBOM", type: "boolean" @@ -45012,10 +58948,10 @@ var ts; }, { name: "jsx", - type: { + type: ts.createMap({ "preserve": 1 /* Preserve */, "react": 2 /* React */ - }, + }), paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -45042,7 +58978,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -45050,16 +58986,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }, + }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: { + type: ts.createMap({ "crlf": 0 /* CarriageReturnLineFeed */, "lf": 1 /* LineFeed */ - }, + }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -45077,6 +59013,10 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, + { + name: "noErrorTruncation", + type: "boolean" + }, { name: "noImplicitAny", type: "boolean", @@ -45090,12 +59030,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Locals + description: ts.Diagnostics.Report_errors_on_unused_locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_Errors_on_Unused_Parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters }, { name: "noLib", @@ -45201,12 +59141,12 @@ var ts; { name: "target", shortName: "t", - type: { + type: ts.createMap({ "es3": 0 /* ES3 */, "es5": 1 /* ES5 */, "es6": 2 /* ES6 */, "es2015": 2 /* ES2015 */ - }, + }), description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -45235,11 +59175,12 @@ var ts; }, { name: "moduleResolution", - type: { + type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }, - description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 + }), + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + paramType: ts.Diagnostics.STRATEGY }, { name: "allowUnusedLabels", @@ -45343,7 +59284,7 @@ var ts; type: "list", element: { name: "lib", - type: { + type: ts.createMap({ // JavaScript only "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", @@ -45353,6 +59294,7 @@ var ts; "es2017": "lib.es2017.d.ts", // Host only "dom": "lib.dom.d.ts", + "dom.iterable": "lib.dom.iterable.d.ts", "webworker": "lib.webworker.d.ts", "scripthost": "lib.scripthost.d.ts", // ES2015 Or ESNext By-feature options @@ -45368,7 +59310,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - } + }) }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -45380,6 +59322,11 @@ var ts; name: "strictNullChecks", type: "boolean", description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "importHelpers", + type: "boolean", + description: ts.Diagnostics.Import_emit_helpers_from_tslib } ]; /* @internal */ @@ -45405,14 +59352,21 @@ var ts; } } ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + noImplicitAny: false, + sourceMap: false + }; var optionNameMapCache; /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = {}; - var shortOptionNames = {}; + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -45426,9 +59380,9 @@ var ts; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - ts.forEachKey(opt.type, function (key) { + for (var key in opt.type) { namesOfType.push(" '" + key + "'"); - }); + } return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; @@ -45436,7 +59390,7 @@ var ts; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (ts.hasProperty(map, key)) { + if (key in map) { return map[key]; } else { @@ -45488,10 +59442,10 @@ var ts; else if (s.charCodeAt(0) === 45 /* minus */) { s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); // Try to translate short option names to their full equivalents. - if (ts.hasProperty(shortOptionNames, s)) { + if (s in shortOptionNames) { s = shortOptionNames[s]; } - if (ts.hasProperty(optionNameMap, s)) { + if (s in optionNameMap) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -45603,6 +59557,90 @@ var ts; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var configurations = { + compilerOptions: serializeCompilerOptions(compilerOptions) + }; + if (fileNames && fileNames.length) { + // only set the files property if we have at least one file + configurations.files = fileNames; + } + return configurations; + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + for (var key in customTypeMap) { + if (customTypeMap[key] === value) { + return key; + } + } + return undefined; + } + function serializeCompilerOptions(options) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name_44 in options) { + if (ts.hasProperty(options, name_44)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + switch (name_44) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_44]; + var optionDefinition = optionsNameMap[name_44.toLowerCase()]; + if (optionDefinition) { + var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + result[name_44] = value; + } + else { + if (optionDefinition.type === "list") { + var convertedValue = []; + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); + } + result[name_44] = convertedValue; + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result[name_44] = getNameOfCompilerOptionValue(value, customTypeMap); + } + } + } + break; + } + } + } + return result; + } + } + ts.generateTSConfig = generateTSConfig; /** * Remove the comments from a json like text. * Comments can be single line comments (starting with # or //) or multiline comments using / * * / @@ -45627,9 +59665,6 @@ var ts; } return output; } - // Skip over any minified JavaScript files (ending in ".min.js") - // Skip over dotted files and folders as well - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -45637,14 +59672,46 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } var errors = []; - var compilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var options = ts.extend(existingOptions, compilerOptions); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + return { + options: {}, + fileNames: [], + typingOptions: {}, + raw: json, + errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], + wildcardDirectories: {} + }; + } + var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + if (json["extends"]) { + var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; + if (typeof json["extends"] === "string") { + _b = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]), include = _b[0], exclude = _b[1], files = _b[2], baseOptions = _b[3]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + if (include && !json["include"]) { + json["include"] = include; + } + if (exclude && !json["exclude"]) { + json["exclude"] = exclude; + } + if (files && !json["files"]) { + json["files"] = files; + } + options = ts.assign({}, baseOptions, options); + } + options = ts.extend(existingOptions, options); options.configFilePath = configFileName; - var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; return { options: options, fileNames: fileNames, @@ -45653,6 +59720,38 @@ var ts; errors: errors, wildcardDirectories: wildcardDirectories }; + function tryExtendsName(extendedConfig) { + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + return; + } + var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return; + } + } + var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (extendedResult.error) { + errors.push(extendedResult.error); + return; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var relativeDifference = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference, path); }; + // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) + var result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, ts.getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); + errors.push.apply(errors, result.errors); + var _a = ts.map(["include", "exclude", "files"], function (key) { + if (!json[key] && extendedResult.config[key]) { + return ts.map(extendedResult.config[key], updatePath); + } + }), include = _a[0], exclude = _a[1], files = _a[2]; + return [include, exclude, files, result.options]; + } function getFileNames(errors) { var fileNames; if (ts.hasProperty(json, "files")) { @@ -45685,19 +59784,19 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - // By default, exclude common package folders + // By default, exclude common package folders and the outDir excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; - } - // Always exclude the output directory unless explicitly included - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - excludeSpecs.push(outDir); + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } + var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { @@ -45713,7 +59812,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -45730,7 +59829,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (ts.hasProperty(optionNameMap, id)) { + if (id in optionNameMap) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -45765,7 +59864,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (ts.hasProperty(opt.type, key)) { + if (key in opt.type) { return opt.type[key]; } else { @@ -45865,11 +59964,11 @@ var ts; // Literal file names (provided via the "files" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map later when when including // wildcard paths. - var literalFileMap = {}; + var literalFileMap = ts.createMap(); // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. - var wildcardFileMap = {}; + var wildcardFileMap = ts.createMap(); if (include) { include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); } @@ -45905,16 +60004,13 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } - if (ignoreFileNamePattern.test(file)) { - continue; - } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // "include" array. If there is a lower priority extension in the // same directory, we should remove it. removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + if (!(key in literalFileMap) && !(key in wildcardFileMap)) { wildcardFileMap[key] = file; } } @@ -45963,20 +60059,20 @@ var ts; // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = {}; + var wildcardDirectories = ts.createMap(); if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_35 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_35)) { + var name_45 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_45)) { continue; } - var match = wildcardDirectoryPattern.exec(name_35); + var match = wildcardDirectoryPattern.exec(name_45); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; - var existingFlags = ts.getProperty(wildcardDirectories, key); + var flags = watchRecursivePattern.test(name_45) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1 /* Recursive */) { @@ -45987,12 +60083,10 @@ var ts; } // Remove any subpaths under an existing recursively watched directory. for (var key in wildcardDirectories) { - if (ts.hasProperty(wildcardDirectories, key)) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; - } + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; } } } @@ -46013,7 +60107,7 @@ var ts; for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { return true; } } @@ -46063,193 +60157,6485 @@ var ts; return key.toLowerCase(); } })(ts || (ts = {})); +var ts; +(function (ts) { + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. + return undefined; + }; + return StringScriptSnapshot; + }()); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + var TextChange = (function () { + function TextChange() { + } + return TextChange; + }()); + ts.TextChange = TextChange; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind.none = "none"; + HighlightSpanKind.definition = "definition"; + HighlightSpanKind.reference = "reference"; + HighlightSpanKind.writtenReference = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(ts.IndentStyle || (ts.IndentStyle = {})); + var IndentStyle = ts.IndentStyle; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(ts.OutputFileType || (ts.OutputFileType = {})); + var OutputFileType = ts.OutputFileType; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["None"] = 0] = "None"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + })(ts.EndOfLineState || (ts.EndOfLineState = {})); + var EndOfLineState = ts.EndOfLineState; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + })(ts.TokenClass || (ts.TokenClass = {})); + var TokenClass = ts.TokenClass; + // TODO: move these to enums + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind.unknown = ""; + ScriptElementKind.warning = "warning"; + /** predefined type (void) or keyword (class) */ + ScriptElementKind.keyword = "keyword"; + /** top level script node */ + ScriptElementKind.scriptElement = "script"; + /** module foo {} */ + ScriptElementKind.moduleElement = "module"; + /** class X {} */ + ScriptElementKind.classElement = "class"; + /** var x = class X {} */ + ScriptElementKind.localClassElement = "local class"; + /** interface Y {} */ + ScriptElementKind.interfaceElement = "interface"; + /** type T = ... */ + ScriptElementKind.typeElement = "type"; + /** enum E */ + ScriptElementKind.enumElement = "enum"; + // TODO: GH#9983 + ScriptElementKind.enumMemberElement = "const"; + /** + * Inside module and script only + * const v = .. + */ + ScriptElementKind.variableElement = "var"; + /** Inside function */ + ScriptElementKind.localVariableElement = "local var"; + /** + * Inside module and script only + * function f() { } + */ + ScriptElementKind.functionElement = "function"; + /** Inside function */ + ScriptElementKind.localFunctionElement = "local function"; + /** class X { [public|private]* foo() {} } */ + ScriptElementKind.memberFunctionElement = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ + ScriptElementKind.memberGetAccessorElement = "getter"; + ScriptElementKind.memberSetAccessorElement = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + ScriptElementKind.memberVariableElement = "property"; + /** class X { constructor() { } } */ + ScriptElementKind.constructorImplementationElement = "constructor"; + /** interface Y { ():number; } */ + ScriptElementKind.callSignatureElement = "call"; + /** interface Y { []:number; } */ + ScriptElementKind.indexSignatureElement = "index"; + /** interface Y { new():Y; } */ + ScriptElementKind.constructSignatureElement = "construct"; + /** function foo(*Y*: string) */ + ScriptElementKind.parameterElement = "parameter"; + ScriptElementKind.typeParameterElement = "type parameter"; + ScriptElementKind.primitiveType = "primitive type"; + ScriptElementKind.label = "label"; + ScriptElementKind.alias = "alias"; + ScriptElementKind.constElement = "const"; + ScriptElementKind.letElement = "let"; + ScriptElementKind.directory = "directory"; + ScriptElementKind.externalModuleName = "external module name"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier.none = ""; + ScriptElementKindModifier.publicMemberModifier = "public"; + ScriptElementKindModifier.privateMemberModifier = "private"; + ScriptElementKindModifier.protectedMemberModifier = "protected"; + ScriptElementKindModifier.exportedModifier = "export"; + ScriptElementKindModifier.ambientModifier = "declare"; + ScriptElementKindModifier.staticModifier = "static"; + ScriptElementKindModifier.abstractModifier = "abstract"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames = (function () { + function ClassificationTypeNames() { + } + return ClassificationTypeNames; + }()); + ClassificationTypeNames.comment = "comment"; + ClassificationTypeNames.identifier = "identifier"; + ClassificationTypeNames.keyword = "keyword"; + ClassificationTypeNames.numericLiteral = "number"; + ClassificationTypeNames.operator = "operator"; + ClassificationTypeNames.stringLiteral = "string"; + ClassificationTypeNames.whiteSpace = "whitespace"; + ClassificationTypeNames.text = "text"; + ClassificationTypeNames.punctuation = "punctuation"; + ClassificationTypeNames.className = "class name"; + ClassificationTypeNames.enumName = "enum name"; + ClassificationTypeNames.interfaceName = "interface name"; + ClassificationTypeNames.moduleName = "module name"; + ClassificationTypeNames.typeParameterName = "type parameter name"; + ClassificationTypeNames.typeAliasName = "type alias name"; + ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; + ts.ClassificationTypeNames = ClassificationTypeNames; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + })(ts.ClassificationType || (ts.ClassificationType = {})); + var ClassificationType = ts.ClassificationType; +})(ts || (ts = {})); +// These utilities are common to multiple language service features. /* @internal */ var ts; (function (ts) { - var OutliningElementsCollector; - (function (OutliningElementsCollector) { - function collectElements(sourceFile) { - var elements = []; - var collapseText = "..."; - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { - if (hintSpanNode && startElement && endElement) { - var span = { - textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), - hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + ts.scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); + ts.emptyArray = []; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(ts.SemanticMeaning || (ts.SemanticMeaning = {})); + var SemanticMeaning = ts.SemanticMeaning; + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 142 /* Parameter */: + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 253 /* PropertyAssignment */: + case 254 /* ShorthandPropertyAssignment */: + case 255 /* EnumMember */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 252 /* CatchClause */: + return 1 /* Value */; + case 141 /* TypeParameter */: + case 222 /* InterfaceDeclaration */: + case 223 /* TypeAliasDeclaration */: + case 159 /* TypeLiteral */: + return 2 /* Type */; + case 221 /* ClassDeclaration */: + case 224 /* EnumDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 225 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { + return 4 /* Namespace */ | 1 /* Value */; } - } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse - }; - elements.push(span); + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; } + else { + return 4 /* Namespace */; + } + case 233 /* NamedImports */: + case 234 /* ImportSpecifier */: + case 229 /* ImportEqualsDeclaration */: + case 230 /* ImportDeclaration */: + case 235 /* ExportAssignment */: + case 236 /* ExportDeclaration */: + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + // An external module can be a Value + case 256 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + ts.getMeaningFromDeclaration = getMeaningFromDeclaration; + function getMeaningFromLocation(node) { + if (node.parent.kind === 235 /* ExportAssignment */) { + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + else if (isInRightSideOfImport(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2 /* Type */; + } + else if (isNamespaceReference(node)) { + return 4 /* Namespace */; + } + else { + return 1 /* Value */; + } + } + ts.getMeaningFromLocation = getMeaningFromLocation; + function getMeaningFromRightHandSideOfImportEquals(node) { + ts.Debug.assert(node.kind === 69 /* Identifier */); + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (node.parent.kind === 139 /* QualifiedName */ && + node.parent.right === node && + node.parent.parent.kind === 229 /* ImportEqualsDeclaration */) { + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + return 4 /* Namespace */; + } + function isInRightSideOfImport(node) { + while (node.parent.kind === 139 /* QualifiedName */) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 139 /* QualifiedName */) { + while (root.parent && root.parent.kind === 139 /* QualifiedName */) { + root = root.parent; } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var currentComment = comments_2[_i]; - // For single line comments, combine consecutive ones (2 or more) into - // a single span from the start of the first till the end of the last - if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; + isLastClause = root.right === node; + } + return root.parent.kind === 155 /* TypeReference */ && !isLastClause; + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 172 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 172 /* PropertyAccessExpression */) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 194 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 251 /* HeritageClause */) { + var decl = root.parent.parent.parent; + return (decl.kind === 221 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 222 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + } + return false; + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + return node.parent.kind === 155 /* TypeReference */ || + (node.parent.kind === 194 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || + node.kind === 165 /* ThisType */; + } + function isCallExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 174 /* CallExpression */); + } + ts.isCallExpressionTarget = isCallExpressionTarget; + function isNewExpressionTarget(node) { + return isCallOrNewExpressionTarget(node, 175 /* NewExpression */); + } + ts.isNewExpressionTarget = isNewExpressionTarget; + function isCallOrNewExpressionTarget(node, kind) { + var target = climbPastPropertyAccess(node); + return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + } + function climbPastPropertyAccess(node) { + return isRightSideOfPropertyAccess(node) ? node.parent : node; + } + ts.climbPastPropertyAccess = climbPastPropertyAccess; + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 214 /* LabeledStatement */ && referenceNode.label.text === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + ts.getTargetLabel = getTargetLabel; + function isJumpStatementTarget(node) { + return node.kind === 69 /* Identifier */ && + (node.parent.kind === 210 /* BreakStatement */ || node.parent.kind === 209 /* ContinueStatement */) && + node.parent.label === node; + } + ts.isJumpStatementTarget = isJumpStatementTarget; + function isLabelOfLabeledStatement(node) { + return node.kind === 69 /* Identifier */ && + node.parent.kind === 214 /* LabeledStatement */ && + node.parent.label === node; + } + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + ts.isLabelName = isLabelName; + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node; + } + ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node; + } + ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 225 /* ModuleDeclaration */ && node.parent.name === node; + } + ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; + function isNameOfFunctionDeclaration(node) { + return node.kind === 69 /* Identifier */ && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { + switch (node.parent.kind) { + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 253 /* PropertyAssignment */: + case 255 /* EnumMember */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 225 /* ModuleDeclaration */: + return node.parent.name === node; + case 173 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 140 /* ComputedPropertyName */: + return true; + } + } + return false; + } + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; + function isExpressionOfExternalModuleImportEqualsDeclaration(node) { + return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node; + } + ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; + /** Returns true if the position is within a comment */ + function isInsideComment(sourceFile, token, position) { + // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment + return position <= token.getStart(sourceFile) && + (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || + isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); + function isInsideCommentRange(comments) { + return ts.forEach(comments, function (comment) { + // either we are 1. completely inside the comment, or 2. at the end of the comment + if (comment.pos < position && position < comment.end) { + return true; + } + else if (position === comment.end) { + var text = sourceFile.text; + var width = comment.end - comment.pos; + // is single line comment or just /* + if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { + return true; + } + else { + // is unterminated multi-line comment + return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && + text.charCodeAt(comment.end - 2) === 42 /* asterisk */); + } + } + return false; + }); + } + } + ts.isInsideComment = isInsideComment; + function getContainerNode(node) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 256 /* SourceFile */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 224 /* EnumDeclaration */: + case 225 /* ModuleDeclaration */: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + function getNodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + case 225 /* ModuleDeclaration */: + return ts.ScriptElementKind.moduleElement; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + return ts.ScriptElementKind.classElement; + case 222 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; + case 223 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; + case 224 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; + case 218 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 169 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + return ts.ScriptElementKind.functionElement; + case 149 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; + case 150 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + return ts.ScriptElementKind.memberFunctionElement; + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + return ts.ScriptElementKind.memberVariableElement; + case 153 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; + case 152 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; + case 151 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; + case 148 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; + case 141 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; + case 255 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; + case 142 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportSpecifier */: + case 231 /* ImportClause */: + case 238 /* ExportSpecifier */: + case 232 /* NamespaceImport */: + return ts.ScriptElementKind.alias; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ts.ScriptElementKind.constElement + : ts.isLet(v) + ? ts.ScriptElementKind.letElement + : ts.ScriptElementKind.variableElement; + } + } + ts.getNodeKind = getNodeKind; + function getStringLiteralTypeForNode(node, typeChecker) { + var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; + var type = typeChecker.getTypeAtLocation(searchNode); + if (type && type.flags & 32 /* StringLiteral */) { + return type; + } + return undefined; + } + ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; + function isThis(node) { + switch (node.kind) { + case 97 /* ThisKeyword */: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case 69 /* Identifier */: + // 'this' as a parameter + return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + default: + return false; + } + } + ts.isThis = isThis; + // Matches the beginning of a triple slash directive + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + function positionBelongsToNode(candidate, position, sourceFile) { + return candidate.end > position || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 224 /* EnumDeclaration */: + case 171 /* ObjectLiteralExpression */: + case 167 /* ObjectBindingPattern */: + case 159 /* TypeLiteral */: + case 199 /* Block */: + case 226 /* ModuleBlock */: + case 227 /* CaseBlock */: + case 233 /* NamedImports */: + case 237 /* NamedExports */: + return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); + case 252 /* CatchClause */: + return isCompletedNode(n.block, sourceFile); + case 175 /* NewExpression */: + if (!n.arguments) { + return true; + } + // fall through + case 174 /* CallExpression */: + case 178 /* ParenthesizedExpression */: + case 164 /* ParenthesizedType */: + return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + case 156 /* FunctionType */: + case 157 /* ConstructorType */: + return isCompletedNode(n.type, sourceFile); + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 152 /* ConstructSignature */: + case 151 /* CallSignature */: + case 180 /* ArrowFunction */: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); + case 225 /* ModuleDeclaration */: + return n.body && isCompletedNode(n.body, sourceFile); + case 203 /* IfStatement */: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 202 /* ExpressionStatement */: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 23 /* SemicolonToken */); + case 170 /* ArrayLiteralExpression */: + case 168 /* ArrayBindingPattern */: + case 173 /* ElementAccessExpression */: + case 140 /* ComputedPropertyName */: + case 161 /* TupleType */: + return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); + case 153 /* IndexSignature */: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + case 249 /* CaseClause */: + case 250 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed + return false; + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + case 205 /* WhileStatement */: + return isCompletedNode(n.statement, sourceFile); + case 204 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); + if (hasWhileKeyword) { + return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + } + return isCompletedNode(n.statement, sourceFile); + case 158 /* TypeQuery */: + return isCompletedNode(n.exprName, sourceFile); + case 182 /* TypeOfExpression */: + case 181 /* DeleteExpression */: + case 183 /* VoidExpression */: + case 190 /* YieldExpression */: + case 191 /* SpreadElementExpression */: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 176 /* TaggedTemplateExpression */: + return isCompletedNode(n.template, sourceFile); + case 189 /* TemplateExpression */: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 197 /* TemplateSpan */: + return ts.nodeIsPresent(n.literal); + case 236 /* ExportDeclaration */: + case 230 /* ImportDeclaration */: + return ts.nodeIsPresent(n.moduleSpecifier); + case 185 /* PrefixUnaryExpression */: + return isCompletedNode(n.operand, sourceFile); + case 187 /* BinaryExpression */: + return isCompletedNode(n.right, sourceFile); + case 188 /* ConditionalExpression */: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + ts.isCompletedNode = isCompletedNode; + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var last = ts.lastOrUndefined(children); + if (last.kind === expectedLastToken) { + return true; + } + else if (last.kind === 23 /* SemicolonToken */ && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOf(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). + var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { + // find syntax list that covers the span of the node + if (c.kind === 286 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + return c; + } + }); + // Either we didn't find an appropriate list, or the list must contain us. + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + /* Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is keyword or identifier)) + */ + function getTouchingWord(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + } + ts.getTouchingWord = getTouchingWord; + /* Gets the token whose text has range [start, end) and position >= start + * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) + */ + function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ + function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); + } + ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile, position, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); + } + ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { + if (includeJsDocComment === void 0) { includeJsDocComment = false; } + var current = sourceFile; + outer: while (true) { + if (isToken(current)) { + // exit early + return current; + } + if (includeJsDocComment) { + var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); + for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { + var jsDocChild = jsDocChildren_1[_i]; + var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = jsDocChild.getEnd(); + if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { + current = jsDocChild; + continue outer; } - else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, /*autoCollapse*/ false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } } } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); } } - function combineAndAddMultipleSingleLineComments(count, start, end) { - // Only outline spans of two or more consecutive single line comments - if (count > 1) { - var multipleSingleLineComments = { - pos: start, - end: end, - kind: 2 /* SingleLineCommentTrivia */ - }; - addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); + // find the child that contains 'position' + for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { + var child = current.getChildAt(i); + // all jsDocComment nodes were already visited + if (ts.isJSDocNode(child)) { + continue; + } + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); + if (start <= position) { + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } + } } } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180 /* ArrowFunction */; + return current; + } + } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ + function findTokenOnLeftOfPosition(file, position) { + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position); + if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent) { + return find(parent); + function find(n) { + if (isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; } - var depth = 0; - var maxDepth = 20; - function walk(n) { - if (depth > maxDepth) { + var children = n.getChildren(); + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + (child.pos === previousToken.end); + if (shouldDiveInChildNode && nodeHasTokens(child)) { + return find(child); + } + } + return undefined; + } + } + ts.findNextToken = findNextToken; + function findPrecedingToken(position, sourceFile, startNode) { + return find(startNode || sourceFile); + function findRightmostToken(n) { + if (isToken(n) || n.kind === 244 /* JsxText */) { + return n; + } + var children = n.getChildren(); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + return candidate && findRightmostToken(candidate); + } + function find(n) { + if (isToken(n) || n.kind === 244 /* JsxText */) { + return n; + } + var children = n.getChildren(); + for (var i = 0, len = children.length; i < len; i++) { + var child = children[i]; + // condition 'position < child.end' checks if child node end after the position + // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' + // aaaa___bbbb___$__ccc + // after we found child node with end after the position we check if start of the node is after the position. + // if yes - then position is in the trivia and we need to look into the previous child to find the token in question. + // if no - position is in the node itself so we should recurse in it. + // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). + // if this is the case - then we should assume that token in question is located in previous child. + if (position < child.end && (nodeHasTokens(child) || child.kind === 244 /* JsxText */)) { + var start = child.getStart(sourceFile); + var lookInPreviousChild = (start >= position) || + (child.kind === 244 /* JsxText */ && start === child.end); // whitespace only JsxText + if (lookInPreviousChild) { + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + return candidate && findRightmostToken(candidate); + } + else { + // candidate should be in this node + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 256 /* SourceFile */); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' + if (children.length) { + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + return candidate && findRightmostToken(candidate); + } + } + /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { + if (nodeHasTokens(children[i])) { + return children[i]; + } + } + } + } + ts.findPrecedingToken = findPrecedingToken; + function isInString(sourceFile, position) { + var previousToken = findPrecedingToken(position, sourceFile); + if (previousToken && previousToken.kind === 9 /* StringLiteral */) { + var start = previousToken.getStart(); + var end = previousToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start < position && position < end) { + return true; + } + if (position === end) { + return !!previousToken.isUnterminated; + } + } + return false; + } + ts.isInString = isInString; + function isInComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); + } + ts.isInComment = isInComment; + /** + * returns true if the position is in between the open and close elements of an JSX expression. + */ + function isInsideJsxElementOrAttribute(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + if (!token) { + return false; + } + if (token.kind === 244 /* JsxText */) { + return true; + } + //
Hello |
+ if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { + return true; + } + //
{ |
or
+ if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { + return true; + } + //
{ + // | + // } < /div> + if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { + return true; + } + //
|
+ if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { + return true; + } + return false; + } + ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; + function isInTemplateString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); + } + ts.isInTemplateString = isInTemplateString; + /** + * Returns true if the cursor at position in sourceFile is within a comment that additionally + * satisfies predicate, and false otherwise. + */ + function isInCommentHelper(sourceFile, position, predicate) { + var token = getTokenAtPosition(sourceFile, position); + if (token && position <= token.getStart(sourceFile)) { + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + // The end marker of a single-line comment does not include the newline character. + // In the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + return predicate ? + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && + predicate(c); }) : + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + } + return false; + } + ts.isInCommentHelper = isInCommentHelper; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + // First, we have to see if this position actually landed in a comment. + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + return ts.forEach(commentRanges, jsDocPrefix); + function jsDocPrefix(c) { + var text = sourceFile.text; + return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; + } + } + ts.hasDocComment = hasDocComment; + /** + * Get the corresponding JSDocTag node if the position is in a jsDoc comment + */ + function getJsDocTagAtPosition(sourceFile, position) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (isToken(node)) { + switch (node.kind) { + case 102 /* VarKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + // if the current token is var, let or const, skip the VariableDeclarationList + node = node.parent === undefined ? undefined : node.parent.parent; + break; + default: + node = node.parent; + break; + } + } + if (node) { + if (node.jsDocComments) { + for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + if (jsDocComment.tags) { + for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.pos <= position && position <= tag.end) { + return tag; + } + } + } + } + } + } + return undefined; + } + ts.getJsDocTagAtPosition = getJsDocTagAtPosition; + function nodeHasTokens(n) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note, that getWidth() does not take trivia into account. + return n.getWidth() !== 0; + } + function getNodeModifiers(node) { + var flags = ts.getCombinedModifierFlags(node); + var result = []; + if (flags & 8 /* Private */) + result.push(ts.ScriptElementKindModifier.privateMemberModifier); + if (flags & 16 /* Protected */) + result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + if (flags & 4 /* Public */) + result.push(ts.ScriptElementKindModifier.publicMemberModifier); + if (flags & 32 /* Static */) + result.push(ts.ScriptElementKindModifier.staticModifier); + if (flags & 128 /* Abstract */) + result.push(ts.ScriptElementKindModifier.abstractModifier); + if (flags & 1 /* Export */) + result.push(ts.ScriptElementKindModifier.exportedModifier); + if (ts.isInAmbientContext(node)) + result.push(ts.ScriptElementKindModifier.ambientModifier); + return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 155 /* TypeReference */ || node.kind === 174 /* CallExpression */) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 221 /* ClassDeclaration */ || node.kind === 222 /* InterfaceDeclaration */) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 138 /* LastToken */; + } + ts.isToken = isToken; + function isWord(kind) { + return kind === 69 /* Identifier */ || ts.isKeyword(kind); + } + ts.isWord = isWord; + function isPropertyName(kind) { + return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); + } + function isComment(kind) { + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 9 /* StringLiteral */ + || kind === 10 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 15 /* FirstPunctuation */ <= kind && kind <= 68 /* LastPunctuation */; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 170 /* ArrayLiteralExpression */ || + node.kind === 171 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 187 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 208 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + function hasTrailingDirectorySeparator(path) { + var lastCharacter = path.charAt(path.length - 1); + return lastCharacter === "/" || lastCharacter === "\\"; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function isInReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isReferenceComment); + function isReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInReferenceComment = isInReferenceComment; + function isInNonReferenceComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, isNonReferenceComment); + function isNonReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return !tripleSlashDirectivePrefixRegex.test(commentText); + } + } + ts.isInNonReferenceComment = isInNonReferenceComment; +})(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ +var ts; +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var displayParts; + var lineStart; + var indent; + resetWriter(); + return { + displayParts: function () { return displayParts; }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: function () { }, + reportInaccessibleThisError: function () { } + }; + function writeIndent() { + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + writeIndent(); + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + writeIndent(); + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol), symbol); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3 /* Variable */) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4 /* Property */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768 /* GetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536 /* SetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8 /* EnumMember */) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16 /* Function */) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32 /* Class */) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64 /* Interface */) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384 /* Enum */) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536 /* Module */) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192 /* Method */) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144 /* TypeParameter */) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288 /* TypeAlias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 8388608 /* Alias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind, symbol) { + return { + text: text, + kind: ts.SymbolDisplayPartKind[kind] + }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ + function getNewLineOrDefaultFromHost(host) { + return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + writeDisplayParts(displayPartWriter); + var result = displayPartWriter.displayParts(); + displayPartWriter.clear(); + return result; + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + return mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function getDeclaredName(typeChecker, symbol, location) { + // If this is an export or import specifier it could have been renamed using the 'as' syntax. + // If so we want to search for whatever is under the cursor. + if (isImportOrExportSpecifierName(location)) { + return location.getText(); + } + else if (ts.isStringOrNumericLiteral(location.kind) && + location.parent.kind === 140 /* ComputedPropertyName */) { + return location.text; + } + // Try to get the local symbol if we're dealing with an 'export default' + // since that symbol has the "true" name. + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); + return name; + } + ts.getDeclaredName = getDeclaredName; + function isImportOrExportSpecifierName(location) { + return location.parent && + (location.parent.kind === 234 /* ImportSpecifier */ || location.parent.kind === 238 /* ExportSpecifier */) && + location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && + name.charCodeAt(0) === name.charCodeAt(length - 1) && + (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + return name.substring(1, length - 1); + } + ; + return name; + } + ts.stripQuotes = stripQuotes; + function scriptKindIs(fileName, host) { + var scriptKinds = []; + for (var _i = 2; _i < arguments.length; _i++) { + scriptKinds[_i - 2] = arguments[_i]; + } + var scriptKind = getScriptKind(fileName, host); + return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + } + ts.scriptKindIs = scriptKindIs; + function getScriptKind(fileName, host) { + // First check to see if the script kind was specified by the host. Chances are the host + // may override the default script kind for the file extension. + var scriptKind; + if (host && host.getScriptKind) { + scriptKind = host.getScriptKind(fileName); + } + if (!scriptKind) { + scriptKind = ts.getScriptKindFromFileName(fileName); + } + return ts.ensureScriptKind(fileName, scriptKind); + } + ts.getScriptKind = getScriptKind; + function parseAndReEmitConfigJSONFile(content) { + var options = { + fileName: "config.js", + compilerOptions: { + target: 2 /* ES6 */, + removeComments: true + }, + reportDiagnostics: true + }; + var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; + // Becasue the content was wrapped in "()", the start position of diagnostics needs to be subtract by 1 + // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these + // as well + var trimmedOutput = outputText.trim(); + var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; +})(ts || (ts = {})); +var ts; +(function (ts) { + /// Classifier + function createClassifier() { + var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false); + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = []; + noRegexTable[69 /* Identifier */] = true; + noRegexTable[9 /* StringLiteral */] = true; + noRegexTable[8 /* NumericLiteral */] = true; + noRegexTable[10 /* RegularExpressionLiteral */] = true; + noRegexTable[97 /* ThisKeyword */] = true; + noRegexTable[41 /* PlusPlusToken */] = true; + noRegexTable[42 /* MinusMinusToken */] = true; + noRegexTable[18 /* CloseParenToken */] = true; + noRegexTable[20 /* CloseBracketToken */] = true; + noRegexTable[16 /* CloseBraceToken */] = true; + noRegexTable[99 /* TrueKeyword */] = true; + noRegexTable[84 /* FalseKeyword */] = true; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (ts.isAccessibilityModifier(keyword1)) { + if (keyword2 === 123 /* GetKeyword */ || + keyword2 === 131 /* SetKeyword */ || + keyword2 === 121 /* ConstructorKeyword */ || + keyword2 === 113 /* StaticKeyword */) { + // Allow things like "public get", "public constructor" and "public static". + // These are all legal. + return true; + } + // Any other keyword following "public" is actually an identifier an not a real + // keyword. + return false; + } + // Assume any other keyword combination is legal. This can be refined in the future + // if there are more cases we want the classifier to be better at. + return true; + } + function convertClassifications(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0, n = dense.length; i < n; i += 3) { + var start = dense[i]; + var length_4 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); + } + } + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; + } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + default: + return ts.TokenClass.Identifier; + } + } + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + 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 getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var offset = 0; + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Empty out the template stack for reuse. + while (templateStack.length > 0) { + templateStack.pop(); + } + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + text = "\"\\\n" + text; + offset = 3; + break; + case 2 /* InSingleQuoteStringLiteral */: + text = "'\\\n" + text; + offset = 3; + break; + case 1 /* InMultiLineCommentTrivia */: + text = "/*\n" + text; + offset = 3; + break; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + text = "`\n" + text; + offset = 2; + break; + case 5 /* InTemplateMiddleOrTail */: + text = "}\n" + text; + offset = 2; + // fallthrough + case 6 /* InTemplateSubstitutionPosition */: + templateStack.push(12 /* TemplateHead */); + break; + } + scanner.setText(text); + var result = { + endOfLineState: 0 /* None */, + spans: [] + }; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { + token = 10 /* RegularExpressionLiteral */; + } + } + else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { + token = 69 /* Identifier */; + } + else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 69 /* Identifier */; + } + else if (lastNonTriviaToken === 69 /* Identifier */ && + token === 25 /* LessThanToken */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + else if (token === 117 /* AnyKeyword */ || + token === 132 /* StringKeyword */ || + token === 130 /* NumberKeyword */ || + token === 120 /* BooleanKeyword */ || + token === 133 /* SymbolKeyword */) { + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 69 /* Identifier */; + } + } + else if (token === 12 /* TemplateHead */) { + templateStack.push(token); + } + else if (token === 15 /* OpenBraceToken */) { + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + templateStack.push(token); + } + } + else if (token === 16 /* CloseBraceToken */) { + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 12 /* TemplateHead */) { + token = scanner.reScanTemplateToken(); + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 14 /* TemplateTail */) { + templateStack.pop(); + } + else { + ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); + } + } + else { + ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); + templateStack.pop(); + } + } + } + lastNonTriviaToken = token; + } + processToken(); + } while (token !== 1 /* EndOfFileToken */); + return result; + function processToken() { + var start = scanner.getTokenPos(); + var end = scanner.getTextPos(); + addResult(start, end, classFromKind(token)); + if (end >= text.length) { + if (token === 9 /* StringLiteral */) { + // Check to see if we finished up on a multiline string literal. + var tokenText = scanner.getTokenText(); + if (scanner.isUnterminated()) { + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if (numBackslashes & 1) { + var quoteChar = tokenText.charCodeAt(0); + result.endOfLineState = quoteChar === 34 /* doubleQuote */ + ? 3 /* InDoubleQuoteStringLiteral */ + : 2 /* InSingleQuoteStringLiteral */; + } + } + } + else if (token === 3 /* MultiLineCommentTrivia */) { + // Check to see if the multiline comment was unclosed. + if (scanner.isUnterminated()) { + result.endOfLineState = 1 /* InMultiLineCommentTrivia */; + } + } + else if (ts.isTemplateLiteralKind(token)) { + if (scanner.isUnterminated()) { + if (token === 14 /* TemplateTail */) { + result.endOfLineState = 5 /* InTemplateMiddleOrTail */; + } + else if (token === 11 /* NoSubstitutionTemplateLiteral */) { + result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + } + else { + ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + } + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { + result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; + } + } + } + function addResult(start, end, classification) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. return; } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); + 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; } - switch (n.kind) { - case 199 /* Block */: - if (!ts.isFunctionBlock(n)) { - var parent_15 = n.parent; - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); - // Check if the block is standalone, or 'attached' to some parent statement. - // If the latter, we want to collapse the block, but consider its hint span - // to be the entire span of the parent. - if (parent_15.kind === 204 /* DoStatement */ || - parent_15.kind === 207 /* ForInStatement */ || - parent_15.kind === 208 /* ForOfStatement */ || - parent_15.kind === 206 /* ForStatement */ || - parent_15.kind === 203 /* IfStatement */ || - parent_15.kind === 205 /* WhileStatement */ || - parent_15.kind === 212 /* WithStatement */ || - parent_15.kind === 252 /* CatchClause */) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + start -= offset; + end -= offset; + var length = end - start; + if (length > 0) { + result.spans.push(start); + result.spans.push(length); + result.spans.push(classification); + } + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 37 /* AsteriskToken */: + case 39 /* SlashToken */: + case 40 /* PercentToken */: + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 43 /* LessThanLessThanToken */: + case 44 /* GreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 25 /* LessThanToken */: + case 27 /* GreaterThanToken */: + case 28 /* LessThanEqualsToken */: + case 29 /* GreaterThanEqualsToken */: + case 91 /* InstanceOfKeyword */: + case 90 /* InKeyword */: + case 116 /* AsKeyword */: + case 30 /* EqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + case 32 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + case 46 /* AmpersandToken */: + case 48 /* CaretToken */: + case 47 /* BarToken */: + case 51 /* AmpersandAmpersandToken */: + case 52 /* BarBarToken */: + case 67 /* BarEqualsToken */: + case 66 /* AmpersandEqualsToken */: + case 68 /* CaretEqualsToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 57 /* PlusEqualsToken */: + case 58 /* MinusEqualsToken */: + case 59 /* AsteriskEqualsToken */: + case 61 /* SlashEqualsToken */: + case 62 /* PercentEqualsToken */: + case 56 /* EqualsToken */: + case 24 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + case 49 /* ExclamationToken */: + case 41 /* PlusPlusToken */: + case 42 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function isKeyword(token) { + return token >= 70 /* FirstKeyword */ && token <= 138 /* LastKeyword */; + } + function classFromKind(token) { + if (isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* StringLiteral */: + return 6 /* stringLiteral */; + case 10 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 69 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + return { + getClassificationsForLine: getClassificationsForLine, + getEncodedLexicalClassifications: getEncodedLexicalClassifications + }; + } + ts.createClassifier = createClassifier; + /* @internal */ + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + } + ts.getSemanticClassifications = getSemanticClassifications; + function checkForClassificationCancellation(cancellationToken, kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. + switch (kind) { + case 225 /* ModuleDeclaration */: + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 220 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + /* @internal */ + function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { + var result = []; + processNode(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifySymbol(symbol, meaningAtPosition) { + var flags = symbol.getFlags(); + if ((flags & 788448 /* Classifiable */) === 0 /* None */) { + return; + } + if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (meaningAtPosition & 2 /* Type */) { + if (flags & 64 /* Interface */) { + return 13 /* interfaceName */; + } + else if (flags & 262144 /* TypeParameter */) { + return 15 /* typeParameterName */; + } + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + if (meaningAtPosition & 4 /* Namespace */ || + (meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) { + return 14 /* moduleName */; + } + } + return undefined; + /** + * Returns true if there exists a module that introduces entities on the value side. + */ + function hasValueSideModule(symbol) { + return ts.forEach(symbol.declarations, function (declaration) { + return declaration.kind === 225 /* ModuleDeclaration */ && + ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } + } + function processNode(node) { + // Only walk into nodes that intersect the requested span. + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + var kind = node.kind; + checkForClassificationCancellation(cancellationToken, kind); + if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { + var identifier = node; + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (classifiableNames[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); } - if (parent_15.kind === 216 /* TryStatement */) { - // Could be the try-block, or the finally-block. - var tryStatement = parent_15; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); - break; + } + } + } + ts.forEachChild(node, processNode); + } + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function getClassificationTypeName(type) { + switch (type) { + case 1 /* comment */: return ts.ClassificationTypeNames.comment; + case 2 /* identifier */: return ts.ClassificationTypeNames.identifier; + case 3 /* keyword */: return ts.ClassificationTypeNames.keyword; + case 4 /* numericLiteral */: return ts.ClassificationTypeNames.numericLiteral; + case 5 /* operator */: return ts.ClassificationTypeNames.operator; + case 6 /* stringLiteral */: return ts.ClassificationTypeNames.stringLiteral; + case 8 /* whiteSpace */: return ts.ClassificationTypeNames.whiteSpace; + case 9 /* text */: return ts.ClassificationTypeNames.text; + case 10 /* punctuation */: return ts.ClassificationTypeNames.punctuation; + case 11 /* className */: return ts.ClassificationTypeNames.className; + case 12 /* enumName */: return ts.ClassificationTypeNames.enumName; + case 13 /* interfaceName */: return ts.ClassificationTypeNames.interfaceName; + case 14 /* moduleName */: return ts.ClassificationTypeNames.moduleName; + case 15 /* typeParameterName */: return ts.ClassificationTypeNames.typeParameterName; + case 16 /* typeAliasName */: return ts.ClassificationTypeNames.typeAliasName; + case 17 /* parameterName */: return ts.ClassificationTypeNames.parameterName; + case 18 /* docCommentTagName */: return ts.ClassificationTypeNames.docCommentTagName; + case 19 /* jsxOpenTagName */: return ts.ClassificationTypeNames.jsxOpenTagName; + case 20 /* jsxCloseTagName */: return ts.ClassificationTypeNames.jsxCloseTagName; + case 21 /* jsxSelfClosingTagName */: return ts.ClassificationTypeNames.jsxSelfClosingTagName; + case 22 /* jsxAttribute */: return ts.ClassificationTypeNames.jsxAttribute; + case 23 /* jsxText */: return ts.ClassificationTypeNames.jsxText; + case 24 /* jsxAttributeStringLiteralValue */: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + } + } + function convertClassifications(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0, n = dense.length; i < n; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + /* @internal */ + function getSyntacticClassifications(cancellationToken, sourceFile, span) { + return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + } + ts.getSyntacticClassifications = getSyntacticClassifications; + /* @internal */ + function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { + var spanStart = span.start; + var spanLength = span.length; + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + // The moment we get something that isn't trivia, then stop processing. + if (!ts.isTrivia(kind)) { + return start; + } + // Don't bother with newlines/whitespace. + if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { + continue; + } + // Only bother with the trivia if it at least intersects the span of interest. + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + } + if (kind === 7 /* ConflictMarkerTrivia */) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ======== add a comment for the first line, and then lex all + // subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + docCommentAndDiagnostics.jsDoc.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDoc); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + if (docComment.tags) { + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); + pos = tag.tagName.end; + switch (tag.kind) { + case 275 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 278 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + break; + case 277 /* JSDocTypeTag */: + processElement(tag.typeExpression); + break; + case 276 /* JSDocReturnTag */: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.preParameterName) { + pushCommentRange(pos, tag.preParameterName.pos - pos); + pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); + pos = tag.preParameterName.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (tag.postParameterName) { + pushCommentRange(pos, tag.postParameterName.pos - pos); + pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); + pos = tag.postParameterName.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ======= marker is on as a comment. Then just lex + // all further tokens and add them to the result. + var i; + for (i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1 /* comment */); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.isJSDocTag(node)) { + return true; + } + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifiedElementName || classifyTokenType(node.kind, node); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 243 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 245 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 242 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 246 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; + } + // 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, token) { + if (ts.isKeyword(tokenKind)) { + return 3 /* keyword */; + } + // Special case < and > If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { + // 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 && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10 /* punctuation */; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + if (tokenKind === 56 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (token.parent.kind === 218 /* VariableDeclaration */ || + token.parent.kind === 145 /* PropertyDeclaration */ || + token.parent.kind === 142 /* Parameter */ || + token.parent.kind === 246 /* JsxAttribute */) { + return 5 /* operator */; + } + } + if (token.parent.kind === 187 /* BinaryExpression */ || + token.parent.kind === 185 /* PrefixUnaryExpression */ || + token.parent.kind === 186 /* PostfixUnaryExpression */ || + token.parent.kind === 188 /* ConditionalExpression */) { + return 5 /* operator */; + } + } + return 10 /* punctuation */; + } + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; + } + else if (tokenKind === 9 /* StringLiteral */) { + return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + } + else if (tokenKind === 10 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (tokenKind === 244 /* JsxText */) { + return 23 /* jsxText */; + } + else if (tokenKind === 69 /* Identifier */) { + if (token) { + switch (token.parent.kind) { + case 221 /* ClassDeclaration */: + if (token.parent.name === token) { + return 11 /* className */; + } + return; + case 141 /* TypeParameter */: + if (token.parent.name === token) { + return 15 /* typeParameterName */; + } + return; + case 222 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return 13 /* interfaceName */; + } + return; + case 224 /* EnumDeclaration */: + if (token.parent.name === token) { + return 12 /* enumName */; + } + return; + case 225 /* ModuleDeclaration */: + if (token.parent.name === token) { + return 14 /* moduleName */; + } + return; + case 142 /* Parameter */: + if (token.parent.name === token) { + var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; + return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + } + return; + } + } + return 2 /* identifier */; + } + } + function processElement(element) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(cancellationToken, element.kind); + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; + if (!tryClassifyNode(child)) { + // Recurse into our child nodes. + processElement(child); + } + } + } + } + } + ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Completions; + (function (Completions) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + if (ts.isInReferenceComment(sourceFile, position)) { + return getTripleSlashReferenceCompletion(sourceFile, position); + } + if (ts.isInString(sourceFile, position)) { + return getStringLiteralCompletionEntries(sourceFile, position); + } + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + if (isJsDocTagName) { + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + } + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); + } + else { + if (!symbols || symbols.length === 0) { + if (sourceFile.languageVariant === 1 /* JSX */ && + location.parent && location.parent.kind === 245 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } + } + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); + } + // Add keywords if this is not a member completion list + if (!isMemberCompletion && !isJsDocTagName) { + ts.addRange(entries, keywordCompletions); + } + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { + var entries = []; + var nameTable = ts.getNameTable(sourceFile); + for (var name_46 in nameTable) { + // Skip identifiers produced only from the current location + if (nameTable[name_46] === position) { + continue; + } + if (!uniqueNames[name_46]) { + uniqueNames[name_46] = name_46; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, /*performCharacterChecks*/ true); + if (displayName) { + var entry = { + name: displayName, + kind: ts.ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); + } + } + } + return entries; + } + function createCompletionEntry(symbol, location, performCharacterChecks) { + // Try to get a valid display name for this symbol, if we could not find one, then ignore it. + // We would like to only show things that can be added after a dot, so for instance numeric properties can + // not be accessed with a dot (a.1 <- invalid) + var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, compilerOptions.target, performCharacterChecks, location); + if (!displayName) { + return undefined; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). + return { + name: displayName, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + sortText: "0" + }; + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { + var start = ts.timestamp(); + var uniqueNames = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var entry = createCompletionEntry(symbol, location, performCharacterChecks); + if (entry) { + var id = ts.escapeIdentifier(entry.name); + if (!uniqueNames[id]) { + entries.push(entry); + uniqueNames[id] = id; + } + } + } + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); + return uniqueNames; + } + function getStringLiteralCompletionEntries(sourceFile, position) { + var node = ts.findPrecedingToken(position, sourceFile); + if (!node || node.kind !== 9 /* StringLiteral */) { + return undefined; + } + if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); + } + else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return getStringLiteralCompletionEntriesFromElementAccess(node.parent); + } + else if (node.parent.kind === 230 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + return getStringLiteralCompletionEntriesFromModuleNames(node); + } + else { + var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); + if (argumentInfo) { + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + } + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return getStringLiteralCompletionEntriesFromContextualType(node); + } + } + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var type = typeChecker.getContextualType(element.parent); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + } + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + var candidates = []; + var entries = []; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); + for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { + var candidate = candidates_3[_i]; + if (candidate.parameters.length > argumentInfo.argumentIndex) { + var parameter = candidate.parameters[argumentInfo.argumentIndex]; + addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); + } + } + if (entries.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + } + return undefined; + } + function getStringLiteralCompletionEntriesFromElementAccess(node) { + var type = typeChecker.getTypeAtLocation(node.expression); + var entries = []; + if (type) { + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); + if (entries.length) { + return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + } + } + return undefined; + } + function getStringLiteralCompletionEntriesFromContextualType(node) { + var type = typeChecker.getContextualType(node); + if (type) { + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + } + } + return undefined; + } + function addStringLiteralCompletionsFromType(type, result) { + if (!type) { + return; + } + if (type.flags & 524288 /* Union */) { + ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); + } + else { + if (type.flags & 32 /* StringLiteral */) { + result.push({ + name: type.text, + kindModifiers: ts.ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.variableElement, + sortText: "0" + }); + } + } + } + function getStringLiteralCompletionEntriesFromModuleNames(node) { + var literalValue = ts.normalizeSlashes(node.text); + var scriptPath = node.getSourceFile().path; + var scriptDirectory = ts.getDirectoryPath(scriptPath); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var entries; + if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { + if (compilerOptions.rootDirs) { + entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ false, span, scriptPath); + } + else { + entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ false, span, scriptPath); + } + } + else { + // Check for node modules + entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries + }; + } + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ + function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { + // Make all paths absolute/normalized if they are not already + rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + // Determine the path to the directory containing the script relative to the root directory it is contained within + var relativeDirectory; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDirectory = rootDirs_1[_i]; + if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { + relativeDirectory = scriptPath.substr(rootDirectory.length); + break; + } + } + // Now find a path for each potential directory that is to be merged with the one containing the script + return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + } + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, exclude) { + var basePath = compilerOptions.project || host.getCurrentDirectory(); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); + var result = []; + for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { + var baseDirectory = baseDirectories_1[_i]; + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, exclude, result); + } + return result; + } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { + if (result === void 0) { result = []; } + fragment = ts.getDirectoryPath(fragment); + if (!fragment) { + fragment = "./"; + } + else { + fragment = ts.ensureTrailingDirectorySeparator(fragment); + } + var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); + var baseDirectory = ts.getDirectoryPath(absolutePath); + var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (tryDirectoryExists(host, baseDirectory)) { + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (files) { + var foundFiles = ts.createMap(); + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; + filePath = ts.normalizePath(filePath); + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { + continue; + } + var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + if (!foundFiles[foundFileName]) { + foundFiles[foundFileName] = true; + } + } + for (var foundFile in foundFiles) { + result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + } + } + // If possible, get folder completion as well + var directories = tryGetDirectories(host, baseDirectory); + if (directories) { + for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { + var directory = directories_2[_a]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + } + } + } + return result; + } + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span) { + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + var result; + if (baseUrl) { + var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var projectDir = compilerOptions.project || host.getCurrentDirectory(); + var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); + result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span); + if (paths) { + for (var path in paths) { + if (paths.hasOwnProperty(path)) { + if (path === "*") { + if (paths[path]) { + for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { + var pattern = _a[_i]; + for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions); _b < _c.length; _b++) { + var match = _c[_b]; + result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + } + } + } } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); - break; + else if (ts.startsWith(path, fragment)) { + var entry = paths[path] && paths[path].length === 1 && paths[path][0]; + if (entry) { + result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); } } } - // Block was a standalone block. In this case we want to only collapse - // the span of the block, independent of any parent span. - var span = ts.createTextSpanFromBounds(n.getStart(), n.end); - elements.push({ - textSpan: span, - hintSpan: span, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); + } + } + } + else { + result = []; + } + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); + for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions); _d < _e.length; _d++) { + var moduleName = _e[_d]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + return result; + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions) { + if (host.readDirectory) { + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (parsed) { + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); + if (matches) { + var result = []; + // Trim away prefix and suffix + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + continue; + } + var start = completePrefix.length; + var length_5 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_5))); + } + return result; + } + } + } + return undefined; + } + function enumeratePotentialNonRelativeModules(fragment, scriptPath, options) { + // Check If this is a nested module + var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; + // Get modules that the type checker picked up + var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts + if (isNestedModule) { + var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); + nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { + if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { + return moduleName.substr(moduleNameWithSeperator_1.length); + } + return moduleName; + }); + } + if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { + var visibleModule = _a[_i]; + if (!isNestedModule) { + nonRelativeModules.push(visibleModule.moduleName); + } + else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { + var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); + if (nestedFiles) { + for (var _b = 0, nestedFiles_1 = nestedFiles; _b < nestedFiles_1.length; _b++) { + var f = nestedFiles_1[_b]; + f = ts.normalizePath(f); + var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); + nonRelativeModules.push(nestedModule); + } + } + } + } + } + return ts.deduplicate(nonRelativeModules); + } + function getTripleSlashReferenceCompletion(sourceFile, position) { + var token = ts.getTokenAtPosition(sourceFile, position); + if (!token) { + return undefined; + } + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + if (!commentRanges || !commentRanges.length) { + return undefined; + } + var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + if (!range) { + return undefined; + } + var text = sourceFile.text.substr(range.pos, position - range.pos); + var match = tripleSlashDirectiveFragmentRegex.exec(text); + if (match) { + var prefix = match[1]; + var kind = match[2]; + var toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + var entries_3; + if (kind === "path") { + // Give completions for a relative path + var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); + entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + } + else { + // Give completions based on the typings available + var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; + entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + } + return { + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries_3 + }; + } + return undefined; + } + function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + if (result === void 0) { result = []; } + // Check for typings specified in compiler options + if (options.types) { + for (var _i = 0, _a = options.types; _i < _a.length; _i++) { + var moduleName = _a[_i]; + result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + } + } + else if (host.getDirectories) { + var typeRoots = void 0; + try { + // Wrap in try catch because getEffectiveTypeRoots touches the filesystem + typeRoots = ts.getEffectiveTypeRoots(options, host); + } + catch (e) { } + if (typeRoots) { + for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { + var root = typeRoots_2[_b]; + getCompletionEntriesFromDirectories(host, options, root, span, result); + } + } + } + if (host.getDirectories) { + // Also get all @types typings installed in visible node_modules directories + for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { + var packageJson = _d[_c]; + var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + } + } + return result; + } + function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + if (host.getDirectories && tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { + var typeDirectory = directories_3[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + } + } + } + } + function findPackageJsons(currentDir) { + var paths = []; + var currentConfigPath; + while (true) { + currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); + if (currentConfigPath) { + paths.push(currentConfigPath); + currentDir = ts.getDirectoryPath(currentConfigPath); + var parent_16 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_16) { break; } - // Fallthrough. - case 226 /* ModuleBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + currentDir = parent_16; + } + else { break; } - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 227 /* CaseBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); - break; - } - case 170 /* ArrayLiteralExpression */: - var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); - break; } - depth++; - ts.forEachChild(n, walk); - depth--; + return paths; + } + function enumerateNodeModulesVisibleToScript(host, scriptPath) { + var result = []; + if (host.readFile && host.fileExists) { + for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = tryReadingPackageJson(packageJson); + if (!contents) { + return; + } + var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); + var foundModuleNames = []; + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + addPotentialPackageNames(contents[key], foundModuleNames); + } + for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { + var moduleName = foundModuleNames_1[_c]; + var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); + result.push({ + moduleName: moduleName, + moduleDir: moduleDir + }); + } + } + } + return result; + function tryReadingPackageJson(filePath) { + try { + var fileText = tryReadFile(host, filePath); + return fileText ? JSON.parse(fileText) : undefined; + } + catch (e) { + return undefined; + } + } + function addPotentialPackageNames(dependencies, result) { + if (dependencies) { + for (var dep in dependencies) { + if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { + result.push(dep); + } + } + } + } + } + function createCompletionEntryForModule(name, kind, replacementSpan) { + return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + } + // Replace everything after the last directory seperator that appears + function getDirectoryFragmentTextSpan(text, textStart) { + var index = text.lastIndexOf(ts.directorySeparator); + var offset = index !== -1 ? index + 1 : 0; + return { start: textStart + offset, length: text.length - offset }; + } + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) + function isPathRelativeToScript(path) { + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; + var slashCharCode = path.charCodeAt(slashIndex); + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; + } + return false; + } + function normalizeAndPreserveTrailingSlash(path) { + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); } - walk(sourceFile); - return elements; } - OutliningElementsCollector.collectElements = collectElements; - })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + // Compute all the completion symbols again. + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_2 = completionData.location; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); + if (symbol) { + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + return { + name: entryName, + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + kind: symbolKind, + displayParts: displayParts, + documentation: documentation + }; + } + } + // Didn't find a symbol with this name. See if we can find a keyword instead. + var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + if (keywordCompletion) { + return { + name: entryName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined + }; + } + return undefined; + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + // Compute all the completion symbols again. + var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (completionData) { + var symbols = completionData.symbols, location_3 = completionData.location; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); + } + return undefined; + } + Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + function getCompletionData(typeChecker, log, sourceFile, position) { + var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + var isJsDocTagName = false; + var start = ts.timestamp(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); + // Completion not allowed inside comments, bail out if this is the case + var insideComment = ts.isInsideComment(sourceFile, currentToken, position); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + if (insideComment) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + isJsDocTagName = true; + } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets + var insideJsDocTagExpression = false; + var tag = ts.getJsDocTagAtPosition(sourceFile, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + isJsDocTagName = true; + } + switch (tag.kind) { + case 277 /* JSDocTypeTag */: + case 275 /* JSDocParameterTag */: + case 276 /* JSDocReturnTag */: + var tagWithExpression = tag; + if (tagWithExpression.typeExpression) { + insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; + } + break; + } + } + if (isJsDocTagName) { + return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + } + if (!insideJsDocTagExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = ts.timestamp(); + var previousToken = ts.findPrecedingToken(position, sourceFile); + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file + var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. + if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { + var start_2 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. + var node = currentToken; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + // Bail out if this is a known invalid completion location + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent_17 = contextToken.parent, kind = contextToken.kind; + if (kind === 21 /* DotToken */) { + if (parent_17.kind === 172 /* PropertyAccessExpression */) { + node = contextToken.parent.expression; + isRightOfDot = true; + } + else if (parent_17.kind === 139 /* QualifiedName */) { + node = contextToken.parent.left; + isRightOfDot = true; + } + else { + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + if (kind === 25 /* LessThanToken */) { + isRightOfOpenTag = true; + location = contextToken; + } + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 245 /* JsxClosingElement */) { + isStartingCloseTag = true; + location = contextToken; + } + } + } + var semanticStart = ts.timestamp(); + var isMemberCompletion; + var isNewIdentifierLocation; + var symbols = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); + if (tryGetGlobalSymbols()) { + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 8388608 /* Alias */)); })); + } + else { + symbols = tagSymbols; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); + return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + function getTypeScriptMemberSymbols() { + // Right of dot member completion list + isMemberCompletion = true; + isNewIdentifierLocation = false; + if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { + var symbol = typeChecker.getSymbolAtLocation(node); + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 8388608 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol && symbol.flags & 1952 /* HasExports */) { + // Extract module or enum members + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + ts.forEach(exportedSymbols, function (symbol) { + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + }); + } + } + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { + if (type) { + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + } + if (isJavaScriptFile && type.flags & 524288 /* Union */) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); + } + } + } + } + function tryGetGlobalSymbols() { + var objectLikeContainer; + var namedImportsOrExports; + var jsxContainer; + if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { + return tryGetObjectLikeCompletionSymbols(objectLikeContainer); + } + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { + // cursor is in an import clause + // try to show exported member for imported module + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); + } + if (jsxContainer = tryGetContainingJsxElement(contextToken)) { + var attrsType = void 0; + if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { + // Cursor is inside a JSX self-closing element or opening element + attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + if (attrsType) { + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); + isMemberCompletion = true; + isNewIdentifierLocation = false; + return true; + } + } + } + // Get all entities in the current scope. + isMemberCompletion = false; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + /// TODO filter meaning based on the current context + var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + return true; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = ts.timestamp(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 244 /* JsxText */) { + return true; + } + if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 243 /* JsxOpeningElement */) { + return true; + } + if (contextToken.parent.kind === 245 /* JsxClosingElement */ || contextToken.parent.kind === 242 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 241 /* JsxElement */; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + switch (previousToken.kind) { + case 24 /* CommaToken */: + return containingNodeKind === 174 /* CallExpression */ // func( a, | + || containingNodeKind === 148 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 175 /* NewExpression */ // new C(a, | + || containingNodeKind === 170 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 187 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 156 /* FunctionType */; // var x: (s: string, list| + case 17 /* OpenParenToken */: + return containingNodeKind === 174 /* CallExpression */ // func( | + || containingNodeKind === 148 /* Constructor */ // constructor( | + || containingNodeKind === 175 /* NewExpression */ // new C(a| + || containingNodeKind === 178 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 164 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 19 /* OpenBracketToken */: + return containingNodeKind === 170 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 153 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 140 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 125 /* ModuleKeyword */: // module | + case 126 /* NamespaceKeyword */: + return true; + case 21 /* DotToken */: + return containingNodeKind === 225 /* ModuleDeclaration */; // module A.| + case 15 /* OpenBraceToken */: + return containingNodeKind === 221 /* ClassDeclaration */; // class A{ | + case 56 /* EqualsToken */: + return containingNodeKind === 218 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 187 /* BinaryExpression */; // x = a| + case 12 /* TemplateHead */: + return containingNodeKind === 189 /* TemplateExpression */; // `aa ${| + case 13 /* TemplateMiddle */: + return containingNodeKind === 197 /* TemplateSpan */; // `aa ${10} dd ${| + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return containingNodeKind === 145 /* PropertyDeclaration */; // class A{ public | + } + // Previous token may have been a keyword that was converted to an identifier. + switch (previousToken.getText()) { + case "public": + case "protected": + case "private": + return true; + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 10 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(contextToken.kind)) { + var start_3 = contextToken.getStart(); + var end = contextToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start_3 < position && position < end) { + return true; + } + if (position === end) { + return !!contextToken.isUnterminated + || contextToken.kind === 10 /* RegularExpressionLiteral */; + } + } + return false; + } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + // We're looking up possible property names from contextual/inferred/declared type. + isMemberCompletion = true; + var typeForObject; + var existingMembers; + if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { + // We are completing on contextual types, but may also include properties + // other than those within the declared type. + isNewIdentifierLocation = true; + // If the object literal is being assigned to something of type 'null | { hello: string }', + // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. + typeForObject = typeChecker.getContextualType(objectLikeContainer); + typeForObject = typeForObject && typeForObject.getNonNullableType(); + existingMembers = objectLikeContainer.properties; + } + else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { + // We are *only* completing on properties from the type being destructured. + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (ts.isVariableLike(rootDeclaration)) { + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); + if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); + } + else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); + } + } + if (canGetType) { + typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + existingMembers = objectLikeContainer.elements; + } + } + else { + ts.Debug.fail("Root declaration is not variable-like."); + } + } + else { + ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); + } + if (!typeForObject) { + return false; + } + var typeMembers = typeChecker.getPropertiesOfType(typeForObject); + if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list + symbols = filterObjectMembersList(typeMembers, existingMembers); + } + return true; + } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 233 /* NamedImports */ ? + 230 /* ImportDeclaration */ : + 236 /* ExportDeclaration */; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); + } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : ts.emptyArray; + return true; + } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15 /* OpenBraceToken */: // const x = { | + case 24 /* CommaToken */: + var parent_18 = contextToken.parent; + if (parent_18 && (parent_18.kind === 171 /* ObjectLiteralExpression */ || parent_18.kind === 167 /* ObjectBindingPattern */)) { + return parent_18; + } + break; + } + } + return undefined; + } + /** + * Returns the containing list of named imports or exports of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15 /* OpenBraceToken */: // import { | + case 24 /* CommaToken */: + switch (contextToken.parent.kind) { + case 233 /* NamedImports */: + case 237 /* NamedExports */: + return contextToken.parent; + } + } + } + return undefined; + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent_19 = contextToken.parent; + switch (contextToken.kind) { + case 26 /* LessThanSlashToken */: + case 39 /* SlashToken */: + case 69 /* Identifier */: + case 246 /* JsxAttribute */: + case 247 /* JsxSpreadAttribute */: + if (parent_19 && (parent_19.kind === 242 /* JsxSelfClosingElement */ || parent_19.kind === 243 /* JsxOpeningElement */)) { + return parent_19; + } + else if (parent_19.kind === 246 /* JsxAttribute */) { + return parent_19.parent; + } + break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 9 /* StringLiteral */: + if (parent_19 && ((parent_19.kind === 246 /* JsxAttribute */) || (parent_19.kind === 247 /* JsxSpreadAttribute */))) { + return parent_19.parent; + } + break; + case 16 /* CloseBraceToken */: + if (parent_19 && + parent_19.kind === 248 /* JsxExpression */ && + parent_19.parent && + (parent_19.parent.kind === 246 /* JsxAttribute */)) { + return parent_19.parent.parent; + } + if (parent_19 && parent_19.kind === 247 /* JsxSpreadAttribute */) { + return parent_19.parent; + } + break; + } + } + return undefined; + } + function isFunction(kind) { + switch (kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 153 /* IndexSignature */: + return true; + } + return false; + } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { + var containingNodeKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 24 /* CommaToken */: + return containingNodeKind === 218 /* VariableDeclaration */ || + containingNodeKind === 219 /* VariableDeclarationList */ || + containingNodeKind === 200 /* VariableStatement */ || + containingNodeKind === 224 /* EnumDeclaration */ || + isFunction(containingNodeKind) || + containingNodeKind === 221 /* ClassDeclaration */ || + containingNodeKind === 192 /* ClassExpression */ || + containingNodeKind === 222 /* InterfaceDeclaration */ || + containingNodeKind === 168 /* ArrayBindingPattern */ || + containingNodeKind === 223 /* TypeAliasDeclaration */; // type Map, K, | + case 21 /* DotToken */: + return containingNodeKind === 168 /* ArrayBindingPattern */; // var [.| + case 54 /* ColonToken */: + return containingNodeKind === 169 /* BindingElement */; // var {x :html| + case 19 /* OpenBracketToken */: + return containingNodeKind === 168 /* ArrayBindingPattern */; // var [x| + case 17 /* OpenParenToken */: + return containingNodeKind === 252 /* CatchClause */ || + isFunction(containingNodeKind); + case 15 /* OpenBraceToken */: + return containingNodeKind === 224 /* EnumDeclaration */ || + containingNodeKind === 222 /* InterfaceDeclaration */ || + containingNodeKind === 159 /* TypeLiteral */; // const x : { | + case 23 /* SemicolonToken */: + return containingNodeKind === 144 /* PropertySignature */ && + contextToken.parent && contextToken.parent.parent && + (contextToken.parent.parent.kind === 222 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 159 /* TypeLiteral */); // const x : { a; | + case 25 /* LessThanToken */: + return containingNodeKind === 221 /* ClassDeclaration */ || + containingNodeKind === 192 /* ClassExpression */ || + containingNodeKind === 222 /* InterfaceDeclaration */ || + containingNodeKind === 223 /* TypeAliasDeclaration */ || + isFunction(containingNodeKind); + case 113 /* StaticKeyword */: + return containingNodeKind === 145 /* PropertyDeclaration */; + case 22 /* DotDotDotToken */: + return containingNodeKind === 142 /* Parameter */ || + (contextToken.parent && contextToken.parent.parent && + contextToken.parent.parent.kind === 168 /* ArrayBindingPattern */); // var [...z| + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return containingNodeKind === 142 /* Parameter */; + case 116 /* AsKeyword */: + return containingNodeKind === 234 /* ImportSpecifier */ || + containingNodeKind === 238 /* ExportSpecifier */ || + containingNodeKind === 232 /* NamespaceImport */; + case 73 /* ClassKeyword */: + case 81 /* EnumKeyword */: + case 107 /* InterfaceKeyword */: + case 87 /* FunctionKeyword */: + case 102 /* VarKeyword */: + case 123 /* GetKeyword */: + case 131 /* SetKeyword */: + case 89 /* ImportKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + case 114 /* YieldKeyword */: + case 134 /* TypeKeyword */: + return true; + } + // Previous token may have been a keyword that was converted to an identifier. + switch (contextToken.getText()) { + case "abstract": + case "async": + case "class": + case "const": + case "declare": + case "enum": + case "function": + case "interface": + case "let": + case "private": + case "protected": + case "public": + case "static": + case "var": + case "yield": + return true; + } + return false; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8 /* NumericLiteral */) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @param exportsOfModule The list of symbols which a module exposes. + * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. + * + * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports + * do not occur at the current position and have not otherwise been typed. + */ + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var existingImportsOrExports = ts.createMap(); + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_47 = element.propertyName || element.name; + existingImportsOrExports[name_47.text] = true; + } + if (!ts.someProperties(existingImportsOrExports)) { + return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + } + return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (!existingMembers || existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = ts.createMap(); + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 253 /* PropertyAssignment */ && + m.kind !== 254 /* ShorthandPropertyAssignment */ && + m.kind !== 169 /* BindingElement */ && + m.kind !== 147 /* MethodDeclaration */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (m.getStart() <= position && position <= m.getEnd()) { + continue; + } + var existingName = void 0; + if (m.kind === 169 /* BindingElement */ && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 69 /* Identifier */) { + existingName = m.propertyName.text; + } + } + else { + // TODO(jfreeman): Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + existingName = m.name.text; + } + existingMemberNames[existingName] = true; + } + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); + } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { + var seenNames = ts.createMap(); + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; + // If this is the current item we are editing right now, do not filter it out + if (attr.getStart() <= position && position <= attr.getEnd()) { + continue; + } + if (attr.kind === 246 /* JsxAttribute */) { + seenNames[attr.name.text] = true; + } + } + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); + } + } + /** + * Get the name to be display in completion from a given symbol. + * + * @return undefined if the name is of external module otherwise a name with striped of any quote + */ + function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { + var displayName = ts.getDeclaredName(typeChecker, symbol, location); + if (displayName) { + var firstCharCode = displayName.charCodeAt(0); + // First check of the displayName is not external module; if it is an external module, it is not valid entry + if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + return undefined; + } + } + return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + } + /** + * Get a displayName from a given for completion list, performing any necessary quotes stripping + * and checking whether the name is valid identifier name. + */ + function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + if (!name) { + return undefined; + } + name = ts.stripQuotes(name); + if (!name) { + return undefined; + } + // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an + // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. + // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. + // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. + if (performCharacterChecks) { + if (!ts.isIdentifierText(name, target)) { + return undefined; + } + } + return name; + } + // A cache of completion entries for keywords, these do not change between sessions + var keywordCompletions = []; + for (var i = 70 /* FirstKeyword */; i <= 138 /* LastKeyword */; i++) { + keywordCompletions.push({ + name: ts.tokenToString(i), + kind: ts.ScriptElementKind.keyword, + kindModifiers: ts.ScriptElementKindModifier.none, + sortText: "0" + }); + } + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches /// = 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { + break; + } + } + } + } + var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); + } + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 206 /* ForStatement */: + case 207 /* ForInStatement */: + case 208 /* ForOfStatement */: + case 204 /* DoStatement */: + case 205 /* WhileStatement */: + return getLoopBreakContinueOccurrences(owner); + case 213 /* SwitchStatement */: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); + var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); + } + }); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getTryCatchFinallyOccurrences(tryStatement) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getThrowOccurrences(throwStatement) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + }); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getReturnOccurrences(returnStatement) { + var func = ts.getContainingFunction(returnStatement); + // If we didn't find a containing function with a block body, bail out. + if (!(func && hasKind(func.body, 199 /* Block */))) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(func.body, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + }); + // Include 'throw' statements that do not occur within a try block. + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getIfElseOccurrences(ifStatement) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (hasKind(ifStatement.parent, 203 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (ifStatement) { + var children = ifStatement.getChildren(); + pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { + break; + } + } + if (!hasKind(ifStatement.elseStatement, 203 /* IfStatement */)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombindElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { + shouldCombindElseAndIf = false; + break; + } + } + if (shouldCombindElseAndIf) { + result.push({ + fileName: fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: ts.HighlightSpanKind.reference + }); + i++; // skip the next keyword + continue; + } + } + // Ordinary case: just highlight the keyword. + result.push(getHighlightSpanForNode(keywords[i])); + } + return result; + } + } + } + DocumentHighlights.getDocumentHighlights = getDocumentHighlights; + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ + function isLabeledBy(node, labelName) { + for (var owner = node.parent; owner.kind === 214 /* LabeledStatement */; owner = owner.parent) { + if (owner.label.text === labelName) { + return true; + } + } + return false; + } + })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. + var buckets = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function getKeyForCompilationSettings(settings) { + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); + } + function getBucketForCompilationSettings(key, createIfMissing) { + var bucket = buckets[key]; + if (!bucket && createIfMissing) { + buckets[key] = bucket = ts.createFileMap(); + } + return bucket; + } + function reportStats() { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { + var entries = buckets[name]; + var sourceFiles = []; + entries.forEachValue(function (key, entry) { + sourceFiles.push({ + name: key, + refCount: entry.languageServiceRefCount, + references: entry.owners.slice(0) + }); + }); + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, undefined, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + } + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + } + function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { + var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + var entry = bucket.get(path); + if (!entry) { + ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0, + owners: [] + }; + bucket.set(path, entry); + } + else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. + if (entry.sourceFile.version !== version) { + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + } + } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var key = getKeyForCompilationSettings(compilationSettings); + return releaseDocumentWithKey(path, key); + } + function releaseDocumentWithKey(path, key) { + var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); + ts.Debug.assert(bucket !== undefined); + var entry = bucket.get(path); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.remove(path); + } + } + return { + acquireDocument: acquireDocument, + acquireDocumentWithKey: acquireDocumentWithKey, + updateDocument: updateDocument, + updateDocumentWithKey: updateDocumentWithKey, + releaseDocument: releaseDocument, + releaseDocumentWithKey: releaseDocumentWithKey, + reportStats: reportStats, + getKeyForCompilationSettings: getKeyForCompilationSettings + }; + } + ts.createDocumentRegistry = createDocumentRegistry; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var FindAllReferences; + (function (FindAllReferences) { + function findReferencedSymbols(typeChecker, cancellationToken, sourceFiles, sourceFile, position, findInStrings, findInComments) { + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + if (node === sourceFile) { + return undefined; + } + switch (node.kind) { + case 8 /* NumericLiteral */: + if (!ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + break; + } + // Fallthrough + case 69 /* Identifier */: + case 97 /* ThisKeyword */: + // case SyntaxKind.SuperKeyword: TODO:GH#9268 + case 121 /* ConstructorKeyword */: + case 9 /* StringLiteral */: + return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, /*implementations*/ false); + } + return undefined; + } + FindAllReferences.findReferencedSymbols = findReferencedSymbols; + function getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, implementations) { + if (!implementations) { + // Labels + if (ts.isLabelName(node)) { + if (ts.isJumpStatementTarget(node)) { + var labelDefinition = ts.getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. + return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; + } + else { + // it is a label definition and not a target, search within the parent labeledStatement + return getLabelReferencesInNode(node.parent, node); + } + } + if (ts.isThis(node)) { + return getReferencesForThisKeyword(node, sourceFiles); + } + if (node.kind === 95 /* SuperKeyword */) { + return getReferencesForSuperKeyword(node); + } + } + // `getSymbolAtLocation` normally returns the symbol of the class when given the constructor keyword, + // so we have to specify that we want the constructor symbol. + var symbol = typeChecker.getSymbolAtLocation(node); + if (!implementations && !symbol && node.kind === 9 /* StringLiteral */) { + return getReferencesForStringLiteral(node, sourceFiles); + } + // Could not find a symbol e.g. unknown identifier + if (!symbol) { + // Can't have references to something that we have no symbol for. + return undefined; + } + var declarations = symbol.declarations; + // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!declarations || !declarations.length) { + return undefined; + } + var result; + // Compute the meaning from the location and the symbol it references + var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), declarations); + // Get the text to search for. + // Note: if this is an external module symbol, the name doesn't include quotes. + var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + // Maps from a symbol ID to the ReferencedSymbol entry in 'result'. + var symbolToIndex = []; + if (scope) { + result = []; + getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + else { + var internedName = getInternedName(symbol, node, declarations); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + cancellationToken.throwIfCancellationRequested(); + var nameTable = ts.getNameTable(sourceFile); + if (nameTable[internedName] !== undefined) { + result = result || []; + getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + } + } + return result; + function getDefinition(symbol) { + var info = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, node.getSourceFile(), ts.getContainerNode(node), node); + var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) { + return undefined; + } + return { + containerKind: "", + containerName: "", + name: name, + kind: info.symbolKind, + fileName: declarations[0].getSourceFile().fileName, + textSpan: ts.createTextSpan(declarations[0].getStart(), 0), + displayParts: info.displayParts + }; + } + function getAliasSymbolForPropertyNameSymbol(symbol, location) { + if (symbol.flags & 8388608 /* Alias */) { + // Default import get alias + var defaultImport = ts.getDeclarationOfKind(symbol, 231 /* ImportClause */); + if (defaultImport) { + return typeChecker.getAliasedSymbol(symbol); + } + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 /* ImportSpecifier */ || + declaration.kind === 238 /* ExportSpecifier */) ? declaration : undefined; }); + if (importOrExportSpecifier && + // export { a } + (!importOrExportSpecifier.propertyName || + // export {a as class } where a is location + importOrExportSpecifier.propertyName === location)) { + // If Import specifier -> get alias + // else Export specifier -> get local target + return importOrExportSpecifier.kind === 234 /* ImportSpecifier */ ? + typeChecker.getAliasedSymbol(symbol) : + typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); + } + } + return undefined; + } + function followAliasIfNecessary(symbol, location) { + return getAliasSymbolForPropertyNameSymbol(symbol, location) || symbol; + } + function getPropertySymbolOfDestructuringAssignment(location) { + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && + typeChecker.getPropertySymbolOfDestructuringAssignment(location); + } + function isObjectBindingPatternElementWithoutPropertyName(symbol) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + return bindingElement && + bindingElement.parent.kind === 167 /* ObjectBindingPattern */ && + !bindingElement.propertyName; + } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); + return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + } + return undefined; + } + function getInternedName(symbol, location, declarations) { + // If this is an export or import specifier it could have been renamed using the 'as' syntax. + // If so we want to search for whatever under the cursor. + if (ts.isImportOrExportSpecifierName(location)) { + return location.getText(); + } + // Try to get the local symbol if we're dealing with an 'export default' + // since that symbol has the "true" name. + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + symbol = localExportDefaultSymbol || symbol; + return ts.stripQuotes(symbol.name); + } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ + function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. + var valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { + return valueDeclaration; + } + // If this is private property or method, the scope is the containing class + if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8 /* Private */) ? d : undefined; }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); + } + } + // If the symbol is an import we would like to find it if we are looking for what it imports. + // So consider it visible outside its declaration scope. + if (symbol.flags & 8388608 /* Alias */) { + return undefined; + } + // If symbol is of object binding pattern element without property name we would want to + // look for property too and that could be anywhere + if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + return undefined; + } + // if this symbol is visible from its parent container, e.g. exported, then bail out + // if symbol correspond to the union property - bail out + if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { + return undefined; + } + var scope; + var declarations = symbol.getDeclarations(); + if (declarations) { + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var container = ts.getContainerNode(declaration); + if (!container) { + return undefined; + } + if (scope && scope !== container) { + // Different declarations have different containers, bail out + return undefined; + } + if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file + return undefined; + } + // The search scope is the container node + scope = container; + } + } + return scope; + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, start); + while (position >= 0) { + cancellationToken.throwIfCancellationRequested(); + // If we are past the end, stop looking + if (position > end) + break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { + // Found a real match. Keep searching. + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var references = []; + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.getWidth() !== labelName.length) { + return; + } + // Only pick labels that are either the target label, or have a target that is the target label + if (node === targetLabel || + (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = { + containerKind: "", + containerName: "", + fileName: targetLabel.getSourceFile().fileName, + kind: ts.ScriptElementKind.label, + name: labelName, + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), + displayParts: [ts.displayPart(labelName, ts.SymbolDisplayPartKind.text)] + }; + return [{ definition: definition, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + if (node) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for + switch (node.kind) { + case 69 /* Identifier */: + return node.getWidth() === searchSymbolName.length; + case 9 /* StringLiteral */: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isNameOfExternalModuleImportOrDeclaration(node)) { + // For string literals we have two additional chars for the quotes + return node.getWidth() === searchSymbolName.length + 2; + } + break; + case 8 /* NumericLiteral */: + if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + return node.getWidth() === searchSymbolName.length; + } + break; + } + } + return false; + } + /** Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ + function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { + var sourceFile = container.getSourceFile(); + var start = findInComments ? container.getFullStart() : container.getStart(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, start, container.getEnd()); + var parents = getParentSymbolsOfPropertyAccess(); + var inheritsFromCache = ts.createMap(); + if (possiblePositions.length) { + // Build the set of symbols to search for, initially it has only the current symbol + var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + if (!isValidReferencePosition(referenceLocation, searchText)) { + // This wasn't the start of a token. Check to see if it might be a + // match in a comment or string if that's what the caller is asking + // for. + if (!implementations && ((findInStrings && ts.isInString(sourceFile, position)) || + (findInComments && ts.isInNonReferenceComment(sourceFile, position)))) { + // In the case where we're looking inside comments/strings, we don't have + // an actual definition. So just use 'undefined' here. Features like + // 'Rename' won't care (as they ignore the definitions), and features like + // 'FindReferences' will just filter out these results. + result.push({ + definition: undefined, + references: [{ + fileName: sourceFile.fileName, + textSpan: ts.createTextSpan(position, searchText.length), + isWriteAccess: false, + isDefinition: false + }] + }); + } + return; + } + if (!(ts.getMeaningFromLocation(referenceLocation) & searchMeaning)) { + return; + } + var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation); + if (referenceSymbol) { + var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, + /*searchLocationIsConstructor*/ searchLocation.kind === 121 /* ConstructorKeyword */, parents, inheritsFromCache); + if (relatedSymbol) { + addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); + } + else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { + addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); + } + else if (searchLocation.kind === 121 /* ConstructorKeyword */) { + findAdditionalConstructorReferences(referenceSymbol, referenceLocation); + } + } + }); + } + return; + /* If we are just looking for implementations and this is a property access expression, we need to get the + * symbol of the local type of the symbol the property is being accessed on. This is because our search + * symbol may have a different parent symbol if the local type's symbol does not declare the property + * being accessed (i.e. it is declared in some parent class or interface) + */ + function getParentSymbolsOfPropertyAccess() { + if (implementations) { + var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(searchLocation); + if (propertyAccessExpression) { + var localParentType = typeChecker.getTypeAtLocation(propertyAccessExpression.expression); + if (localParentType) { + if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== searchSymbol.parent) { + return [localParentType.symbol]; + } + else if (localParentType.flags & 1572864 /* UnionOrIntersection */) { + return getSymbolsForClassAndInterfaceComponents(localParentType); + } + } + } + } + } + function getPropertyAccessExpressionFromRightHandSide(node) { + return ts.isRightSideOfPropertyAccess(node) && node.parent; + } + /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ + function findAdditionalConstructorReferences(referenceSymbol, referenceLocation) { + ts.Debug.assert(ts.isClassLike(searchSymbol.valueDeclaration)); + var referenceClass = referenceLocation.parent; + if (referenceSymbol === searchSymbol && ts.isClassLike(referenceClass)) { + ts.Debug.assert(referenceClass.name === referenceLocation); + // This is the class declaration containing the constructor. + addReferences(findOwnConstructorCalls(searchSymbol)); + } + else { + // If this class appears in `extends C`, then the extending class' "super" calls are references. + var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); + if (classExtending && ts.isClassLike(classExtending) && followAliasIfNecessary(referenceSymbol, referenceLocation) === searchSymbol) { + addReferences(superConstructorAccesses(classExtending)); + } + } + } + function addReferences(references) { + if (references.length) { + var referencedSymbol = getReferencedSymbol(searchSymbol); + ts.addRange(referencedSymbol.references, ts.map(references, getReferenceEntryFromNode)); + } + } + /** `classSymbol` is the class where the constructor was defined. + * Reference the constructor and all calls to `new this()`. + */ + function findOwnConstructorCalls(classSymbol) { + var result = []; + for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148 /* Constructor */); + var ctrKeyword = decl.getChildAt(0); + ts.Debug.assert(ctrKeyword.kind === 121 /* ConstructorKeyword */); + result.push(ctrKeyword); + } + ts.forEachProperty(classSymbol.exports, function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 147 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 97 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + result.push(thisKeyword); + } + }); + } + } + }); + return result; + } + /** Find references to `super` in the constructor of an extending class. */ + function superConstructorAccesses(cls) { + var symbol = cls.symbol; + var ctr = symbol.members["__constructor"]; + if (!ctr) { + return []; + } + var result = []; + for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.Debug.assert(decl.kind === 148 /* Constructor */); + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 95 /* SuperKeyword */, function (node) { + if (ts.isCallExpressionTarget(node)) { + result.push(node); + } + }); + } + } + ; + return result; + } + function getReferencedSymbol(symbol) { + var symbolId = ts.getSymbolId(symbol); + var index = symbolToIndex[symbolId]; + if (index === undefined) { + index = result.length; + symbolToIndex[symbolId] = index; + result.push({ + definition: getDefinition(symbol), + references: [] + }); + } + return result[index]; + } + function addReferenceToRelatedSymbol(node, relatedSymbol) { + var references = getReferencedSymbol(relatedSymbol).references; + if (implementations) { + getImplementationReferenceEntryForNode(node, references); + } + else { + references.push(getReferenceEntryFromNode(node)); + } + } + } + function getImplementationReferenceEntryForNode(refNode, result) { + // Check if we found a function/propertyAssignment/method with an implementation or initializer + if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { + result.push(getReferenceEntryFromNode(refNode.parent)); + } + else if (refNode.kind === 69 /* Identifier */) { + if (refNode.parent.kind === 254 /* ShorthandPropertyAssignment */) { + // Go ahead and dereference the shorthand assignment by going to its definition + getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); + } + // Check if the node is within an extends or implements clause + var containingClass = getContainingClassIfInHeritageClause(refNode); + if (containingClass) { + result.push(getReferenceEntryFromNode(containingClass)); + return; + } + // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface + var containingTypeReference = getContainingTypeReference(refNode); + if (containingTypeReference) { + var parent_21 = containingTypeReference.parent; + if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + } + else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { + if (parent_21.body.kind === 199 /* Block */) { + ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { + maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); + } + }); + } + else if (isImplementationExpression(parent_21.body)) { + maybeAdd(getReferenceEntryFromNode(parent_21.body)); + } + } + else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + } + } + } + // Type nodes can contain multiple references to the same type. For example: + // let x: Foo & (Foo & Bar) = ... + // Because we are returning the implementation locations and not the identifier locations, + // duplicate entries would be returned here as each of the type references is part of + // the same implementation. For that reason, check before we add a new entry + function maybeAdd(a) { + if (!ts.forEach(result, function (b) { return a.fileName === b.fileName && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; })) { + result.push(a); + } + } + } + function getSymbolsForClassAndInterfaceComponents(type, result) { + if (result === void 0) { result = []; } + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var componentType = _a[_i]; + if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { + result.push(componentType.symbol); + } + if (componentType.getFlags() & 1572864 /* UnionOrIntersection */) { + getSymbolsForClassAndInterfaceComponents(componentType, result); + } + } + return result; + } + function getContainingTypeReference(node) { + var topLevelTypeReference = undefined; + while (node) { + if (ts.isTypeNode(node)) { + topLevelTypeReference = node; + } + node = node.parent; + } + return topLevelTypeReference; + } + function getContainingClassIfInHeritageClause(node) { + if (node && node.parent) { + if (node.kind === 194 /* ExpressionWithTypeArguments */ + && node.parent.kind === 251 /* HeritageClause */ + && ts.isClassLike(node.parent.parent)) { + return node.parent.parent; + } + else if (node.kind === 69 /* Identifier */ || node.kind === 172 /* PropertyAccessExpression */) { + return getContainingClassIfInHeritageClause(node.parent); + } + } + return undefined; + } + /** + * Returns true if this is an expression that can be considered an implementation + */ + function isImplementationExpression(node) { + // Unwrap parentheses + if (node.kind === 178 /* ParenthesizedExpression */) { + return isImplementationExpression(node.expression); + } + return node.kind === 180 /* ArrowFunction */ || + node.kind === 179 /* FunctionExpression */ || + node.kind === 171 /* ObjectLiteralExpression */ || + node.kind === 192 /* ClassExpression */ || + node.kind === 170 /* ArrayLiteralExpression */; + } + /** + * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol + * is an interface, determines if some ancestor of the child symbol extends or inherits from it. + * Also takes in a cache of previous results which makes this slightly more efficient and is + * necessary to avoid potential loops like so: + * class A extends B { } + * class B extends A { } + * + * We traverse the AST rather than using the type checker because users are typically only interested + * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling + * implementations of types that share a common ancestor with the type whose implementation we are + * searching for need to be filtered out of the results. The type checker doesn't let us make the + * distinction between structurally compatible implementations and explicit implementations, so we + * must use the AST. + * + * @param child A class or interface Symbol + * @param parent Another class or interface Symbol + * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results + */ + function explicitlyInheritsFrom(child, parent, cachedResults) { + var parentIsInterface = parent.getFlags() & 64 /* Interface */; + return searchHierarchy(child); + function searchHierarchy(symbol) { + if (symbol === parent) { + return true; + } + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + if (key in cachedResults) { + return cachedResults[key]; + } + // Set the key so that we don't infinitely recurse + cachedResults[key] = false; + var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + if (parentIsInterface) { + var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); + if (interfaceReferences) { + for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { + var typeReference = interfaceReferences_1[_i]; + if (searchTypeReference(typeReference)) { + return true; + } + } + } + } + return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + } + else if (declaration.kind === 222 /* InterfaceDeclaration */) { + if (parentIsInterface) { + return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); + } + } + return false; + }); + cachedResults[key] = inherits; + return inherits; + } + function searchTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type && type.symbol) { + return searchHierarchy(type.symbol); + } + } + return false; + } + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); + if (!searchSpaceNode) { + return undefined; + } + // Whether 'super' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + default: + return undefined; + } + var references = []; + var sourceFile = searchSpaceNode.getSourceFile(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.kind !== 95 /* SuperKeyword */) { + return; + } + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + if (container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = getDefinition(searchSpaceNode.symbol); + return [{ definition: definition, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 32 /* Static */; + switch (searchSpaceNode.kind) { + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + // fall through + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 148 /* Constructor */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + staticFlag &= ts.getModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + case 256 /* SourceFile */: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + // Fall through + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. + default: + return undefined; + } + var references = []; + var possiblePositions; + if (searchSpaceNode.kind === 256 /* SourceFile */) { + ts.forEach(sourceFiles, function (sourceFile) { + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); + }); + } + else { + var sourceFile = searchSpaceNode.getSourceFile(); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); + } + var thisOrSuperSymbol = typeChecker.getSymbolAtLocation(thisOrSuperKeyword); + var displayParts = thisOrSuperSymbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, thisOrSuperSymbol, thisOrSuperKeyword.getSourceFile(), ts.getContainerNode(thisOrSuperKeyword), thisOrSuperKeyword).displayParts; + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: "this", + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: displayParts + }, + references: references + }]; + function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || !ts.isThis(node)) { + return; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 179 /* FunctionExpression */: + case 220 /* FunctionDeclaration */: + if (searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 192 /* ClassExpression */: + case 221 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 256 /* SourceFile */: + if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + result.push(getReferenceEntryFromNode(node)); + } + break; + } + }); + } + } + function getReferencesForStringLiteral(node, sourceFiles) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (!type) { + // nothing to do here. moving on + return undefined; + } + var references = []; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); + getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); + } + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ts.ScriptElementKind.variableElement, + name: type.text, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + displayParts: [ts.displayPart(ts.getTextOfNode(node), ts.SymbolDisplayPartKind.stringLiteral)] + }, + references: references + }]; + function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { + for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { + var position = possiblePositions_1[_i]; + cancellationToken.throwIfCancellationRequested(); + var node_2 = ts.getTouchingWord(sourceFile, position); + if (!node_2 || node_2.kind !== 9 /* StringLiteral */) { + return; + } + var type_1 = ts.getStringLiteralTypeForNode(node_2, typeChecker); + if (type_1 === searchType) { + references.push(getReferenceEntryFromNode(node_2)); + } + } + } + } + function populateSearchSymbolSet(symbol, location) { + // The search set contains at least the current symbol + var result = [symbol]; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var containingObjectLiteralElement = getContainingObjectLiteralElement(location); + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254 /* ShorthandPropertyAssignment */) { + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); + if (propertySymbol) { + result.push(propertySymbol); + } + } + // If the symbol is an alias, add what it aliases to the list + // import {a} from "mod"; + // export {a} + // If the symbol is an alias to default declaration, add what it aliases to the list + // declare "mod" { export default class B { } } + // import B from "mod"; + //// For export specifiers, the exported name can be referring to a local symbol, e.g.: + //// import {a} from "mod"; + //// export {a as somethingElse} + //// We want the *local* declaration of 'a' as declared in the import, + //// *not* as declared within "mod" (or farther) + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); + if (aliasSymbol) { + result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + if (containingObjectLiteralElement) { + ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); + }); + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * const name = "Foo"; + * const obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); + if (shorthandValueSymbol) { + result.push(shorthandValueSymbol); + } + } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 /* Parameter */ && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } + // If this is symbol of binding element without propertyName declaration in Object binding pattern + // Include the property in the search + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); + if (bindingElementPropertySymbol) { + result.push(bindingElementPropertySymbol); + } + // If this is a union property, add all the symbols from all its source symbols in all unioned types. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list + ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + if (rootSymbol !== symbol) { + result.push(rootSymbol); + } + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap()); + } + }); + return result; + } + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited + // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. + // For example: + // interface C extends C { + // /*findRef*/propName: string; + // } + // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, + // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, + // the function will add any found symbol of the property-name, then its sub-routine will call + // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already + // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. + if (symbol.name in previousIterationSymbolsCache) { + return; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + ts.forEach(symbol.getDeclarations(), function (declaration) { + if (ts.isClassLike(declaration)) { + getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); + } + else if (declaration.kind === 222 /* InterfaceDeclaration */) { + ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); + } + }); + } + return; + function getPropertySymbolFromTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type) { + var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); + if (propertySymbol) { + result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); + } + // Visit the typeReference as well to see if it directly or indirectly use that property + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); + } + } + } + } + function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation, searchLocationIsConstructor, parents, cache) { + if (ts.contains(searchSymbols, referenceSymbol)) { + // If we are searching for constructor uses, they must be 'new' expressions. + return (!searchLocationIsConstructor || ts.isNewExpressionTarget(referenceLocation)) && referenceSymbol; + } + // If the reference symbol is an alias, check if what it is aliasing is one of the search + // symbols but by looking up for related symbol of this alias so it can handle multiple level of indirectness. + var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); + if (aliasSymbol) { + return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation, searchLocationIsConstructor, parents, cache); + } + // If the reference location is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this symbol to + // compare to our searchSymbol + var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); + if (containingObjectLiteralElement) { + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { + return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + }); + if (contextualSymbol) { + return contextualSymbol; + } + // If the reference location is the name of property from object literal destructuring pattern + // Get the property symbol from the object literal's type and look if thats the search symbol + // In below eg. get 'property' from type of elems iterating type + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); + if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { + return propertySymbol; + } + } + // If the reference location is the binding element and doesn't have property name + // then include the binding element in the related symbols + // let { a } : { a }; + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); + if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { + return bindingElementPropertySymbol; + } + // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) + // Or a union property, use its underlying unioned symbols + return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { + // if it is in the list, then we are done + if (searchSymbols.indexOf(rootSymbol) >= 0) { + return rootSymbol; + } + // Finally, try all properties with the same name in any type the containing type extended or implemented, and + // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the + // parent symbol + if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + // Parents will only be defined if implementations is true + if (parents) { + if (!ts.forEach(parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, cache); })) { + return undefined; + } + } + var result_3 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, /*previousIterationSymbolsCache*/ ts.createMap()); + return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + } + return undefined; + }); + } + function getNameFromObjectLiteralElement(node) { + if (node.name.kind === 140 /* ComputedPropertyName */) { + var nameExpression = node.name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } + return undefined; + } + return node.name.text; + } + function getPropertySymbolsFromContextualType(node) { + var objectLiteral = node.parent; + var contextualType = typeChecker.getContextualType(objectLiteral); + var name = getNameFromObjectLiteralElement(node); + if (name && contextualType) { + var result_4 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_4.push(symbol_2); + } + if (contextualType.flags & 524288 /* Union */) { + ts.forEach(contextualType.types, function (t) { + var symbol = t.getProperty(name); + if (symbol) { + result_4.push(symbol); + } + }); + } + return result_4; + } + return undefined; + } + /** Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ + function getIntersectingMeaningFromDeclarations(meaning, declarations) { + if (declarations) { + var lastIterationMeaning = void 0; + do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning + lastIterationMeaning = meaning; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + var declarationMeaning = ts.getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + } + FindAllReferences.getReferencedSymbolsForNode = getReferencedSymbolsForNode; + function convertReferences(referenceSymbols) { + if (!referenceSymbols) { + return undefined; + } + var referenceEntries = []; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; + ts.addRange(referenceEntries, referenceSymbol.references); + } + return referenceEntries; + } + FindAllReferences.convertReferences = convertReferences; + function isImplementation(node) { + if (!node) { + return false; + } + else if (ts.isVariableLike(node)) { + if (node.initializer) { + return true; + } + else if (node.kind === 218 /* VariableDeclaration */) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); + } + } + else if (ts.isFunctionLike(node)) { + return !!node.body || ts.hasModifier(node, 2 /* Ambient */); + } + else { + switch (node.kind) { + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 224 /* EnumDeclaration */: + case 225 /* ModuleDeclaration */: + return true; + } + } + return false; + } + function getParentStatementOfVariableDeclaration(node) { + if (node.parent && node.parent.parent && node.parent.parent.kind === 200 /* VariableStatement */) { + ts.Debug.assert(node.parent.kind === 219 /* VariableDeclarationList */); + return node.parent.parent; + } + } + function getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result) { + var refSymbol = typeChecker.getSymbolAtLocation(node); + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration); + if (shorthandSymbol) { + for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) { + result.push(getReferenceEntryFromNode(declaration)); + } + } + } + } + FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; + function getReferenceEntryFromNode(node) { + var start = node.getStart(); + var end = node.getEnd(); + if (node.kind === 9 /* StringLiteral */) { + start += 1; + end -= 1; + } + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(start, end), + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) + }; + } + FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ + function isWriteAccess(node) { + if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { + return true; + } + var parent = node.parent; + if (parent) { + if (parent.kind === 186 /* PostfixUnaryExpression */ || parent.kind === 185 /* PrefixUnaryExpression */) { + return true; + } + else if (parent.kind === 187 /* BinaryExpression */ && parent.left === node) { + var operator = parent.operatorToken.kind; + return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; + } + } + return false; + } + function forEachDescendantOfKind(node, kind, action) { + ts.forEachChild(node, function (child) { + if (child.kind === kind) { + action(child); + } + forEachDescendantOfKind(child, kind, action); + }); + } + /** + * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } + */ + function getContainingObjectLiteralElement(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (node.parent.kind === 140 /* ComputedPropertyName */) { + return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; + } + // intential fall through + case 69 /* Identifier */: + return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; + } + return undefined; + } + function isObjectLiteralPropertyDeclaration(node) { + switch (node.kind) { + case 253 /* PropertyAssignment */: + case 254 /* ShorthandPropertyAssignment */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return true; + } + return false; + } + /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */ + function tryGetClassByExtendingIdentifier(node) { + return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); + } + function isNameOfExternalModuleImportOrDeclaration(node) { + if (node.kind === 9 /* StringLiteral */) { + return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); + } + return false; + } + })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToDefinition; + (function (GoToDefinition) { + function getDefinitionAtPosition(program, sourceFile, position) { + /// Triple slash reference comments + var comment = findReferenceInPosition(sourceFile.referencedFiles, position); + if (comment) { + var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); + if (referenceFile) { + return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; + } + return undefined; + } + // Type reference directives + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + if (referenceFile && referenceFile.resolvedFileName) { + return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + } + return undefined; + } + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + // Labels + if (ts.isJumpStatementTarget(node)) { + var labelName = node.text; + var label = ts.getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfo(label, ts.ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; + } + var typeChecker = program.getTypeChecker(); + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + if (calledDeclaration) { + return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; + } + var symbol = typeChecker.getSymbolAtLocation(node); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return undefined; + } + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol.flags & 8388608 /* Alias */) { + var declaration = symbol.declarations[0]; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from a named import. + // + if (node.kind === 69 /* Identifier */ && + (node.parent === declaration || + (declaration.kind === 234 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 233 /* NamedImports */))) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + } + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + if (!shorthandSymbol) { + return []; + } + var shorthandDeclarations = shorthandSymbol.getDeclarations(); + var shorthandSymbolKind_1 = ts.SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); + } + return getDefinitionFromSymbol(typeChecker, symbol, node); + } + GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /// Goto type + function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); + if (node === sourceFile) { + return undefined; + } + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; + } + if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_5 = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + } + }); + return result_5; + } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(typeChecker, type.symbol, node); + } + GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionFromSymbol(typeChecker, symbol, node) { + var result = []; + var declarations = symbol.getDeclarations(); + var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + // Just add all the declarations. + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + // 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 (ts.isNewExpressionTarget(location) || location.kind === 121 /* ConstructorKeyword */) { + if (symbol.flags & 32 /* Class */) { + // Find the first class-like declaration and try to get the construct signature. + for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isClassLike(declaration)) { + return tryAddSignature(declaration.members, + /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); + } + } + ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 148 /* Constructor */) || + (!selectConstructors && (d.kind === 220 /* FunctionDeclaration */ || d.kind === 147 /* MethodDeclaration */ || d.kind === 146 /* MethodSignature */))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } + function createDefinitionInfo(node, symbolKind, symbolName, containerName) { + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function getSymbolInfo(typeChecker, symbol, node) { + return { + symbolName: typeChecker.symbolToString(symbol), + symbolKind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node), + containerName: symbol.parent ? typeChecker.symbolToString(symbol.parent, node) : "" + }; + } + function createDefinitionFromSignatureDeclaration(typeChecker, decl) { + var _a = getSymbolInfo(typeChecker, decl.symbol, decl), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; + return createDefinitionInfo(decl, symbolKind, symbolName, containerName); + } + function findReferenceInPosition(refs, pos) { + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; + if (ref.pos <= pos && pos < ref.end) { + return ref; + } + } + return undefined; + } + function getDefinitionInfoForFileReference(name, targetFileName) { + return { + fileName: targetFileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: ts.ScriptElementKind.scriptElement, + name: name, + containerName: undefined, + containerKind: undefined + }; + } + /** Returns a CallLikeExpression where `node` is the target being invoked. */ + function getAncestorCallLikeExpression(node) { + var target = climbPastManyPropertyAccesses(node); + var callLike = target.parent; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + } + function climbPastManyPropertyAccesses(node) { + return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; + } + function tryGetSignatureDeclaration(typeChecker, node) { + var callLike = getAncestorCallLikeExpression(node); + return callLike && typeChecker.getResolvedSignature(callLike).declaration; + } + })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var GoToImplementation; + (function (GoToImplementation) { + function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { + // If invoked directly on a shorthand property assignment, then return + // the declaration of the symbol being assigned (not the symbol being assigned to). + if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + var result = []; + ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); + return result.length > 0 ? result : undefined; + } + else if (node.kind === 95 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + // References to and accesses on the super keyword only have one possible implementation, so no + // need to "Find all References" + var symbol = typeChecker.getSymbolAtLocation(node); + return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)]; + } + else { + // Perform "Find all References" and retrieve only those that are implementations + var referencedSymbols = ts.FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, /*findInStrings*/ false, /*findInComments*/ false, /*implementations*/ true); + var result = ts.flatMap(referencedSymbols, function (symbol) { + return ts.map(symbol.references, function (_a) { + var textSpan = _a.textSpan, fileName = _a.fileName; + return ({ textSpan: textSpan, fileName: fileName }); + }); + }); + return result && result.length > 0 ? result : undefined; + } + } + GoToImplementation.getImplementationAtPosition = getImplementationAtPosition; + })(GoToImplementation = ts.GoToImplementation || (ts.GoToImplementation = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsDoc; + (function (JsDoc) { + var jsDocTagNames = [ + "augments", + "author", + "argument", + "borrows", + "class", + "constant", + "constructor", + "constructs", + "default", + "deprecated", + "description", + "event", + "example", + "extends", + "field", + "fileOverview", + "function", + "ignore", + "inner", + "lends", + "link", + "memberOf", + "name", + "namespace", + "param", + "private", + "property", + "public", + "requires", + "returns", + "see", + "since", + "static", + "throws", + "type", + "typedef", + "property", + "prop", + "version" + ]; + var jsDocCompletionEntries; + function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + // Only collect doc comments from duplicate declarations once: + // In case of a union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. const a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array + var documentationComment = []; + forEachUnique(declarations, function (declaration) { + var comments = ts.getJSDocComments(declaration, /*checkParentVariableStatement*/ true); + if (!comments) { + return; + } + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var comment = comments_3[_i]; + if (comment) { + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(ts.textPart(comment)); + } + } + }); + return documentationComment; + } + JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (ts.indexOf(array, array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + function getAllJsDocCompletionEntries() { + return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: ts.ScriptElementKind.keyword, + kindModifiers: "", + sortText: "0" + }; + })); + } + JsDoc.getAllJsDocCompletionEntries = getAllJsDocCompletionEntries; + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ + function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + // Check if in a context where we don't want to perform any insertion + if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + return undefined; + } + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenStart = tokenAtPos.getStart(); + if (!tokenAtPos || tokenStart < position) { + return undefined; + } + // TODO: add support for: + // - enums/enum members + // - interfaces + // - property declarations + // - potentially property assignments + var commentOwner; + findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 220 /* FunctionDeclaration */: + case 147 /* MethodDeclaration */: + case 148 /* Constructor */: + case 221 /* ClassDeclaration */: + case 200 /* VariableStatement */: + break findOwner; + case 256 /* SourceFile */: + return undefined; + case 225 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + if (commentOwner.parent.kind === 225 /* ModuleDeclaration */) { + return undefined; + } + break findOwner; + } + } + if (!commentOwner || commentOwner.getStart() < position) { + return undefined; + } + var parameters = getParametersForJsDocOwningNode(commentOwner); + var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); + var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; + var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var docParams = ""; + for (var i = 0, numParams = parameters.length; i < numParams; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 69 /* Identifier */ ? + currentName.text : + "param" + i; + docParams += indentationStr + " * @param " + paramName + newLine; + } + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. + var preamble = "/**" + newLine + + indentationStr + " * "; + var result = preamble + newLine + + docParams + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getParametersForJsDocOwningNode(commentOwner) { + if (ts.isFunctionLike(commentOwner)) { + return commentOwner.parameters; + } + if (commentOwner.kind === 200 /* VariableStatement */) { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + if (varDeclarations.length === 1 && varDeclarations[0].initializer) { + return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + } + } + return ts.emptyArray; + } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 178 /* ParenthesizedExpression */) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + return rightHandSide.parameters; + case 192 /* ClassExpression */: + for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148 /* Constructor */) { + return member.parameters; + } + } + break; + } + return ts.emptyArray; + } + })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); +})(ts || (ts = {})); +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + // A map of loose file names to library names + // that we are confident require typings + var safeList; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations + * @param typingOptions are used to customize the typing inference process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // Only infer typings for .js and .jsx files + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = ts.createMap(result.config); + } + var filesToWatch = []; + // Directories to search for package.json, bower.json and other typing information + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + // Add the cached typing locations for inferred typings that are already installed + for (var name_48 in packageNameToTypingLocation) { + if (name_48 in inferredTypings && !inferredTypings[name_48]) { + inferredTypings[name_48] = packageNameToTypingLocation[name_48]; + } + } + // Remove typings that the user has added to the exclude list + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + /** + * Merge a given list of typingNames to the inferredTypings map + */ + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); + } + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + /** + * Infer typing names from node_module folder + * @param nodeModulesPath is the path to the "node_modules" folder + */ + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - ts.forEach(program.getSourceFiles(), function (sourceFile) { + ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_49 in nameToDeclarations) { + var declarations = nameToDeclarations[name_49]; if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_49); if (!matches) { continue; } - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -46257,14 +66643,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_49); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -46290,8 +66676,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; if (!match.isCaseSensitive) { return false; } @@ -46366,8 +66752,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -46546,9 +66932,9 @@ var ts; case 169 /* BindingElement */: case 218 /* VariableDeclaration */: var decl = node; - var name_37 = decl.name; - if (ts.isBindingPattern(name_37)) { - addChildrenRecursively(name_37); + var name_50 = decl.name; + if (ts.isBindingPattern(name_50)) { + addChildrenRecursively(name_50); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -46595,23 +66981,19 @@ var ts; addLeafNode(node); break; default: - if (node.jsDocComments) { - for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { - var jsDocComment = _j[_h]; - for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { - var tag = _l[_k]; - if (tag.kind === 279 /* JSDocTypedefTag */) { - addLeafNode(tag); - } + ts.forEach(node.jsDocComments, function (jsDocComment) { + ts.forEach(jsDocComment.tags, function (tag) { + if (tag.kind === 279 /* JSDocTypedefTag */) { + addLeafNode(tag); } - } - } + }); + }); ts.forEachChild(node, addChildrenRecursively); } } /** Merge declarations of the same kind. */ function mergeChildren(children) { - var nameToItems = {}; + var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); @@ -46619,7 +67001,7 @@ var ts; // Anonymous items are never merged. return true; } - var itemsWithSameName = ts.getProperty(nameToItems, name); + var itemsWithSameName = nameToItems[name]; if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -46761,7 +67143,7 @@ var ts; case 179 /* FunctionExpression */: case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: - if (node.flags & 512 /* Default */) { + if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } return getFunctionOrClassName(node); @@ -46827,6 +67209,7 @@ var ts; case 147 /* MethodDeclaration */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: + case 218 /* VariableDeclaration */: return hasSomeImportantChild(item); case 180 /* ArrowFunction */: case 220 /* FunctionDeclaration */: @@ -46862,7 +67245,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -46873,7 +67256,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: nodeKind(n.node), + kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -46893,49 +67276,6 @@ var ts; return spans; } } - // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. - function nodeKind(node) { - switch (node.kind) { - case 256 /* SourceFile */: - return ts.ScriptElementKind.moduleElement; - case 255 /* EnumMember */: - return ts.ScriptElementKind.memberVariableElement; - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - var variableDeclarationNode = void 0; - var name_38; - if (node.kind === 169 /* BindingElement */) { - name_38 = node.name; - variableDeclarationNode = node; - // binding elements are added only for variable declarations - // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(!!variableDeclarationNode); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_38 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return ts.ScriptElementKind.constElement; - } - else if (ts.isLet(variableDeclarationNode)) { - return ts.ScriptElementKind.letElement; - } - else { - return ts.ScriptElementKind.variableElement; - } - case 180 /* ArrowFunction */: - return ts.ScriptElementKind.functionElement; - case 279 /* JSDocTypedefTag */: - return ts.ScriptElementKind.typeElement; - default: - return ts.getNodeKind(node); - } - } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. if (ts.isAmbientModule(moduleDeclaration)) { @@ -46979,7 +67319,7 @@ var ts; else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } - else if (node.flags & 512 /* Default */) { + else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } else { @@ -46993,6 +67333,168 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile) { + var elements = []; + var collapseText = "..."; + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + if (hintSpanNode && startElement && endElement) { + var span_12 = { + textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_12); + } + } + function addOutliningSpanComments(commentSpan, autoCollapse) { + if (commentSpan) { + var span_13 = { + textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span_13); + } + } + function addOutliningForLeadingCommentsForNode(n) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (comments) { + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var isFirstSingleLineComment = true; + var singleLineCommentCount = 0; + for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { + var currentComment = comments_4[_i]; + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { + if (isFirstSingleLineComment) { + firstSingleLineCommentStart = currentComment.pos; + } + isFirstSingleLineComment = false; + lastSingleLineCommentEnd = currentComment.end; + singleLineCommentCount++; + } + else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) { + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + addOutliningSpanComments(currentComment, /*autoCollapse*/ false); + singleLineCommentCount = 0; + lastSingleLineCommentEnd = -1; + isFirstSingleLineComment = true; + } + } + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + } + } + function combineAndAddMultipleSingleLineComments(count, start, end) { + // Only outline spans of two or more consecutive single line comments + if (count > 1) { + var multipleSingleLineComments = { + pos: start, + end: end, + kind: 2 /* SingleLineCommentTrivia */ + }; + addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); + } + } + function autoCollapse(node) { + return ts.isFunctionBlock(node) && node.parent.kind !== 180 /* ArrowFunction */; + } + var depth = 0; + var maxDepth = 20; + function walk(n) { + if (depth > maxDepth) { + return; + } + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n); + } + switch (n.kind) { + case 199 /* Block */: + if (!ts.isFunctionBlock(n)) { + var parent_22 = n.parent; + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + if (parent_22.kind === 204 /* DoStatement */ || + parent_22.kind === 207 /* ForInStatement */ || + parent_22.kind === 208 /* ForOfStatement */ || + parent_22.kind === 206 /* ForStatement */ || + parent_22.kind === 203 /* IfStatement */ || + parent_22.kind === 205 /* WhileStatement */ || + parent_22.kind === 212 /* WithStatement */ || + parent_22.kind === 252 /* CatchClause */) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + if (parent_22.kind === 216 /* TryStatement */) { + // Could be the try-block, or the finally-block. + var tryStatement = parent_22; + if (tryStatement.tryBlock === n) { + addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + break; + } + else if (tryStatement.finallyBlock === n) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + if (finallyKeyword) { + addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + break; + } + } + } + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + var span_14 = ts.createTextSpanFromBounds(n.getStart(), n.end); + elements.push({ + textSpan: span_14, + hintSpan: span_14, + bannerText: collapseText, + autoCollapse: autoCollapse(n) + }); + break; + } + // Fallthrough. + case 226 /* ModuleBlock */: { + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 224 /* EnumDeclaration */: + case 171 /* ObjectLiteralExpression */: + case 227 /* CaseBlock */: { + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 170 /* ArrayLiteralExpression */: + var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); + var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + break; + } + depth++; + ts.forEachChild(n, walk); + depth--; + } + walk(sourceFile); + return elements; + } + OutliningElementsCollector.collectElements = collectElements; + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. (function (PatternMatchKind) { @@ -47015,7 +67517,7 @@ var ts; // we see the name of a module that is used everywhere, or the name of an overload). As // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. - var stringToWordSpans = {}; + var stringToWordSpans = ts.createMap(); pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -47071,7 +67573,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -47087,7 +67589,7 @@ var ts; else { // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive // manner. If it does, return that there was a prefix match. - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -47102,10 +67604,10 @@ var ts; // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span = wordSpans_1[_i]; - if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + var span_15 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_15, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + /*isCaseSensitive:*/ partStartsWith(candidate, span_15, chunk.text, /*ignoreCase:*/ false)); } } } @@ -47353,14 +67855,6 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function startsWith(string, search) { - for (var i = 0, n = search.length; i < n; i++) { - if (string.charCodeAt(i) !== search.charCodeAt(i)) { - return false; - } - } - return true; - } // Assumes 'value' is already lowercase. function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { @@ -47558,6 +68052,434 @@ var ts; return transition; } })(ts || (ts = {})); +var ts; +(function (ts) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { + if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } + var referencedFiles = []; + var typeReferenceDirectives = []; + var importedFiles = []; + var ambientExternalModules; + var isNoDefaultLib = false; + var braceNesting = 0; + // assume that text represent an external module if it contains at least one top level import/export + // ambient modules that are found inside external modules are interpreted as module augmentations + var externalModule = false; + function nextToken() { + var token = ts.scanner.scan(); + if (token === 15 /* OpenBraceToken */) { + braceNesting++; + } + else if (token === 16 /* CloseBraceToken */) { + braceNesting--; + } + return token; + } + function processTripleSlashDirectives() { + var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); + ts.forEach(commentRanges, function (commentRange) { + var comment = sourceText.substring(commentRange.pos, commentRange.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); + if (referencePathMatchResult) { + isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var fileReference = referencePathMatchResult.fileReference; + if (fileReference) { + var collection = referencePathMatchResult.isTypeReferenceDirective + ? typeReferenceDirectives + : referencedFiles; + collection.push(fileReference); + } + } + }); + } + function getFileReference() { + var file = ts.scanner.getTokenValue(); + var pos = ts.scanner.getTokenPos(); + return { + fileName: file, + pos: pos, + end: pos + file.length + }; + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + } + function recordModuleName() { + importedFiles.push(getFileReference()); + markAsExternalModuleIfTopLevel(); + } + function markAsExternalModuleIfTopLevel() { + if (braceNesting === 0) { + externalModule = true; + } + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = ts.scanner.getToken(); + if (token === 122 /* DeclareKeyword */) { + // declare module "mod" + token = nextToken(); + if (token === 125 /* ModuleKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + var token = ts.scanner.getToken(); + if (token === 89 /* ImportKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 24 /* CommaToken */) { + // consume comma and keep going + token = nextToken(); + } + else { + // unknown syntax + return true; + } + } + if (token === 15 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 16 /* CloseBraceToken */) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = nextToken(); + if (token === 116 /* AsKeyword */) { + token = nextToken(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = ts.scanner.getToken(); + if (token === 82 /* ExportKeyword */) { + markAsExternalModuleIfTopLevel(); + token = nextToken(); + if (token === 15 /* OpenBraceToken */) { + token = nextToken(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = nextToken(); + } + if (token === 16 /* CloseBraceToken */) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = nextToken(); + if (token === 136 /* FromKeyword */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 89 /* ImportKeyword */) { + token = nextToken(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = nextToken(); + if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); + if (token === 129 /* RequireKeyword */) { + token = nextToken(); + if (token === 17 /* OpenParenToken */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = ts.scanner.getToken(); + if (token === 69 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + token = nextToken(); + if (token !== 17 /* OpenParenToken */) { + return true; + } + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = nextToken(); + if (token === 24 /* CommaToken */) { + token = nextToken(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 19 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = nextToken(); + var i = 0; + // scan until ']' or EOF + while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 9 /* StringLiteral */) { + recordModuleName(); + i++; + } + token = nextToken(); + } + return true; + } + return false; + } + function processImports() { + ts.scanner.setText(sourceText); + nextToken(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + // (for JavaScript files) require("mod") + while (true) { + if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { + break; + } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; + } + else { + nextToken(); + } + } + ts.scanner.setText(undefined); + } + if (readImportFiles) { + processImports(); + } + processTripleSlashDirectives(); + if (externalModule) { + // for external modules module all nested ambient modules are augmentations + if (ambientExternalModules) { + // move all detected ambient modules to imported files since they need to be resolved + for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { + var decl = ambientExternalModules_1[_i]; + importedFiles.push(decl.ref); + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; + } + else { + // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 + var ambientModuleNames = void 0; + if (ambientExternalModules) { + for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { + var decl = ambientExternalModules_2[_a]; + if (decl.depth === 0) { + if (!ambientModuleNames) { + ambientModuleNames = []; + } + ambientModuleNames.push(decl.ref.fileName); + } + else { + importedFiles.push(decl.ref); + } + } + } + return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; + } + } + ts.preProcessFile = preProcessFile; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var Rename; + (function (Rename) { + function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + if (node) { + if (node.kind === 69 /* Identifier */ || + node.kind === 9 /* StringLiteral */ || + ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + ts.isThis(node)) { + var symbol = typeChecker.getSymbolAtLocation(node); + // Only allow a symbol to be renamed if it actually has at least one declaration. + if (symbol) { + var declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + // Disallow rename for elements that are defined in the standard TypeScript library. + if (ts.forEach(declarations, isDefinedInLibraryFile)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + if (kind) { + return { + canRename: true, + kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + else if (node.kind === 9 /* StringLiteral */) { + var type = ts.getStringLiteralTypeForNode(node, typeChecker); + if (type) { + if (isDefinedInLibraryFile(node)) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); + } + else { + var displayName = ts.stripQuotes(type.text); + return { + canRename: true, + kind: ts.ScriptElementKind.variableElement, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: displayName, + kindModifiers: ts.ScriptElementKindModifier.none, + triggerSpan: createTriggerSpanForNode(node, sourceFile) + }; + } + } + } + } + } + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); + function getRenameInfoError(localizedErrorMessage) { + return { + canRename: false, + localizedErrorMessage: localizedErrorMessage, + displayName: undefined, + fullDisplayName: undefined, + kind: undefined, + kindModifiers: undefined, + triggerSpan: undefined + }; + } + function isDefinedInLibraryFile(declaration) { + if (defaultLibFileName) { + var sourceFile_1 = declaration.getSourceFile(); + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_1.fileName)); + if (canonicalName === canonicalDefaultLibName) { + return true; + } + } + return false; + } + function createTriggerSpanForNode(node, sourceFile) { + var start = node.getStart(sourceFile); + var width = node.getWidth(sourceFile); + if (node.kind === 9 /* StringLiteral */) { + // Exclude the quotes + start += 1; + width -= 2; + } + return ts.createTextSpan(start, width); + } + } + Rename.getRenameInfo = getRenameInfo; + })(Rename = ts.Rename || (ts.Rename = {})); +})(ts || (ts = {})); /// /* @internal */ var ts; @@ -47751,10 +68673,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = ts.getProperty(nameToDeclarations, name.text); + var declarations = nameToDeclarations[name.text]; if (declarations) { - for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { - var declaration = declarations_8[_b]; + for (var _b = 0, declarations_10 = declarations; _b < declarations_10.length; _b++) { + var declaration = declarations_10[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -48106,1084 +69028,637 @@ var ts; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); -// These utilities are common to multiple language service features. /* @internal */ var ts; (function (ts) { - function getLineStartPositionForPosition(position, sourceFile) { - var lineStarts = sourceFile.getLineStarts(); - var line = sourceFile.getLineAndCharacterOfPosition(position).line; - return lineStarts[line]; - } - ts.getLineStartPositionForPosition = getLineStartPositionForPosition; - function rangeContainsRange(r1, r2) { - return startEndContainsRange(r1.pos, r1.end, r2); - } - ts.rangeContainsRange = rangeContainsRange; - function startEndContainsRange(start, end, range) { - return start <= range.pos && end >= range.end; - } - ts.startEndContainsRange = startEndContainsRange; - function rangeContainsStartEnd(range, start, end) { - return range.pos <= start && range.end >= end; - } - ts.rangeContainsStartEnd = rangeContainsStartEnd; - function rangeOverlapsWithStartEnd(r1, start, end) { - return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); - } - ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; - function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { - var start = Math.max(start1, start2); - var end = Math.min(end1, end2); - return start < end; - } - ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; - function positionBelongsToNode(candidate, position, sourceFile) { - return candidate.end > position || !isCompletedNode(candidate, sourceFile); - } - ts.positionBelongsToNode = positionBelongsToNode; - function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { - return false; - } - switch (n.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 167 /* ObjectBindingPattern */: - case 159 /* TypeLiteral */: - case 199 /* Block */: - case 226 /* ModuleBlock */: - case 227 /* CaseBlock */: - case 233 /* NamedImports */: - case 237 /* NamedExports */: - return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 252 /* CatchClause */: - return isCompletedNode(n.block, sourceFile); - case 175 /* NewExpression */: - if (!n.arguments) { - return true; - } - // fall through - case 174 /* CallExpression */: - case 178 /* ParenthesizedExpression */: - case 164 /* ParenthesizedType */: - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - return isCompletedNode(n.type, sourceFile); - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 180 /* ArrowFunction */: - if (n.body) { - return isCompletedNode(n.body, sourceFile); - } - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - // Even though type parameters can be unclosed, we can get away with - // having at least a closing paren. - return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 225 /* ModuleDeclaration */: - return n.body && isCompletedNode(n.body, sourceFile); - case 203 /* IfStatement */: - if (n.elseStatement) { - return isCompletedNode(n.elseStatement, sourceFile); - } - return isCompletedNode(n.thenStatement, sourceFile); - case 202 /* ExpressionStatement */: - return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23 /* SemicolonToken */); - case 170 /* ArrayLiteralExpression */: - case 168 /* ArrayBindingPattern */: - case 173 /* ElementAccessExpression */: - case 140 /* ComputedPropertyName */: - case 161 /* TupleType */: - return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); - case 153 /* IndexSignature */: - if (n.type) { - return isCompletedNode(n.type, sourceFile); - } - return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: - // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed - return false; - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: - return isCompletedNode(n.statement, sourceFile); - case 204 /* DoStatement */: - // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); - case 158 /* TypeQuery */: - return isCompletedNode(n.exprName, sourceFile); - case 182 /* TypeOfExpression */: - case 181 /* DeleteExpression */: - case 183 /* VoidExpression */: - case 190 /* YieldExpression */: - case 191 /* SpreadElementExpression */: - var unaryWordExpression = n; - return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176 /* TaggedTemplateExpression */: - return isCompletedNode(n.template, sourceFile); - case 189 /* TemplateExpression */: - var lastSpan = ts.lastOrUndefined(n.templateSpans); - return isCompletedNode(lastSpan, sourceFile); - case 197 /* TemplateSpan */: - return ts.nodeIsPresent(n.literal); - case 236 /* ExportDeclaration */: - case 230 /* ImportDeclaration */: - return ts.nodeIsPresent(n.moduleSpecifier); - case 185 /* PrefixUnaryExpression */: - return isCompletedNode(n.operand, sourceFile); - case 187 /* BinaryExpression */: - return isCompletedNode(n.right, sourceFile); - case 188 /* ConditionalExpression */: - return isCompletedNode(n.whenFalse, sourceFile); - default: - return true; - } - } - ts.isCompletedNode = isCompletedNode; - /* - * Checks if node ends with 'expectedLastToken'. - * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. - */ - function nodeEndsWith(n, expectedLastToken, sourceFile) { - var children = n.getChildren(sourceFile); - if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { - return true; - } - else if (last.kind === 23 /* SemicolonToken */ && children.length !== 1) { - return children[children.length - 2].kind === expectedLastToken; + var SymbolDisplay; + (function (SymbolDisplay) { + // TODO(drosen): use contextual SemanticMeaning. + function getSymbolKind(typeChecker, symbol, location) { + var flags = symbol.getFlags(); + if (flags & 32 /* Class */) + return ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */) ? + ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + if (flags & 384 /* Enum */) + return ts.ScriptElementKind.enumElement; + if (flags & 524288 /* TypeAlias */) + return ts.ScriptElementKind.typeElement; + if (flags & 64 /* Interface */) + return ts.ScriptElementKind.interfaceElement; + if (flags & 262144 /* TypeParameter */) + return ts.ScriptElementKind.typeParameterElement; + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location); + if (result === ts.ScriptElementKind.unknown) { + if (flags & 262144 /* TypeParameter */) + return ts.ScriptElementKind.typeParameterElement; + if (flags & 8 /* EnumMember */) + return ts.ScriptElementKind.variableElement; + if (flags & 8388608 /* Alias */) + return ts.ScriptElementKind.alias; + if (flags & 1536 /* Module */) + return ts.ScriptElementKind.moduleElement; } + return result; } - return false; - } - function findListItemInfo(node) { - var list = findContainingList(node); - // It is possible at this point for syntaxList to be undefined, either if - // node.parent had no list child, or if none of its list children contained - // the span of node. If this happens, return undefined. The caller should - // handle this case. - if (!list) { - return undefined; - } - var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); - return { - listItemIndex: listItemIndex, - list: list - }; - } - ts.findListItemInfo = findListItemInfo; - function hasChildOfKind(n, kind, sourceFile) { - return !!findChildOfKind(n, kind, sourceFile); - } - ts.hasChildOfKind = hasChildOfKind; - function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); - } - ts.findChildOfKind = findChildOfKind; - function findContainingList(node) { - // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will - // be parented by the container of the SyntaxList, not the SyntaxList itself. - // In order to find the list item index, we first need to locate SyntaxList itself and then search - // for the position of the relevant node (or comma). - var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - // find syntax list that covers the span of the node - if (c.kind === 282 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { - return c; + SymbolDisplay.getSymbolKind = getSymbolKind; + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location) { + if (typeChecker.isUndefinedSymbol(symbol)) { + return ts.ScriptElementKind.variableElement; } - }); - // Either we didn't find an appropriate list, or the list must contain us. - ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); - return syntaxList; - } - ts.findContainingList = findContainingList; - /* Gets the token whose text has range [start, end) and - * position >= start and (position < end or (position === end && token is keyword or identifier)) - */ - function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); - } - ts.getTouchingWord = getTouchingWord; - /* Gets the token whose text has range [start, end) and position >= start - * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) - */ - function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); - } - ts.getTouchingPropertyName = getTouchingPropertyName; - /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); - } - ts.getTouchingToken = getTouchingToken; - /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); - } - ts.getTokenAtPosition = getTokenAtPosition; - /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - var current = sourceFile; - outer: while (true) { - if (isToken(current)) { - // exit early - return current; + if (typeChecker.isArgumentsSymbol(symbol)) { + return ts.ScriptElementKind.localVariableElement; } - if (includeJsDocComment) { - var jsDocChildren = ts.filter(current.getChildren(), ts.isJSDocNode); - for (var _i = 0, jsDocChildren_1 = jsDocChildren; _i < jsDocChildren_1.length; _i++) { - var jsDocChild = jsDocChildren_1[_i]; - var start = allowPositionInLeadingTrivia ? jsDocChild.getFullStart() : jsDocChild.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = jsDocChild.getEnd(); - if (position < end || (position === end && jsDocChild.kind === 1 /* EndOfFileToken */)) { - current = jsDocChild; - continue outer; + if (location.kind === 97 /* ThisKeyword */ && ts.isExpression(location)) { + return ts.ScriptElementKind.parameterElement; + } + if (flags & 3 /* Variable */) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return ts.ScriptElementKind.parameterElement; + } + else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return ts.ScriptElementKind.letElement; + } + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + if (flags & 32768 /* GetAccessor */) + return ts.ScriptElementKind.memberGetAccessorElement; + if (flags & 65536 /* SetAccessor */) + return ts.ScriptElementKind.memberSetAccessorElement; + if (flags & 8192 /* Method */) + return ts.ScriptElementKind.memberFunctionElement; + if (flags & 16384 /* Constructor */) + return ts.ScriptElementKind.constructorImplementationElement; + if (flags & 4 /* Property */) { + if (flags & 268435456 /* SyntheticProperty */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return ts.ScriptElementKind.memberVariableElement; } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, jsDocChild); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; + ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); + }); + if (!unionPropertyKind) { + // If this was union of all methods, + // make sure it has call signatures before we can label it as method + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return ts.ScriptElementKind.memberFunctionElement; + } + return ts.ScriptElementKind.memberVariableElement; + } + return unionPropertyKind; + } + return ts.ScriptElementKind.memberVariableElement; + } + return ts.ScriptElementKind.unknown; + } + function getSymbolModifiers(symbol) { + return symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : ts.ScriptElementKindModifier.none; + } + SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } + var displayParts = []; + var documentation; + var symbolFlags = symbol.flags; + var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); + var hasAddedSymbolInfo; + var isThisExpression = location.kind === 97 /* ThisKeyword */ && ts.isExpression(location); + var type; + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { + symbolKind = ts.ScriptElementKind.memberVariableElement; + } + var signature = void 0; + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (type) { + if (location.parent && location.parent.kind === 172 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpression = void 0; + if (location.kind === 174 /* CallExpression */ || location.kind === 175 /* NewExpression */) { + callExpression = location; + } + else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { + callExpression = location.parent; + } + if (callExpression) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); + if (!signature && candidateSignatures.length) { + // Use the first candidate: + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpression.kind === 175 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 8388608 /* Alias */) { + symbolKind = ts.ScriptElementKind.alias; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case ts.ScriptElementKind.memberVariableElement: + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.parameterElement: + case ts.ScriptElementKind.localVariableElement: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + if (!(type.flags & 2097152 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + } + addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || + (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 148 /* Constructor */)) { + // get the signature from the declaration and write it + var functionDeclaration = location.parent; + var allSignatures = functionDeclaration.kind === 148 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration.kind === 148 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = ts.ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + if (ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushTypePart(ts.ScriptElementKind.localClassElement); + } + else { + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(73 /* ClassKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(107 /* InterfaceKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if (symbolFlags & 524288 /* TypeAlias */) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); + } + if (symbolFlags & 384 /* Enum */) { + addNewLineIfDisplayPartsExist(); + if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + displayParts.push(ts.keywordPart(74 /* ConstKeyword */)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(81 /* EnumKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536 /* Module */) { + addNewLineIfDisplayPartsExist(); + var declaration = ts.getDeclarationOfKind(symbol, 225 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(90 /* InKeyword */)); + displayParts.push(ts.spacePart()); + if (symbol.parent) { + // Class/Interface type parameter + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + // Method/function type parameter + var declaration = ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 152 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 151 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + } + if (symbolFlags & 8 /* EnumMember */) { + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 255 /* EnumMember */) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); + } + } + } + if (symbolFlags & 8388608 /* Alias */) { + addNewLineIfDisplayPartsExist(); + if (symbol.declarations[0].kind === 228 /* NamespaceExportDeclaration */) { + displayParts.push(ts.keywordPart(82 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(126 /* NamespaceKeyword */)); + } + else { + displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 229 /* ImportEqualsDeclaration */) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== ts.ScriptElementKind.unknown) { + if (type) { + if (isThisExpression) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(97 /* ThisKeyword */)); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + // For properties, variables and local vars: show the type + if (symbolKind === ts.ScriptElementKind.memberVariableElement || + symbolFlags & 3 /* Variable */ || + symbolKind === ts.ScriptElementKind.localVariableElement || + isThisExpression) { + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.spacePart()); + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === ts.ScriptElementKind.memberFunctionElement) { + var allSignatures = type.getNonNullableType().getCallSignatures(); + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + else { + symbolKind = getSymbolKind(typeChecker, symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(); + if (documentation.length === 0 && symbol.flags & 4 /* Property */) { + // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` + // there documentation comments might be attached to the right hand side symbol of their declarations. + // The pattern of such special property access is that the parent symbol is the symbol of the file. + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256 /* SourceFile */; })) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!declaration.parent || declaration.parent.kind !== 187 /* BinaryExpression */) { + continue; + } + var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; } } } } } - // find the child that contains 'position' - for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { - var child = current.getChildAt(i); - // all jsDocComment nodes were already visited - if (ts.isJSDocNode(child)) { - continue; - } - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); - if (start <= position) { - var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { - current = child; - continue outer; - } - else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { - return previousToken; - } - } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + function addNewLineIfDisplayPartsExist() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); } } - return current; - } - } - /** - * The token on the left of the position is the token that strictly includes the position - * or sits to the left of the cursor if it is on a boundary. For example - * - * fo|o -> will return foo - * foo |bar -> will return foo - * - */ - function findTokenOnLeftOfPosition(file, position) { - // Ideally, getTokenAtPosition should return a token. However, it is currently - // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position); - if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { - return tokenAtPosition; - } - return findPrecedingToken(position, file); - } - ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { - return find(parent); - function find(n) { - if (isToken(n) && n.pos === previousToken.end) { - // this is token that starts at the end of previous token - return it - return n; + function addFullSymbolName(symbol, enclosingDeclaration) { + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + ts.addRange(displayParts, fullSymbolDisplayParts); } - var children = n.getChildren(); - for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { - var child = children_1[_i]; - var shouldDiveInChildNode = - // previous token is enclosed somewhere in the child - (child.pos <= previousToken.pos && child.end > previousToken.end) || - // previous token ends exactly at the beginning of child - (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { - return find(child); + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + addNewLineIfDisplayPartsExist(); + if (symbolKind) { + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); } } - return undefined; - } - } - ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { - return find(startNode || sourceFile); - function findRightmostToken(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { - return n; - } - var children = n.getChildren(); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); - return candidate && findRightmostToken(candidate); - } - function find(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { - return n; - } - var children = n.getChildren(); - for (var i = 0, len = children.length; i < len; i++) { - var child = children[i]; - // condition 'position < child.end' checks if child node end after the position - // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' - // aaaa___bbbb___$__ccc - // after we found child node with end after the position we check if start of the node is after the position. - // if yes - then position is in the trivia and we need to look into the previous child to find the token in question. - // if no - position is in the node itself so we should recurse in it. - // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). - // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 244 /* JsxText */)) { - var start = child.getStart(sourceFile); - var lookInPreviousChild = (start >= position) || - (child.kind === 244 /* JsxText */ && start === child.end); // whitespace only JsxText - if (lookInPreviousChild) { - // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); - return candidate && findRightmostToken(candidate); - } - else { - // candidate should be in this node - return find(child); - } + function pushTypePart(symbolKind) { + switch (symbolKind) { + case ts.ScriptElementKind.variableElement: + case ts.ScriptElementKind.functionElement: + case ts.ScriptElementKind.letElement: + case ts.ScriptElementKind.constElement: + case ts.ScriptElementKind.constructorImplementationElement: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + return; } } - ts.Debug.assert(startNode !== undefined || n.kind === 256 /* SourceFile */); - // Here we know that none of child token nodes embrace the position, - // the only known case is when position is at the end of the file. - // Try to find the rightmost token in the file without filtering. - // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); - return candidate && findRightmostToken(candidate); - } - } - /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { - for (var i = exclusiveStartPosition - 1; i >= 0; i--) { - if (nodeHasTokens(children[i])) { - return children[i]; + function addSignatureDisplayParts(signature, allSignatures, flags) { + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(35 /* PlusToken */)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); } + documentation = signature.getDocumentationComment(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); } } - } - ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 /* StringLiteral */ || previousToken.kind === 166 /* StringLiteralType */)) { - var start = previousToken.getStart(); - var end = previousToken.getEnd(); - // To be "in" one of these literals, the position has to be: - // 1. entirely within the token text. - // 2. at the end position of an unterminated token. - // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start < position && position < end) { - return true; + SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; // This is exported symbol } - if (position === end) { - return !!previousToken.isUnterminated; - } - } - return false; - } - ts.isInString = isInString; - function isInComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); - } - ts.isInComment = isInComment; - /** - * returns true if the position is in between the open and close elements of an JSX expression. - */ - function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - if (!token) { - return false; - } - if (token.kind === 244 /* JsxText */) { - return true; - } - //
Hello |
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { - return true; - } - //
{ |
or
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { - return true; - } - //
{ - // | - // } < /div> - if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { - return true; - } - //
|
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { - return true; - } - return false; - } - ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; - function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); - } - ts.isInTemplateString = isInTemplateString; - /** - * Returns true if the cursor at position in sourceFile is within a comment that additionally - * satisfies predicate, and false otherwise. - */ - function isInCommentHelper(sourceFile, position, predicate) { - var token = getTokenAtPosition(sourceFile, position); - if (token && position <= token.getStart(sourceFile)) { - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - // The end marker of a single-line comment does not include the newline character. - // In the following case, we are inside a comment (^ denotes the cursor position): - // - // // asdf ^\n - // - // But for multi-line comments, we don't want to be inside the comment in the following case: - // - // /* asdf */^ - // - // Internally, we represent the end of the comment at the newline and closing '/', respectively. - return predicate ? - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && - predicate(c); }) : - ts.forEach(commentRanges, function (c) { return c.pos < position && - (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); - } - return false; - } - ts.isInCommentHelper = isInCommentHelper; - function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); - // First, we have to see if this position actually landed in a comment. - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return ts.forEach(commentRanges, jsDocPrefix); - function jsDocPrefix(c) { - var text = sourceFile.text; - return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; - } - } - ts.hasDocComment = hasDocComment; - /** - * Get the corresponding JSDocTag node if the position is in a jsDoc comment - */ - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (isToken(node)) { - switch (node.kind) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - // if the current token is var, let or const, skip the VariableDeclarationList - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } + return ts.forEach(symbol.declarations, function (declaration) { + // Function expressions are local + if (declaration.kind === 179 /* FunctionExpression */) { + return true; } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; - function nodeHasTokens(n) { - // If we have a token or node that has a non-zero width, it must have tokens. - // Note, that getWidth() does not take trivia into account. - return n.getWidth() !== 0; - } - function getNodeModifiers(node) { - var flags = ts.getCombinedNodeFlags(node); - var result = []; - if (flags & 8 /* Private */) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 16 /* Protected */) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 4 /* Public */) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 32 /* Static */) - result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 128 /* Abstract */) - result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1 /* Export */) - result.push(ts.ScriptElementKindModifier.exportedModifier); - if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; - } - ts.getNodeModifiers = getNodeModifiers; - function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 /* TypeReference */ || node.kind === 174 /* CallExpression */) { - return node.typeArguments; - } - if (ts.isFunctionLike(node) || node.kind === 221 /* ClassDeclaration */ || node.kind === 222 /* InterfaceDeclaration */) { - return node.typeParameters; - } - return undefined; - } - ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; - function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 138 /* LastToken */; - } - ts.isToken = isToken; - function isWord(kind) { - return kind === 69 /* Identifier */ || ts.isKeyword(kind); - } - ts.isWord = isWord; - function isPropertyName(kind) { - return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); - } - function isComment(kind) { - return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; - } - ts.isComment = isComment; - function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 /* StringLiteral */ - || kind === 166 /* StringLiteralType */ - || kind === 10 /* RegularExpressionLiteral */ - || ts.isTemplateLiteralKind(kind)) { - return true; - } - return false; - } - ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; - function isPunctuation(kind) { - return 15 /* FirstPunctuation */ <= kind && kind <= 68 /* LastPunctuation */; - } - ts.isPunctuation = isPunctuation; - function isInsideTemplateLiteral(node, position) { - return ts.isTemplateLiteralKind(node.kind) - && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); - } - ts.isInsideTemplateLiteral = isInsideTemplateLiteral; - function isAccessibilityModifier(kind) { - switch (kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return true; - } - return false; - } - ts.isAccessibilityModifier = isAccessibilityModifier; - function compareDataObjects(dst, src) { - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { + if (declaration.kind !== 218 /* VariableDeclaration */ && declaration.kind !== 220 /* FunctionDeclaration */) { return false; } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; + // If the parent is not sourceFile or module block it is local variable + for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { + // Reached source file or module block + if (parent_23.kind === 256 /* SourceFile */ || parent_23.kind === 226 /* ModuleBlock */) { + return false; + } } - } + // parent is in function block + return true; + }); } - return true; - } - ts.compareDataObjects = compareDataObjects; - function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 /* ArrayLiteralExpression */ || - node.kind === 171 /* ObjectLiteralExpression */) { - // [a,b,c] from: - // [a, b, c] = someExpression; - if (node.parent.kind === 187 /* BinaryExpression */ && - node.parent.left === node && - node.parent.operatorToken.kind === 56 /* EqualsToken */) { - return true; - } - // [a, b, c] from: - // for([a, b, c] of expression) - if (node.parent.kind === 208 /* ForOfStatement */ && - node.parent.initializer === node) { - return true; - } - // [a, b, c] of - // [x, [a, b, c] ] = someExpression - // or - // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { - return true; - } - } - return false; - } - ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; + })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {})); })(ts || (ts = {})); -// Display-part writer helpers -/* @internal */ var ts; (function (ts) { - function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; - } - ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; - var displayPartWriter = getDisplayPartWriter(); - function getDisplayPartWriter() { - var displayParts; - var lineStart; - var indent; - resetWriter(); - return { - displayParts: function () { return displayParts; }, - writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, - writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, - writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, - writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, - writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, - writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, - writeSymbol: writeSymbol, - writeLine: writeLine, - increaseIndent: function () { indent++; }, - decreaseIndent: function () { indent--; }, - clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } - }; - function writeIndent() { - if (lineStart) { - var indentString = ts.getIndentString(indent); - if (indentString) { - displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); - } - lineStart = false; - } - } - function writeKind(text, kind) { - writeIndent(); - displayParts.push(displayPart(text, kind)); - } - function writeSymbol(text, symbol) { - writeIndent(); - displayParts.push(symbolPart(text, symbol)); - } - function writeLine() { - displayParts.push(lineBreakPart()); - lineStart = true; - } - function resetWriter() { - displayParts = []; - lineStart = true; - indent = 0; - } - } - function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); - function displayPartKind(symbol) { - var flags = symbol.flags; - if (flags & 3 /* Variable */) { - return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; - } - else if (flags & 4 /* Property */) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 32768 /* GetAccessor */) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 65536 /* SetAccessor */) { - return ts.SymbolDisplayPartKind.propertyName; - } - else if (flags & 8 /* EnumMember */) { - return ts.SymbolDisplayPartKind.enumMemberName; - } - else if (flags & 16 /* Function */) { - return ts.SymbolDisplayPartKind.functionName; - } - else if (flags & 32 /* Class */) { - return ts.SymbolDisplayPartKind.className; - } - else if (flags & 64 /* Interface */) { - return ts.SymbolDisplayPartKind.interfaceName; - } - else if (flags & 384 /* Enum */) { - return ts.SymbolDisplayPartKind.enumName; - } - else if (flags & 1536 /* Module */) { - return ts.SymbolDisplayPartKind.moduleName; - } - else if (flags & 8192 /* Method */) { - return ts.SymbolDisplayPartKind.methodName; - } - else if (flags & 262144 /* TypeParameter */) { - return ts.SymbolDisplayPartKind.typeParameterName; - } - else if (flags & 524288 /* TypeAlias */) { - return ts.SymbolDisplayPartKind.aliasName; - } - else if (flags & 8388608 /* Alias */) { - return ts.SymbolDisplayPartKind.aliasName; - } - return ts.SymbolDisplayPartKind.text; - } - } - ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] - }; - } - ts.displayPart = displayPart; - function spacePart() { - return displayPart(" ", ts.SymbolDisplayPartKind.space); - } - ts.spacePart = spacePart; - function keywordPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); - } - ts.keywordPart = keywordPart; - function punctuationPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); - } - ts.punctuationPart = punctuationPart; - function operatorPart(kind) { - return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); - } - ts.operatorPart = operatorPart; - function textOrKeywordPart(text) { - var kind = ts.stringToToken(text); - return kind === undefined - ? textPart(text) - : keywordPart(kind); - } - ts.textOrKeywordPart = textOrKeywordPart; - function textPart(text) { - return displayPart(text, ts.SymbolDisplayPartKind.text); - } - ts.textPart = textPart; - var carriageReturnLineFeed = "\r\n"; - /** - * The default is CRLF. + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; - } - ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; - function lineBreakPart() { - return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); - } - ts.lineBreakPart = lineBreakPart; - function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; - } - ts.mapToDisplayParts = mapToDisplayParts; - function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - }); - } - ts.typeToDisplayParts = typeToDisplayParts; - function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { - return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); - }); - } - ts.symbolToDisplayParts = symbolToDisplayParts; - function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); - }); - } - ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location)) { - return location.getText(); + function transpileModule(input, transpileOptions) { + var diagnostics = []; + var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); + options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; + // Filename can be non-ts file. + options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + // if jsx is specified then treat file as .tsx + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140 /* ComputedPropertyName */) { - return location.text; + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); - return name; + var newLine = ts.getNewLineCharacter(options); + // Output + var outputText; + var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files + var compilerHost = { + getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text, writeByteOrderMark) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + sourceMapText = text; + } + else { + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } + }; + var program = ts.createProgram([inputFileName], options, compilerHost); + if (transpileOptions.reportDiagnostics) { + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } + // Emit + program.emit(); + ts.Debug.assert(outputText !== undefined, "Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } - ts.getDeclaredName = getDeclaredName; - function isImportOrExportSpecifierName(location) { - return location.parent && - (location.parent.kind === 234 /* ImportSpecifier */ || location.parent.kind === 238 /* ExportSpecifier */) && - location.parent.propertyName === location; - } - ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; - /** - * Strip off existed single quotes or double quotes from a given string - * - * @return non-quoted string + ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. */ - function stripQuotes(name) { - var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { - return name.substring(1, length - 1); - } - ; - return name; + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; } - ts.stripQuotes = stripQuotes; - function scriptKindIs(fileName, host) { - var scriptKinds = []; - for (var _i = 2; _i < arguments.length; _i++) { - scriptKinds[_i - 2] = arguments[_i]; + ts.transpile = transpile; + var commandLineOptionsStringToEnum; + /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ + function fixupCompilerOptions(options, diagnostics) { + // Lazily create this value to fix module loading errors. + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); + }); + options = ts.clone(options); + var _loop_2 = function (opt) { + if (!ts.hasProperty(options, opt.name)) { + return "continue"; + } + var value = options[opt.name]; + // Value should be a key of opt.type + if (typeof value === "string") { + // If value is not a string, this will fail + options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); + } + else { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { + // Supplied value isn't a valid enum value. + diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + }; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; + _loop_2(opt); } - var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return options; } - ts.scriptKindIs = scriptKindIs; - function getScriptKind(fileName, host) { - // First check to see if the script kind was specified by the host. Chances are the host - // may override the default script kind for the file extension. - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind || scriptKind === 0 /* Unknown */) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); - } - ts.getScriptKind = getScriptKind; -})(ts || (ts = {})); -// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. -// See LICENSE.txt in the project root for complete license information. -/// -/* @internal */ -var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - // A map of loose file names to library names - // that we are confident require typings - var safeList; - /** - * @param host is the object providing I/O related operations. - * @param fileNames are the file names that belong to the same project - * @param projectRootPath is the path to the project root directory - * @param safeListPath is the path used to retrieve the safe list - * @param packageNameToTypingLocation is the map of package names to their cached typing locations - * @param typingOptions are used to customize the typing inference process - * @param compilerOptions are used as a source for typing inference - */ - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - // A typing name to typing file path mapping - var inferredTypings = {}; - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - if (result.config) { - safeList = result.config; - } - else { - safeList = {}; - } - ; - } - var filesToWatch = []; - // Directories to search for package.json, bower.json and other typing information - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - // Add the cached typing locations for inferred typings that are already installed - for (var name_39 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { - inferredTypings[name_39] = packageNameToTypingLocation[name_39]; - } - } - // Remove typings that the user has added to the exclude list - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - /** - * Merge a given list of typingNames to the inferredTypings map - */ - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { - inferredTypings[typing] = undefined; - } - } - } - /** - * Get the typing info from common package manager json files like package.json or bower.json - */ - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); - } - } - } - /** - * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" - * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred - * to the 'angular-route' typing name. - * @param fileNames are the names for source files in the project - */ - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - /** - * Infer typing names from node_module folder - * @param nodeModulesPath is the path to the "node_modules" folder - */ - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - // Todo: add support for ModuleResolutionHost too - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; - var normalizedFileName = ts.normalizePath(fileName); - if (ts.getBaseFileName(normalizedFileName) !== "package.json") { - continue; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - // npm 3's package.json contains a "_requiredBy" field - // we should include all the top level module names for npm 2, and only module names whose - // "_requiredBy" field starts with "#" or equals "/" for npm 3. - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used - // to download d.ts files from DefinitelyTyped - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /// /// @@ -49205,6 +69680,7 @@ var ts; ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); function getFormattingScanner(sourceFile, startPos, endPos) { ts.Debug.assert(scanner === undefined); @@ -49296,6 +69772,9 @@ var ts; } return false; } + function shouldRescanJsxText(node) { + return node && node.kind === 244 /* JsxText */; + } function shouldRescanSlashToken(container) { return container.kind === 10 /* RegularExpressionLiteral */; } @@ -49326,7 +69805,9 @@ var ts; ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ - : 0 /* Scan */; + : shouldRescanJsxText(n) + ? 5 /* RescanJsxText */ + : 0 /* Scan */; if (lastTokenInfo && expectedScanAction === lastScanAction) { // readTokenInfo was called before with the same expected scan action. // No need to re-scan text, return existing 'lastTokenInfo' @@ -49361,6 +69842,10 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4 /* RescanJsxIdentifier */; } + else if (expectedScanAction === 5 /* RescanJsxText */) { + currentToken = scanner.reScanJsxToken(); + lastScanAction = 5 /* RescanJsxText */; + } else { lastScanAction = 0 /* Scan */; } @@ -49664,9 +70149,9 @@ var ts; } return true; }; - RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); + RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -49716,6 +70201,8 @@ var ts; // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); // Insert new line after { and before } in multi-line contexts. this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); @@ -49750,7 +70237,7 @@ var ts; this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} @@ -49781,7 +70268,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); // Remove spaces in empty interface literals. e.g.: x: {} this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); // decorators @@ -49797,6 +70283,12 @@ var ts; this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + // jsx opening element + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39 /* SlashToken */, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, @@ -49811,7 +70303,7 @@ var ts; this.SpaceAfterPostdecrementWhenFollowedBySubtract, this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, this.NoSpaceAfterCloseBrace, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, @@ -49824,6 +70316,8 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, + this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, + this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, // TypeScript-specific rules this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, @@ -49837,7 +70331,6 @@ var ts; this.NoSpaceAfterOpenAngularBracket, this.NoSpaceBeforeCloseAngularBracket, this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, this.SpaceBeforeAt, this.NoSpaceAfterAt, this.SpaceAfterDecorator, @@ -49857,8 +70350,8 @@ var ts; /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); // Insert space before and after binary operators this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -49895,19 +70388,22 @@ var ts; this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); + // No space after type assertion + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_40 in o) { - if (o[name_40] === rule) { - return name_40; + for (var name_51 in o) { + if (o[name_51] === rule) { + return name_51; } } throw new Error("Unknown rule"); @@ -50110,12 +70606,21 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244 /* JsxText */; }; - Rules.isNonJsxElementContext = function (context) { + Rules.IsNonJsxElementContext = function (context) { return context.contextNode.kind !== 241 /* JsxElement */; }; - Rules.isJsxExpressionContext = function (context) { + Rules.IsJsxExpressionContext = function (context) { return context.contextNode.kind === 248 /* JsxExpression */; }; + Rules.IsNextTokenParentJsxAttribute = function (context) { + return context.nextTokenParent.kind === 246 /* JsxAttribute */; + }; + Rules.IsJsxAttributeContext = function (context) { + return context.contextNode.kind === 246 /* JsxAttribute */; + }; + Rules.IsJsxSelfClosingElementContext = function (context) { + return context.contextNode.kind === 242 /* JsxSelfClosingElement */; + }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -50126,7 +70631,7 @@ var ts; !Rules.NodeIsInDecoratorContext(context.nextTokenParent); }; Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isExpression(node)) { + while (ts.isPartOfExpression(node)) { node = node.parent; } return node.kind === 143 /* Decorator */; @@ -50439,21 +70944,21 @@ var ts; TokenRange.prototype.toString = function () { return this.tokenAccess.toString(); }; - TokenRange.Any = TokenRange.AllTokens(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 138 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 138 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 130 /* NumberKeyword */, 132 /* StringKeyword */, 120 /* BooleanKeyword */, 133 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); return TokenRange; }()); + TokenRange.Any = TokenRange.AllTokens(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 138 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 138 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 130 /* NumberKeyword */, 132 /* StringKeyword */, 120 /* BooleanKeyword */, 133 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -50538,6 +71043,18 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true + // so if the option is undefined, we should treat it as true as well + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + rules.push(this.globalRules.SpaceAfterOpenBrace); + rules.push(this.globalRules.SpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } + else { + rules.push(this.globalRules.NoSpaceAfterOpenBrace); + rules.push(this.globalRules.NoSpaceBeforeCloseBrace); + rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); + } if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); @@ -50575,6 +71092,12 @@ var ts; rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } + if (options.InsertSpaceAfterTypeAssertion) { + rules.push(this.globalRules.SpaceAfterTypeAssertion); + } + else { + rules.push(this.globalRules.NoSpaceAfterTypeAssertion); + } rules = rules.concat(this.globalRules.LowPriorityCommonRules); return rules; }; @@ -50918,8 +71441,9 @@ var ts; case 147 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; - } - // fall-through + } /* + fall-through + */ case 145 /* PropertyDeclaration */: case 142 /* Parameter */: return node.name.kind; @@ -51673,7 +72197,7 @@ var ts; // actual indentation is used for statements\declarations if one of cases below is true: // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line - var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && (parent.kind === 256 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; @@ -51951,101 +72475,49 @@ var ts; })(ts || (ts = {})); /// /// +/// +/// /// -/// +/// +/// +/// +/// +/// +/// +/// +/// +/// /// /// +/// /// +/// +/// /// -/// -/// +/// +/// /// /// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; - var ScriptSnapshot; - (function (ScriptSnapshot) { - var StringScriptSnapshot = (function () { - function StringScriptSnapshot(text) { - this.text = text; - } - StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringScriptSnapshot.prototype.getLength = function () { - return this.text.length; - }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { - // Text-based snapshots do not support incremental parsing. Return undefined - // to signal that to the caller. - return undefined; - }; - return StringScriptSnapshot; - }()); - function fromString(text) { - return new StringScriptSnapshot(text); - } - ScriptSnapshot.fromString = fromString; - })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var emptyArray = []; - var jsDocTagNames = [ - "augments", - "author", - "argument", - "borrows", - "class", - "constant", - "constructor", - "constructs", - "default", - "deprecated", - "description", - "event", - "example", - "extends", - "field", - "fileOverview", - "function", - "ignore", - "inner", - "lends", - "link", - "memberOf", - "name", - "namespace", - "param", - "private", - "property", - "public", - "requires", - "returns", - "see", - "since", - "static", - "throws", - "type", - "typedef", - "property", - "prop", - "version" - ]; - var jsDocCompletionEntries; - function createNode(kind, pos, end, flags, parent) { - var node = new NodeObject(kind, pos, end); - node.flags = flags; + function createNode(kind, pos, end, parent) { + var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : + kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + new TokenObject(kind, pos, end); node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { - this.kind = kind; this.pos = pos; this.end = end; this.flags = 0 /* None */; + this.transformFlags = undefined; + this.excludeTransformFlags = undefined; this.parent = undefined; + this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -52072,22 +72544,25 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { - scanner.setTextPos(pos); + ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); - var textPos = scanner.getTextPos(); + var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, 0, this)); + nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); + var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -52107,16 +72582,19 @@ var ts; var _this = this; var children; if (this.kind >= 139 /* FirstNode */) { - scanner.setText((sourceFile || this.getSourceFile()).text); + ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 281 /* LastJSDocTagNode */; + var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 285 /* LastJSDocTagNode */; var processNode = function (node) { - if (pos_3 < node.pos) { + var isJSDocTagNode = ts.isJSDocTag(node); + if (!isJSDocTagNode && pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - pos_3 = node.end; + if (!isJSDocTagNode) { + pos_3 = node.end; + } }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -52132,13 +72610,17 @@ var ts; processNode(jsDocComment); } } + // For syntactic classifications, all trivia are classcified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos_3 = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos_3 < this.end) { this.addSyntheticNodes(children, pos_3, this.end); } - scanner.setText(undefined); + ts.scanner.setText(undefined); } - this._children = children || emptyArray; + this._children = children || ts.emptyArray; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -52173,6 +72655,58 @@ var ts; }; return NodeObject; }()); + var TokenOrIdentifierObject = (function () { + function TokenOrIdentifierObject(pos, end) { + // Set properties in same order as NodeObject + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } + TokenOrIdentifierObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); + }; + TokenOrIdentifierObject.prototype.getFullStart = function () { + return this.pos; + }; + TokenOrIdentifierObject.prototype.getEnd = function () { + return this.end; + }; + TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + TokenOrIdentifierObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + TokenOrIdentifierObject.prototype.getText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + }; + TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + return 0; + }; + TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + return ts.emptyArray; + }; + TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + return undefined; + }; + TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + return undefined; + }; + return TokenOrIdentifierObject; + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -52189,301 +72723,28 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4 /* Property */)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4 /* Property */)); } return this.documentationComment; }; return SymbolObject; }()); - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { - var documentationComment = []; - var docComments = getJsDocCommentsSeparatedByNewLines(); - ts.forEach(docComments, function (docComment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(docComment); - }); - return documentationComment; - function getJsDocCommentsSeparatedByNewLines() { - var paramTag = "@param"; - var jsDocCommentParts = []; - ts.forEach(declarations, function (declaration, indexOfDeclaration) { - // Make sure we are collecting doc comment from declaration once, - // In case of union property there might be same declaration multiple times - // which only varies in type parameter - // Eg. const a: Array | Array; a.length - // The property length will have two declarations of property length coming - // from Array - Array and Array - if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); - // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments - if (canUseParsedParamTagComments && declaration.kind === 142 /* Parameter */) { - if ((declaration.parent.kind === 179 /* FunctionExpression */ || declaration.parent.kind === 180 /* ArrowFunction */) && - declaration.parent.parent.kind === 218 /* VariableDeclaration */) { - addCommentParts(declaration.parent.parent.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); - } - // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body && declaration.body.kind === 225 /* ModuleDeclaration */) { - return; - } - if ((declaration.kind === 179 /* FunctionExpression */ || declaration.kind === 180 /* ArrowFunction */) && - declaration.parent.kind === 218 /* VariableDeclaration */) { - addCommentParts(declaration.parent.parent, sourceFileOfDeclaration, getCleanedJsDocComment); - } - // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 225 /* ModuleDeclaration */ && declaration.parent.kind === 225 /* ModuleDeclaration */) { - declaration = declaration.parent; - } - addCommentParts(declaration.kind === 218 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration, getCleanedJsDocComment); - if (declaration.kind === 218 /* VariableDeclaration */) { - var init = declaration.initializer; - if (init && (init.kind === 179 /* FunctionExpression */ || init.kind === 180 /* ArrowFunction */)) { - // Get the cleaned js doc comment text from the initializer - addCommentParts(init, sourceFileOfDeclaration, getCleanedJsDocComment); - } - } - } - }); - return jsDocCommentParts; - function addCommentParts(commented, sourceFileOfDeclaration, getCommentPart) { - var ranges = getJsDocCommentTextRange(commented, sourceFileOfDeclaration); - // Get the cleaned js doc comment text from the declaration - ts.forEach(ranges, function (jsDocCommentTextRange) { - var cleanedComment = getCommentPart(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); - if (cleanedComment) { - ts.addRange(jsDocCommentParts, cleanedComment); - } - }); - } - function getJsDocCommentTextRange(node, sourceFile) { - return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { - return { - pos: jsDocComment.pos + "/*".length, - end: jsDocComment.end - "*/".length // Trim off comment end indicator - }; - }); - } - function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { - if (maxSpacesToRemove !== undefined) { - end = Math.min(end, pos + maxSpacesToRemove); - } - for (; pos < end; pos++) { - var ch = sourceFile.text.charCodeAt(pos); - if (!ts.isWhiteSpaceSingleLine(ch)) { - return pos; - } - } - return end; - } - function consumeLineBreaks(pos, end, sourceFile) { - while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function isName(pos, end, sourceFile, name) { - return pos + name.length < end && - sourceFile.text.substr(pos, name.length) === name && - ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)); - } - function isParamTag(pos, end, sourceFile) { - // If it is @param tag - return isName(pos, end, sourceFile, paramTag); - } - function pushDocCommentLineText(docComments, text, blankLineCount) { - // Add the empty lines in between texts - while (blankLineCount) { - blankLineCount--; - docComments.push(ts.textPart("")); - } - docComments.push(ts.textPart(text)); - } - function getCleanedJsDocComment(pos, end, sourceFile) { - var spacesToRemoveAfterAsterisk; - var docComments = []; - var blankLineCount = 0; - var isInParamTag = false; - while (pos < end) { - var docCommentTextOfLine = ""; - // First consume leading white space - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); - // If the comment starts with '*' consume the spaces on this line - if (pos < end && sourceFile.text.charCodeAt(pos) === 42 /* asterisk */) { - var lineStartPos = pos + 1; - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); - // Set the spaces to remove after asterisk as margin if not already set - if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - spacesToRemoveAfterAsterisk = pos - lineStartPos; - } - } - else if (spacesToRemoveAfterAsterisk === undefined) { - spacesToRemoveAfterAsterisk = 0; - } - // Analyze text on this line - while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { - var ch = sourceFile.text.charAt(pos); - if (ch === "@") { - // If it is @param tag - if (isParamTag(pos, end, sourceFile)) { - isInParamTag = true; - pos += paramTag.length; - continue; - } - else { - isInParamTag = false; - } - } - // Add the ch to doc text if we arent in param tag - if (!isInParamTag) { - docCommentTextOfLine += ch; - } - // Scan next character - pos++; - } - // Continue with next line - pos = consumeLineBreaks(pos, end, sourceFile); - if (docCommentTextOfLine) { - pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); - blankLineCount = 0; - } - else if (!isInParamTag && docComments.length) { - // This is blank line when there is text already parsed - blankLineCount++; - } - } - return docComments; - } - function getCleanedParamJsDocComment(pos, end, sourceFile) { - var paramHelpStringMargin; - var paramDocComments = []; - while (pos < end) { - if (isParamTag(pos, end, sourceFile)) { - var blankLineCount = 0; - var recordedParamTag = false; - // Consume leading spaces - pos = consumeWhiteSpaces(pos + paramTag.length); - if (pos >= end) { - break; - } - // Ignore type expression - if (sourceFile.text.charCodeAt(pos) === 123 /* openBrace */) { - pos++; - for (var curlies = 1; pos < end; pos++) { - var charCode = sourceFile.text.charCodeAt(pos); - // { character means we need to find another } to match the found one - if (charCode === 123 /* openBrace */) { - curlies++; - continue; - } - // } char - if (charCode === 125 /* closeBrace */) { - curlies--; - if (curlies === 0) { - // We do not have any more } to match the type expression is ignored completely - pos++; - break; - } - else { - // there are more { to be matched with } - continue; - } - } - // Found start of another tag - if (charCode === 64 /* at */) { - break; - } - } - // Consume white spaces - pos = consumeWhiteSpaces(pos); - if (pos >= end) { - break; - } - } - // Parameter name - if (isName(pos, end, sourceFile, name)) { - // Found the parameter we are looking for consume white spaces - pos = consumeWhiteSpaces(pos + name.length); - if (pos >= end) { - break; - } - var paramHelpString = ""; - var firstLineParamHelpStringPos = pos; - while (pos < end) { - var ch = sourceFile.text.charCodeAt(pos); - // at line break, set this comment line text and go to next line - if (ts.isLineBreak(ch)) { - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - paramHelpString = ""; - blankLineCount = 0; - recordedParamTag = true; - } - else if (recordedParamTag) { - blankLineCount++; - } - // Get the pos after cleaning start of the line - setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); - continue; - } - // Done scanning param help string - next tag found - if (ch === 64 /* at */) { - break; - } - paramHelpString += sourceFile.text.charAt(pos); - // Go to next character - pos++; - } - // If there is param help text, add it top the doc comments - if (paramHelpString) { - pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); - } - paramHelpStringMargin = undefined; - } - // If this is the start of another tag, continue with the loop in search of param tag with symbol name - if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { - continue; - } - } - // Next character - pos++; - } - return paramDocComments; - function consumeWhiteSpaces(pos) { - while (pos < end && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { - pos++; - } - return pos; - } - function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { - // Get the pos after consuming line breaks - pos = consumeLineBreaks(pos, end, sourceFile); - if (pos >= end) { - return; - } - if (paramHelpStringMargin === undefined) { - paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; - } - // Now consume white spaces max - var startOfLinePos = pos; - pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); - if (pos >= end) { - return; - } - var consumedSpaces = pos - startOfLinePos; - if (consumedSpaces < paramHelpStringMargin) { - var ch = sourceFile.text.charCodeAt(pos); - if (ch === 42 /* asterisk */) { - // Consume more spaces after asterisk - pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); - } - } - } - } + var TokenObject = (function (_super) { + __extends(TokenObject, _super); + function TokenObject(kind, pos, end) { + _super.call(this, pos, end); + this.kind = kind; } - } + return TokenObject; + }(TokenOrIdentifierObject)); + var IdentifierObject = (function (_super) { + __extends(IdentifierObject, _super); + function IdentifierObject(kind, pos, end) { + _super.call(this, pos, end); + } + return IdentifierObject; + }(TokenOrIdentifierObject)); + IdentifierObject.prototype.kind = 69 /* Identifier */; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -52517,7 +72778,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (1024 /* Class */ | 2048 /* Interface */) + return this.flags & (32768 /* Class */ | 65536 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; @@ -52544,7 +72805,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? getJsDocCommentsFromDeclarations([this.declaration], + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], /*name*/ undefined, /*canUseParsedParamTagComments*/ false) : []; } @@ -52576,24 +72837,23 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { var name = getDeclarationName(declaration); if (name) { - var declarations = getDeclarations(name); - declarations.push(declaration); + ts.multiMapAdd(result, name, declaration); } } function getDeclarations(name) { - return ts.getProperty(result, name) || (result[name] = []); + return result[name] || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_2 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_2 !== undefined) { - return result_2; + var result_6 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_6 !== undefined) { + return result_6; } if (declaration.name.kind === 140 /* ComputedPropertyName */) { var expr = declaration.name.expression; @@ -52660,7 +72920,7 @@ var ts; break; case 142 /* Parameter */: // Only consider parameter properties - if (!(node.flags & 92 /* ParameterPropertyModifier */)) { + if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // fall through @@ -52714,207 +72974,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); - var TextChange = (function () { - function TextChange() { - } - return TextChange; - }()); - ts.TextChange = TextChange; - var HighlightSpanKind; - (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; - })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); - (function (IndentStyle) { - IndentStyle[IndentStyle["None"] = 0] = "None"; - IndentStyle[IndentStyle["Block"] = 1] = "Block"; - IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; - (function (SymbolDisplayPartKind) { - SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; - SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; - SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; - SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; - SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; - SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; - SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; - SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; - SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; - (function (OutputFileType) { - OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; - OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; - OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; - })(ts.OutputFileType || (ts.OutputFileType = {})); - var OutputFileType = ts.OutputFileType; - (function (EndOfLineState) { - EndOfLineState[EndOfLineState["None"] = 0] = "None"; - EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; - EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; - EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; - EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; - EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; - EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; - })(ts.EndOfLineState || (ts.EndOfLineState = {})); - var EndOfLineState = ts.EndOfLineState; - (function (TokenClass) { - TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; - TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; - TokenClass[TokenClass["Operator"] = 2] = "Operator"; - TokenClass[TokenClass["Comment"] = 3] = "Comment"; - TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; - TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; - TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; - TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; - TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; - // TODO: move these to enums - var ScriptElementKind; - (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; - /** predefined type (void) or keyword (class) */ - ScriptElementKind.keyword = "keyword"; - /** top level script node */ - ScriptElementKind.scriptElement = "script"; - /** module foo {} */ - ScriptElementKind.moduleElement = "module"; - /** class X {} */ - ScriptElementKind.classElement = "class"; - /** var x = class X {} */ - ScriptElementKind.localClassElement = "local class"; - /** interface Y {} */ - ScriptElementKind.interfaceElement = "interface"; - /** type T = ... */ - ScriptElementKind.typeElement = "type"; - /** enum E */ - ScriptElementKind.enumElement = "enum"; - /** - * Inside module and script only - * const v = .. - */ - ScriptElementKind.variableElement = "var"; - /** Inside function */ - ScriptElementKind.localVariableElement = "local var"; - /** - * Inside module and script only - * function f() { } - */ - ScriptElementKind.functionElement = "function"; - /** Inside function */ - ScriptElementKind.localFunctionElement = "local function"; - /** class X { [public|private]* foo() {} } */ - ScriptElementKind.memberFunctionElement = "method"; - /** class X { [public|private]* [get|set] foo:number; } */ - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; - /** - * class X { [public|private]* foo:number; } - * interface Y { foo:number; } - */ - ScriptElementKind.memberVariableElement = "property"; - /** class X { constructor() { } } */ - ScriptElementKind.constructorImplementationElement = "constructor"; - /** interface Y { ():number; } */ - ScriptElementKind.callSignatureElement = "call"; - /** interface Y { []:number; } */ - ScriptElementKind.indexSignatureElement = "index"; - /** interface Y { new():Y; } */ - ScriptElementKind.constructSignatureElement = "construct"; - /** function foo(*Y*: string) */ - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); - var ScriptElementKindModifier; - (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; - })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - return ClassificationTypeNames; - }()); - ts.ClassificationTypeNames = ClassificationTypeNames; - (function (ClassificationType) { - ClassificationType[ClassificationType["comment"] = 1] = "comment"; - ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; - ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; - ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; - ClassificationType[ClassificationType["operator"] = 5] = "operator"; - ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; - ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; - ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; - ClassificationType[ClassificationType["text"] = 9] = "text"; - ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; - ClassificationType[ClassificationType["className"] = 11] = "className"; - ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; - ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; - ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; - ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; - ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; - ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; - ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; - ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; - ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; - ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; - ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; - ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; - ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; - })(ts.ClassificationType || (ts.ClassificationType = {})); - var ClassificationType = ts.ClassificationType; + function getServicesObjectAllocator() { + return { + getNodeConstructor: function () { return NodeObject; }, + getTokenConstructor: function () { return TokenObject; }, + getIdentifierConstructor: function () { return IdentifierObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; } + }; + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -52922,29 +72992,6 @@ var ts; return ""; } ts.displayPartsToString = displayPartsToString; - function isLocalVariableOrFunction(symbol) { - if (symbol.parent) { - return false; // This is exported symbol - } - return ts.forEach(symbol.declarations, function (declaration) { - // Function expressions are local - if (declaration.kind === 179 /* FunctionExpression */) { - return true; - } - if (declaration.kind !== 218 /* VariableDeclaration */ && declaration.kind !== 220 /* FunctionDeclaration */) { - return false; - } - // If the parent is not sourceFile or module block it is local variable - for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { - // Reached source file or module block - if (parent_16.kind === 256 /* SourceFile */ || parent_16.kind === 226 /* ModuleBlock */) { - return false; - } - } - // parent is in function block - return true; - }); - } function getDefaultCompilerOptions() { // Always default to "ScriptTarget.ES5" for the language service return { @@ -52953,7 +73000,7 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about scrip Should be refreshed + // Cache host information about script should be refreshed // at each language service public entry point, since we don't know when // set of scripts handled by the host changes. var HostCache = (function () { @@ -53060,126 +73107,6 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptionsStringToEnum; - /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ - function fixupCompilerOptions(options, diagnostics) { - // Lazily create this value to fix module loading errors. - commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { - return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); - }); - options = ts.clone(options); - var _loop_3 = function(opt) { - if (!ts.hasProperty(options, opt.name)) { - return "continue"; - } - var value = options[opt.name]; - // Value should be a key of opt.type - if (typeof value === "string") { - // If value is not a string, this will fail - options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); - } - else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { - // Supplied value isn't a valid enum value. - diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); - } - } - }; - for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { - var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_3(opt); - } - return options; - } - /* - * This function will compile source text from 'input' argument using specified compiler options. - * If not options are provided - it will use a set of default compiler options. - * Extra compiler options that will unconditionally be used by this function are: - * - isolatedModules = true - * - allowNonTsExtensions = true - * - noLib = true - * - noResolve = true - */ - function transpileModule(input, transpileOptions) { - var diagnostics = []; - var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : getDefaultCompilerOptions(); - options.isolatedModules = true; - // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. - options.suppressOutputPathCheck = true; - // Filename can be non-ts file. - options.allowNonTsExtensions = true; - // We are not returning a sourceFile for lib file when asked by the program, - // so pass --noLib to avoid reporting a file not found error. - options.noLib = true; - // Clear out other settings that would not be used in transpiling this module - options.lib = undefined; - options.types = undefined; - options.noEmit = undefined; - options.noEmitOnError = undefined; - options.paths = undefined; - options.rootDirs = undefined; - options.declaration = undefined; - options.declarationDir = undefined; - options.out = undefined; - options.outFile = undefined; - // We are not doing a full typecheck, we are not resolving the whole context, - // so pass --noResolve to avoid reporting missing file errors. - options.noResolve = true; - // if jsx is specified then treat file as .tsx - var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); - if (transpileOptions.moduleName) { - sourceFile.moduleName = transpileOptions.moduleName; - } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; - var newLine = ts.getNewLineCharacter(options); - // Output - var outputText; - var sourceMapText; - // Create a compilerHost object to allow the compiler to read and write files - var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { - if (ts.fileExtensionIs(name, ".map")) { - ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); - sourceMapText = text; - } - else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); - outputText = text; - } - }, - getDefaultLibFileName: function () { return "lib.d.ts"; }, - useCaseSensitiveFileNames: function () { return false; }, - getCanonicalFileName: function (fileName) { return fileName; }, - getCurrentDirectory: function () { return ""; }, - getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } - }; - var program = ts.createProgram([inputFileName], options, compilerHost); - if (transpileOptions.reportDiagnostics) { - ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); - ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); - } - // Emit - program.emit(); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); - return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; - } - ts.transpileModule = transpileModule; - /* - * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. - */ - function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { - var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); - // addRange correctly handles cases when wither 'from' or 'to' argument is missing - ts.addRange(diagnostics, output.diagnostics); - return output.outputText; - } - ts.transpile = transpile; function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); @@ -53238,681 +73165,6 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have - // for those settings. - var buckets = {}; - var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); - } - function getBucketForCompilationSettings(key, createIfMissing) { - var bucket = ts.lookUp(buckets, key); - if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(); - } - return bucket; - } - function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { - var entries = ts.lookUp(buckets, name); - var sourceFiles = []; - entries.forEachValue(function (key, entry) { - sourceFiles.push({ - name: key, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) - }); - }); - sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); - return { - bucket: name, - sourceFiles: sourceFiles - }; - }); - return JSON.stringify(bucketInfoArray, undefined, 2); - } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); - } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); - } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); - } - function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); - var entry = bucket.get(path); - if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); - // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); - entry = { - sourceFile: sourceFile, - languageServiceRefCount: 0, - owners: [] - }; - bucket.set(path, entry); - } - else { - // We have an entry for this file. However, it may be for a different version of - // the script snapshot. If so, update it appropriately. Otherwise, we can just - // return it as is. - if (entry.sourceFile.version !== version) { - entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); - } - } - // If we're acquiring, then this is the first time this LS is asking for this document. - // Increase our ref count so we know there's another LS using the document. If we're - // not acquiring, then that means the LS is 'updating' the file instead, and that means - // it has already acquired the document previously. As such, we do not need to increase - // the ref count. - if (acquiring) { - entry.languageServiceRefCount++; - } - return entry.sourceFile; - } - function releaseDocument(fileName, compilationSettings) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); - } - function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(path); - entry.languageServiceRefCount--; - ts.Debug.assert(entry.languageServiceRefCount >= 0); - if (entry.languageServiceRefCount === 0) { - bucket.remove(path); - } - } - return { - acquireDocument: acquireDocument, - acquireDocumentWithKey: acquireDocumentWithKey, - updateDocument: updateDocument, - updateDocumentWithKey: updateDocumentWithKey, - releaseDocument: releaseDocument, - releaseDocumentWithKey: releaseDocumentWithKey, - reportStats: reportStats, - getKeyForCompilationSettings: getKeyForCompilationSettings - }; - } - ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { - if (readImportFiles === void 0) { readImportFiles = true; } - if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } - var referencedFiles = []; - var typeReferenceDirectives = []; - var importedFiles = []; - var ambientExternalModules; - var isNoDefaultLib = false; - var braceNesting = 0; - // assume that text represent an external module if it contains at least one top level import/export - // ambient modules that are found inside external modules are interpreted as module augmentations - var externalModule = false; - function nextToken() { - var token = scanner.scan(); - if (token === 15 /* OpenBraceToken */) { - braceNesting++; - } - else if (token === 16 /* CloseBraceToken */) { - braceNesting--; - } - return token; - } - function processTripleSlashDirectives() { - var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); - ts.forEach(commentRanges, function (commentRange) { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); - if (referencePathMatchResult) { - isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; - if (fileReference) { - var collection = referencePathMatchResult.isTypeReferenceDirective - ? typeReferenceDirectives - : referencedFiles; - collection.push(fileReference); - } - } - }); - } - function getFileReference() { - var file = scanner.getTokenValue(); - var pos = scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; - } - function recordAmbientExternalModule() { - if (!ambientExternalModules) { - ambientExternalModules = []; - } - ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); - } - function recordModuleName() { - importedFiles.push(getFileReference()); - markAsExternalModuleIfTopLevel(); - } - function markAsExternalModuleIfTopLevel() { - if (braceNesting === 0) { - externalModule = true; - } - } - /** - * Returns true if at least one token was consumed from the stream - */ - function tryConsumeDeclare() { - var token = scanner.getToken(); - if (token === 122 /* DeclareKeyword */) { - // declare module "mod" - token = nextToken(); - if (token === 125 /* ModuleKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - recordAmbientExternalModule(); - } - } - return true; - } - return false; - } - /** - * Returns true if at least one token was consumed from the stream - */ - function tryConsumeImport() { - var token = scanner.getToken(); - if (token === 89 /* ImportKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import "mod"; - recordModuleName(); - return true; - } - else { - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import d from "mod"; - recordModuleName(); - return true; - } - } - else if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { - return true; - } - } - else if (token === 24 /* CommaToken */) { - // consume comma and keep going - token = nextToken(); - } - else { - // unknown syntax - return true; - } - } - if (token === 15 /* OpenBraceToken */) { - token = nextToken(); - // consume "{ a as B, c, d as D}" clauses - // make sure that it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { - token = nextToken(); - } - if (token === 16 /* CloseBraceToken */) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import {a as A} from "mod"; - // import d, {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = nextToken(); - if (token === 116 /* AsKeyword */) { - token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // import * as NS from "mod" - // import d, * as NS from "mod" - recordModuleName(); - } - } - } - } - } - } - return true; - } - return false; - } - function tryConsumeExport() { - var token = scanner.getToken(); - if (token === 82 /* ExportKeyword */) { - markAsExternalModuleIfTopLevel(); - token = nextToken(); - if (token === 15 /* OpenBraceToken */) { - token = nextToken(); - // consume "{ a as B, c, d as D}" clauses - // make sure it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { - token = nextToken(); - } - if (token === 16 /* CloseBraceToken */) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // export {a as A} from "mod"; - // export {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = nextToken(); - if (token === 136 /* FromKeyword */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // export * from "mod" - recordModuleName(); - } - } - } - else if (token === 89 /* ImportKeyword */) { - token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = nextToken(); - if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { - return true; - } - } - } - } - return true; - } - return false; - } - function tryConsumeRequireCall(skipCurrentToken) { - var token = skipCurrentToken ? nextToken() : scanner.getToken(); - if (token === 129 /* RequireKeyword */) { - token = nextToken(); - if (token === 17 /* OpenParenToken */) { - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // require("mod"); - recordModuleName(); - } - } - return true; - } - return false; - } - function tryConsumeDefine() { - var token = scanner.getToken(); - if (token === 69 /* Identifier */ && scanner.getTokenValue() === "define") { - token = nextToken(); - if (token !== 17 /* OpenParenToken */) { - return true; - } - token = nextToken(); - if (token === 9 /* StringLiteral */) { - // looks like define ("modname", ... - skip string literal and comma - token = nextToken(); - if (token === 24 /* CommaToken */) { - token = nextToken(); - } - else { - // unexpected token - return true; - } - } - // should be start of dependency list - if (token !== 19 /* OpenBracketToken */) { - return true; - } - // skip open bracket - token = nextToken(); - var i = 0; - // scan until ']' or EOF - while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { - // record string literals as module names - if (token === 9 /* StringLiteral */) { - recordModuleName(); - i++; - } - token = nextToken(); - } - return true; - } - return false; - } - function processImports() { - scanner.setText(sourceText); - nextToken(); - // Look for: - // import "mod"; - // import d from "mod" - // import {a as A } from "mod"; - // import * as NS from "mod" - // import d, {a, b as B} from "mod" - // import i = require("mod"); - // - // export * from "mod" - // export {a as b} from "mod" - // export import i = require("mod") - // (for JavaScript files) require("mod") - while (true) { - if (scanner.getToken() === 1 /* EndOfFileToken */) { - break; - } - // check if at least one of alternative have moved scanner forward - if (tryConsumeDeclare() || - tryConsumeImport() || - tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { - continue; - } - else { - nextToken(); - } - } - scanner.setText(undefined); - } - if (readImportFiles) { - processImports(); - } - processTripleSlashDirectives(); - if (externalModule) { - // for external modules module all nested ambient modules are augmentations - if (ambientExternalModules) { - // move all detected ambient modules to imported files since they need to be resolved - for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { - var decl = ambientExternalModules_1[_i]; - importedFiles.push(decl.ref); - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; - } - else { - // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 - var ambientModuleNames = void 0; - if (ambientExternalModules) { - for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { - var decl = ambientExternalModules_2[_a]; - if (decl.depth === 0) { - if (!ambientModuleNames) { - ambientModuleNames = []; - } - ambientModuleNames.push(decl.ref.fileName); - } - else { - importedFiles.push(decl.ref); - } - } - } - return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames }; - } - } - ts.preProcessFile = preProcessFile; - /// Helpers - function getTargetLabel(referenceNode, labelName) { - while (referenceNode) { - if (referenceNode.kind === 214 /* LabeledStatement */ && referenceNode.label.text === labelName) { - return referenceNode.label; - } - referenceNode = referenceNode.parent; - } - return undefined; - } - function isJumpStatementTarget(node) { - return node.kind === 69 /* Identifier */ && - (node.parent.kind === 210 /* BreakStatement */ || node.parent.kind === 209 /* ContinueStatement */) && - node.parent.label === node; - } - function isLabelOfLabeledStatement(node) { - return node.kind === 69 /* Identifier */ && - node.parent.kind === 214 /* LabeledStatement */ && - node.parent.label === node; - } - /** - * Whether or not a 'node' is preceded by a label of the given string. - * Note: 'node' cannot be a SourceFile. - */ - function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214 /* LabeledStatement */; owner = owner.parent) { - if (owner.label.text === labelName) { - return true; - } - } - return false; - } - function isLabelName(node) { - return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); - } - function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node; - } - function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node; - } - function isCallExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; - } - function isNewExpressionTarget(node) { - if (isRightSideOfPropertyAccess(node)) { - node = node.parent; - } - return node && node.parent && node.parent.kind === 175 /* NewExpression */ && node.parent.expression === node; - } - function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 /* ModuleDeclaration */ && node.parent.name === node; - } - function isNameOfFunctionDeclaration(node) { - return node.kind === 69 /* Identifier */ && - ts.isFunctionLike(node.parent) && node.parent.name === node; - } - function isObjectLiteralPropertyDeclaration(node) { - switch (node.kind) { - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return true; - } - return false; - } - /** - * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } - */ - function getContainingObjectLiteralElement(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - if (node.parent.kind === 140 /* ComputedPropertyName */) { - return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; - } - // intential fall through - case 69 /* Identifier */: - return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; - } - return undefined; - } - function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { - switch (node.parent.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 225 /* ModuleDeclaration */: - return node.parent.name === node; - case 173 /* ElementAccessExpression */: - return node.parent.argumentExpression === node; - case 140 /* ComputedPropertyName */: - return true; - } - } - return false; - } - function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9 /* StringLiteral */) { - return isNameOfModuleDeclaration(node) || - (ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node); - } - return false; - } - /** Returns true if the position is within a comment */ - function isInsideComment(sourceFile, token, position) { - // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment - return position <= token.getStart(sourceFile) && - (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || - isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); - function isInsideCommentRange(comments) { - return ts.forEach(comments, function (comment) { - // either we are 1. completely inside the comment, or 2. at the end of the comment - if (comment.pos < position && position < comment.end) { - return true; - } - else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; - // is single line comment or just /* - if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { - return true; - } - else { - // is unterminated multi-line comment - return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && - text.charCodeAt(comment.end - 2) === 42 /* asterisk */); - } - } - return false; - }); - } - } - var SemanticMeaning; - (function (SemanticMeaning) { - SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; - SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; - SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; - SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; - SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; - })(SemanticMeaning || (SemanticMeaning = {})); - var BreakContinueSearchType; - (function (BreakContinueSearchType) { - BreakContinueSearchType[BreakContinueSearchType["None"] = 0] = "None"; - BreakContinueSearchType[BreakContinueSearchType["Unlabeled"] = 1] = "Unlabeled"; - BreakContinueSearchType[BreakContinueSearchType["Labeled"] = 2] = "Labeled"; - BreakContinueSearchType[BreakContinueSearchType["All"] = 3] = "All"; - })(BreakContinueSearchType || (BreakContinueSearchType = {})); - // A cache of completion entries for keywords, these do not change between sessions - var keywordCompletions = []; - for (var i = 70 /* FirstKeyword */; i <= 138 /* LastKeyword */; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - sortText: "0" - }); - } - /* @internal */ function getContainerNode(node) { - while (true) { - node = node.parent; - if (!node) { - return undefined; - } - switch (node.kind) { - case 256 /* SourceFile */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: - return node; - } - } - } - ts.getContainerNode = getContainerNode; - /* @internal */ function getNodeKind(node) { - switch (node.kind) { - case 225 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - return ScriptElementKind.classElement; - case 222 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 223 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 224 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 218 /* VariableDeclaration */: - return ts.isConst(node) - ? ScriptElementKind.constElement - : ts.isLet(node) - ? ScriptElementKind.letElement - : ScriptElementKind.variableElement; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - return ScriptElementKind.functionElement; - case 149 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return ScriptElementKind.memberFunctionElement; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return ScriptElementKind.memberVariableElement; - case 153 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; - case 152 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; - case 151 /* CallSignature */: return ScriptElementKind.callSignatureElement; - case 148 /* Constructor */: return ScriptElementKind.constructorImplementationElement; - case 141 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 255 /* EnumMember */: return ScriptElementKind.variableElement; - case 142 /* Parameter */: return (node.flags & 92 /* ParameterPropertyModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 231 /* ImportClause */: - case 238 /* ExportSpecifier */: - case 232 /* NamespaceImport */: - return ScriptElementKind.alias; - } - return ScriptElementKind.unknown; - } - ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { function CancellationTokenObject(cancellationToken) { this.cancellationToken = cancellationToken; @@ -53928,7 +73180,7 @@ var ts; return CancellationTokenObject; }()); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; @@ -53985,14 +73237,16 @@ var ts; // incremental parsing. var oldSettings = program && program.getCompilerOptions(); var newSettings = hostCache.compilationSettings(); - var changesInCompilationSettingsAffectSyntax = oldSettings && + var shouldCreateNewSourceFiles = oldSettings && (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.baseUrl !== newSettings.baseUrl || + !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -54006,7 +73260,6 @@ var ts; getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return hostCache.getOrCreateEntry(fileName) !== undefined; }, readFile: function (fileName) { @@ -54041,7 +73294,7 @@ var ts; var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); } } @@ -54069,7 +73322,7 @@ var ts; // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. - if (!changesInCompilationSettingsAffectSyntax) { + if (!shouldCreateNewSourceFiles) { // Check if the old program had this file already var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { @@ -54172,1455 +73425,17 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module otherwise a name with striped of any quote - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { - // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) - return undefined; - } - } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { - return undefined; - } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks) { - if (!ts.isIdentifier(name, target)) { - return undefined; - } - } - return name; - } - function getCompletionData(fileName, position) { - var typeChecker = program.getTypeChecker(); - var sourceFile = getValidSourceFile(fileName); - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - var isJsDocTagName = false; - var start = new Date().getTime(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); - // Completion not allowed inside comments, bail out if this is the case - var insideComment = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); - if (insideComment) { - // The current position is next to the '@' sign, when no tag name being provided yet. - // Provide a full list of tag names - if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { - isJsDocTagName = true; - } - // Completion should work inside certain JsDoc tags. For example: - // /** @type {number | string} */ - // Completion should work in the brackets - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); - if (tag) { - if (tag.tagName.pos <= position && position <= tag.tagName.end) { - isJsDocTagName = true; - } - switch (tag.kind) { - case 277 /* JSDocTypeTag */: - case 275 /* JSDocParameterTag */: - case 276 /* JSDocReturnTag */: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; - } - } - if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; - } - if (!insideJsDocTagExpression) { - // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal - // comment or the plain text part of a jsDoc comment, so no completion should be available - log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); - return undefined; - } - } - start = new Date().getTime(); - var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); - // The decision to provide completion depends on the contextToken, which is determined through the previousToken. - // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file - var contextToken = previousToken; - // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| - // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_5 = new Date().getTime(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); - } - // Find the node where completion is requested on. - // Also determine whether we are trying to complete with members of that node - // or attributes of a JSX tag. - var node = currentToken; - var isRightOfDot = false; - var isRightOfOpenTag = false; - var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); - if (contextToken) { - // Bail out if this is a known invalid completion location - if (isCompletionListBlocker(contextToken)) { - log("Returning an empty list because completion was requested in an invalid position."); - return undefined; - } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21 /* DotToken */) { - if (parent_17.kind === 172 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent_17.kind === 139 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; - } - } - else if (sourceFile.languageVariant === 1 /* JSX */) { - if (kind === 25 /* LessThanToken */) { - isRightOfOpenTag = true; - location = contextToken; - } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 245 /* JsxClosingElement */) { - isStartingCloseTag = true; - location = contextToken; - } - } - } - var semanticStart = new Date().getTime(); - var isMemberCompletion; - var isNewIdentifierLocation; - var symbols = []; - if (isRightOfDot) { - getTypeScriptMemberSymbols(); - } - else if (isRightOfOpenTag) { - var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); - if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 8388608 /* Alias */)); })); - } - else { - symbols = tagSymbols; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else if (isStartingCloseTag) { - var tagName = contextToken.parent.parent.openingElement.tagName; - var tagSymbol = typeChecker.getSymbolAtLocation(tagName); - if (!typeChecker.isUnknownSymbol(tagSymbol)) { - symbols = [tagSymbol]; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - } - else { - // For JavaScript or TypeScript, if we're not after a dot, then just try to get the - // global symbols in scope. These results should be valid for either language as - // the set of symbols that can be referenced from this location. - if (!tryGetGlobalSymbols()) { - return undefined; - } - } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; - function getTypeScriptMemberSymbols() { - // Right of dot member completion list - isMemberCompletion = true; - isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { - var symbol = typeChecker.getSymbolAtLocation(node); - // This is an alias, follow what it aliases - if (symbol && symbol.flags & 8388608 /* Alias */) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952 /* HasExports */) { - // Extract module or enum members - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - }); - } - } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); - } - function addTypeProperties(type) { - if (type) { - // Filter private properties - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - } - if (isJavaScriptFile && type.flags & 16384 /* Union */) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } - } - } - } - function tryGetGlobalSymbols() { - var objectLikeContainer; - var namedImportsOrExports; - var jsxContainer; - if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { - return tryGetObjectLikeCompletionSymbols(objectLikeContainer); - } - if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { - // cursor is in an import clause - // try to show exported member for imported module - return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); - } - if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType = void 0; - if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { - // Cursor is inside a JSX self-closing element or opening element - attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); - if (attrsType) { - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); - isMemberCompletion = true; - isNewIdentifierLocation = false; - return true; - } - } - } - // Get all entities in the current scope. - isMemberCompletion = false; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); - if (previousToken !== contextToken) { - ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); - } - // We need to find the node that will give us an appropriate scope to begin - // aggregating completion candidates. This is achieved in 'getScopeNode' - // by finding the first node that encompasses a position, accounting for whether a node - // is "complete" to decide whether a position belongs to the node. - // - // However, at the end of an identifier, we are interested in the scope of the identifier - // itself, but fall outside of the identifier. For instance: - // - // xyz => x$ - // - // the cursor is outside of both the 'x' and the arrow function 'xyz => x', - // so 'xyz' is not returned in our results. - // - // We define 'adjustedPosition' so that we may appropriately account for - // being at the end of an identifier. The intention is that if requesting completion - // at the end of an identifier, it should be effectively equivalent to requesting completion - // anywhere inside/at the beginning of the identifier. So in the previous case, the - // 'adjustedPosition' will work as if requesting completion in the following: - // - // xyz => $x - // - // If previousToken !== contextToken, then - // - 'contextToken' was adjusted to the token prior to 'previousToken' - // because we were at the end of an identifier. - // - 'previousToken' is defined. - var adjustedPosition = previousToken !== contextToken ? - previousToken.getStart() : - position; - var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - /// TODO filter meaning based on the current context - var symbolMeanings = 793056 /* Type */ | 107455 /* Value */ | 1536 /* Namespace */ | 8388608 /* Alias */; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); - return true; - } - /** - * Finds the first node that "embraces" the position, so that one may - * accurately aggregate locals from the closest containing scope. - */ - function getScopeNode(initialToken, position, sourceFile) { - var scope = initialToken; - while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { - scope = scope.parent; - } - return scope; - } - function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); - var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || - isSolelyIdentifierDefinitionLocation(contextToken) || - isDotOfNumericLiteral(contextToken) || - isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); - return result; - } - function isInJsxText(contextToken) { - if (contextToken.kind === 244 /* JsxText */) { - return true; - } - if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 243 /* JsxOpeningElement */) { - return true; - } - if (contextToken.parent.kind === 245 /* JsxClosingElement */ || contextToken.parent.kind === 242 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241 /* JsxElement */; - } - } - return false; - } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 174 /* CallExpression */ // func( a, | - || containingNodeKind === 148 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 175 /* NewExpression */ // new C(a, | - || containingNodeKind === 170 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 187 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 156 /* FunctionType */; // var x: (s: string, list| - case 17 /* OpenParenToken */: - return containingNodeKind === 174 /* CallExpression */ // func( | - || containingNodeKind === 148 /* Constructor */ // constructor( | - || containingNodeKind === 175 /* NewExpression */ // new C(a| - || containingNodeKind === 178 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 164 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 19 /* OpenBracketToken */: - return containingNodeKind === 170 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 153 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 140 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 125 /* ModuleKeyword */: // module | - case 126 /* NamespaceKeyword */: - return true; - case 21 /* DotToken */: - return containingNodeKind === 225 /* ModuleDeclaration */; // module A.| - case 15 /* OpenBraceToken */: - return containingNodeKind === 221 /* ClassDeclaration */; // class A{ | - case 56 /* EqualsToken */: - return containingNodeKind === 218 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 187 /* BinaryExpression */; // x = a| - case 12 /* TemplateHead */: - return containingNodeKind === 189 /* TemplateExpression */; // `aa ${| - case 13 /* TemplateMiddle */: - return containingNodeKind === 197 /* TemplateSpan */; // `aa ${10} dd ${| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; // class A{ public | - } - // Previous token may have been a keyword that was converted to an identifier. - switch (previousToken.getText()) { - case "public": - case "protected": - case "private": - return true; - } - } - return false; - } - function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { - if (contextToken.kind === 9 /* StringLiteral */ - || contextToken.kind === 166 /* StringLiteralType */ - || contextToken.kind === 10 /* RegularExpressionLiteral */ - || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_6 = contextToken.getStart(); - var end = contextToken.getEnd(); - // To be "in" one of these literals, the position has to be: - // 1. entirely within the token text. - // 2. at the end position of an unterminated token. - // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_6 < position && position < end) { - return true; - } - if (position === end) { - return !!contextToken.isUnterminated - || contextToken.kind === 10 /* RegularExpressionLiteral */; - } - } - return false; - } - /** - * Aggregates relevant symbols for completion in object literals and object binding patterns. - * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. - */ - function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { - // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - var typeForObject; - var existingMembers; - if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { - // We are completing on contextual types, but may also include properties - // other than those within the declared type. - isNewIdentifierLocation = true; - typeForObject = typeChecker.getContextualType(objectLikeContainer); - existingMembers = objectLikeContainer.properties; - } - else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { - // We are *only* completing on properties from the type being destructured. - isNewIdentifierLocation = false; - var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - // We don't want to complete using the type acquired by the shape - // of the binding pattern; we are only interested in types acquired - // through type declaration or inference. - // Also proceed if rootDeclaration is parameter and if its containing function expression\arrow function is contextually typed - - // type of parameter will flow in from the contextual type of the function - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } - } - if (canGetType) { - typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - existingMembers = objectLikeContainer.elements; - } - } - else { - ts.Debug.fail("Root declaration is not variable-like."); - } - } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } - if (!typeForObject) { - return false; - } - var typeMembers = typeChecker.getPropertiesOfType(typeForObject); - if (typeMembers && typeMembers.length > 0) { - // Add filtered items to the completion list - symbols = filterObjectMembersList(typeMembers, existingMembers); - } - return true; - } - /** - * Aggregates relevant symbols for completion in import clauses and export clauses - * whose declarations have a module specifier; for instance, symbols will be aggregated for - * - * import { | } from "moduleName"; - * export { a as foo, | } from "moduleName"; - * - * but not for - * - * export { | }; - * - * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. - */ - function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 /* NamedImports */ ? - 230 /* ImportDeclaration */ : - 236 /* ExportDeclaration */; - var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); - var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; - if (!moduleSpecifier) { - return false; - } - isMemberCompletion = true; - isNewIdentifierLocation = false; - var exports; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); - if (moduleSpecifierSymbol) { - exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); - } - symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; - return true; - } - /** - * Returns the immediate owning object literal or binding pattern of a context token, - * on the condition that one exists and that the context implies completion should be given. - */ - function tryGetObjectLikeCompletionContainer(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // const x = { | - case 24 /* CommaToken */: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 /* ObjectLiteralExpression */ || parent_18.kind === 167 /* ObjectBindingPattern */)) { - return parent_18; - } - break; - } - } - return undefined; - } - /** - * Returns the containing list of named imports or exports of a context token, - * on the condition that one exists and that the context implies completion should be given. - */ - function tryGetNamedImportsOrExportsForCompletion(contextToken) { - if (contextToken) { - switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // import { | - case 24 /* CommaToken */: - switch (contextToken.parent.kind) { - case 233 /* NamedImports */: - case 237 /* NamedExports */: - return contextToken.parent; - } - } - } - return undefined; - } - function tryGetContainingJsxElement(contextToken) { - if (contextToken) { - var parent_19 = contextToken.parent; - switch (contextToken.kind) { - case 26 /* LessThanSlashToken */: - case 39 /* SlashToken */: - case 69 /* Identifier */: - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: - if (parent_19 && (parent_19.kind === 242 /* JsxSelfClosingElement */ || parent_19.kind === 243 /* JsxOpeningElement */)) { - return parent_19; - } - else if (parent_19.kind === 246 /* JsxAttribute */) { - return parent_19.parent; - } - break; - // The context token is the closing } or " of an attribute, which means - // its parent is a JsxExpression, whose parent is a JsxAttribute, - // whose parent is a JsxOpeningLikeElement - case 9 /* StringLiteral */: - if (parent_19 && ((parent_19.kind === 246 /* JsxAttribute */) || (parent_19.kind === 247 /* JsxSpreadAttribute */))) { - return parent_19.parent; - } - break; - case 16 /* CloseBraceToken */: - if (parent_19 && - parent_19.kind === 248 /* JsxExpression */ && - parent_19.parent && - (parent_19.parent.kind === 246 /* JsxAttribute */)) { - return parent_19.parent.parent; - } - if (parent_19 && parent_19.kind === 247 /* JsxSpreadAttribute */) { - return parent_19.parent; - } - break; - } - } - return undefined; - } - function isFunction(kind) { - switch (kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - return true; - } - return false; - } - /** - * @returns true if we are certain that the currently edited location must define a new location; false otherwise. - */ - function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; - switch (contextToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 218 /* VariableDeclaration */ || - containingNodeKind === 219 /* VariableDeclarationList */ || - containingNodeKind === 200 /* VariableStatement */ || - containingNodeKind === 224 /* EnumDeclaration */ || - isFunction(containingNodeKind) || - containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 168 /* ArrayBindingPattern */ || - containingNodeKind === 223 /* TypeAliasDeclaration */; // type Map, K, | - case 21 /* DotToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [.| - case 54 /* ColonToken */: - return containingNodeKind === 169 /* BindingElement */; // var {x :html| - case 19 /* OpenBracketToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [x| - case 17 /* OpenParenToken */: - return containingNodeKind === 252 /* CatchClause */ || - isFunction(containingNodeKind); - case 15 /* OpenBraceToken */: - return containingNodeKind === 224 /* EnumDeclaration */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 159 /* TypeLiteral */; // const x : { | - case 23 /* SemicolonToken */: - return containingNodeKind === 144 /* PropertySignature */ && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 159 /* TypeLiteral */); // const x : { a; | - case 25 /* LessThanToken */: - return containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 223 /* TypeAliasDeclaration */ || - isFunction(containingNodeKind); - case 113 /* StaticKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; - case 22 /* DotDotDotToken */: - return containingNodeKind === 142 /* Parameter */ || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168 /* ArrayBindingPattern */); // var [...z| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 142 /* Parameter */; - case 116 /* AsKeyword */: - return containingNodeKind === 234 /* ImportSpecifier */ || - containingNodeKind === 238 /* ExportSpecifier */ || - containingNodeKind === 232 /* NamespaceImport */; - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: - case 107 /* InterfaceKeyword */: - case 87 /* FunctionKeyword */: - case 102 /* VarKeyword */: - case 123 /* GetKeyword */: - case 131 /* SetKeyword */: - case 89 /* ImportKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - case 114 /* YieldKeyword */: - case 134 /* TypeKeyword */: - return true; - } - // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": - return true; - } - return false; - } - function isDotOfNumericLiteral(contextToken) { - if (contextToken.kind === 8 /* NumericLiteral */) { - var text = contextToken.getFullText(); - return text.charAt(text.length - 1) === "."; - } - return false; - } - /** - * Filters out completion suggestions for named imports or exports. - * - * @param exportsOfModule The list of symbols which a module exposes. - * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. - * - * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports - * do not occur at the current position and have not otherwise been typed. - */ - function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; - for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { - var element = namedImportsOrExports_1[_i]; - // If this is the current item we are editing right now, do not filter it out - if (element.getStart() <= position && position <= element.getEnd()) { - continue; - } - var name_41 = element.propertyName || element.name; - existingImportsOrExports[name_41.text] = true; - } - if (ts.isEmpty(existingImportsOrExports)) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); - } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !ts.lookUp(existingImportsOrExports, e.name); }); - } - /** - * Filters out completion suggestions for named imports or exports. - * - * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations - * do not occur at the current position and have not otherwise been typed. - */ - function filterObjectMembersList(contextualMemberSymbols, existingMembers) { - if (!existingMembers || existingMembers.length === 0) { - return contextualMemberSymbols; - } - var existingMemberNames = {}; - for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { - var m = existingMembers_1[_i]; - // Ignore omitted expressions for missing members - if (m.kind !== 253 /* PropertyAssignment */ && - m.kind !== 254 /* ShorthandPropertyAssignment */ && - m.kind !== 169 /* BindingElement */ && - m.kind !== 147 /* MethodDeclaration */) { - continue; - } - // If this is the current item we are editing right now, do not filter it out - if (m.getStart() <= position && position <= m.getEnd()) { - continue; - } - var existingName = void 0; - if (m.kind === 169 /* BindingElement */ && m.propertyName) { - // include only identifiers in completion list - if (m.propertyName.kind === 69 /* Identifier */) { - existingName = m.propertyName.text; - } - } - else { - // TODO(jfreeman): Account for computed property name - // NOTE: if one only performs this step when m.name is an identifier, - // things like '__proto__' are not filtered out. - existingName = m.name.text; - } - existingMemberNames[existingName] = true; - } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); - } - /** - * Filters out completion suggestions from 'symbols' according to existing JSX attributes. - * - * @returns Symbols to be suggested in a JSX element, barring those whose attributes - * do not occur at the current position and have not otherwise been typed. - */ - function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; - for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { - var attr = attributes_1[_i]; - // If this is the current item we are editing right now, do not filter it out - if (attr.getStart() <= position && position <= attr.getEnd()) { - continue; - } - if (attr.kind === 246 /* JsxAttribute */) { - seenNames[attr.name.text] = true; - } - } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); - } - } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position); - } - var completionData = getCompletionData(fileName, position); - if (!completionData) { - return undefined; - } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; - if (isJsDocTagName) { - // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; - } - var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); - } - else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 /* JSX */ && - location.parent && location.parent.kind === 245 /* JsxClosingElement */) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
completion list at "1" will contain "div" with type any - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0" - }); - } - else { - return undefined; - } - } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); - } - // Add keywords if this is not a member completion list - if (!isMemberCompletion && !isJsDocTagName) { - ts.addRange(entries, keywordCompletions); - } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { - var entries = []; - var target = program.getCompilerOptions().target; - var nameTable = getNameTable(sourceFile); - for (var name_42 in nameTable) { - // Skip identifiers produced only from the current location - if (nameTable[name_42] === position) { - continue; - } - if (!uniqueNames[name_42]) { - uniqueNames[name_42] = name_42; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, /*performCharacterChecks*/ true); - if (displayName) { - var entry = { - name: displayName, - kind: ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } - } - } - return entries; - } - function getAllJsDocCompletionEntries() { - return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { - return { - name: tagName, - kind: ScriptElementKind.keyword, - kindModifiers: "", - sortText: "0" - }; - })); - } - function createCompletionEntry(symbol, location, performCharacterChecks) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, performCharacterChecks, location); - if (!displayName) { - return undefined; - } - // TODO(drosen): Right now we just permit *all* semantic meanings when calling - // 'getSymbolKind' which is permissible given that it is backwards compatible; but - // really we should consider passing the meaning for the node so that we don't report - // that a suggestion for a value is an interface. We COULD also just do what - // 'getSymbolModifiers' does, which is to use the first declaration. - // Use a 'sortText' of 0' so that all symbol completion entries come before any other - // entries (like JavaScript identifier entries). - return { - name: displayName, - kind: getSymbolKind(symbol, location), - kindModifiers: getSymbolModifiers(symbol), - sortText: "0" - }; - } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; - if (symbols) { - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks); - if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(uniqueNames, id)) { - entries.push(entry); - uniqueNames[id] = id; - } - } - } - } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return uniqueNames; - } - function getStringLiteralCompletionEntries(sourceFile, position) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9 /* StringLiteral */) { - return undefined; - } - var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - return getStringLiteralCompletionEntriesFromElementAccess(node.parent); - } - else { - // Otherwise, get the completions from the contextual type if one exists - return getStringLiteralCompletionEntriesFromContextualType(node); - } - } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { - var typeChecker = program.getTypeChecker(); - var candidates = []; - var entries = []; - typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); - for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) { - var candidate = candidates_3[_i]; - if (candidate.parameters.length > argumentInfo.argumentIndex) { - var parameter = candidate.parameters[argumentInfo.argumentIndex]; - addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries); - } - } - if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; - } - return undefined; - } - function getStringLiteralCompletionEntriesFromElementAccess(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getTypeAtLocation(node.expression); - var entries = []; - if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); - if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; - } - } - return undefined; - } - function getStringLiteralCompletionEntriesFromContextualType(node) { - var typeChecker = program.getTypeChecker(); - var type = typeChecker.getContextualType(node); - if (type) { - var entries_2 = []; - addStringLiteralCompletionsFromType(type, entries_2); - if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; - } - } - return undefined; - } - function addStringLiteralCompletionsFromType(type, result) { - if (!type) { - return; - } - if (type.flags & 16384 /* Union */) { - ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); - } - else { - if (type.flags & 256 /* StringLiteral */) { - result.push({ - name: type.text, - kindModifiers: ScriptElementKindModifier.none, - kind: ScriptElementKind.variableElement, - sortText: "0" - }); - } - } - } + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); - // Compute all the completion symbols again. - var completionData = getCompletionData(fileName, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - // Find the symbol with the matching entry name. - var target_2 = program.getCompilerOptions().target; - // We don't need to perform character checks here because we're only comparing the - // name against 'entryName' (which is known to be good), not building a new - // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); - if (symbol) { - var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; - return { - name: entryName, - kindModifiers: getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation - }; - } - } - // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - displayParts: [ts.displayPart(entryName, SymbolDisplayPartKind.keyword)], - documentation: undefined - }; - } - return undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } - // TODO(drosen): use contextual SemanticMeaning. - function getSymbolKind(symbol, location) { - var flags = symbol.getFlags(); - if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */) ? - ScriptElementKind.localClassElement : ScriptElementKind.classElement; - if (flags & 384 /* Enum */) - return ScriptElementKind.enumElement; - if (flags & 524288 /* TypeAlias */) - return ScriptElementKind.typeElement; - if (flags & 64 /* Interface */) - return ScriptElementKind.interfaceElement; - if (flags & 262144 /* TypeParameter */) - return ScriptElementKind.typeParameterElement; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location); - if (result === ScriptElementKind.unknown) { - if (flags & 262144 /* TypeParameter */) - return ScriptElementKind.typeParameterElement; - if (flags & 8 /* EnumMember */) - return ScriptElementKind.variableElement; - if (flags & 8388608 /* Alias */) - return ScriptElementKind.alias; - if (flags & 1536 /* Module */) - return ScriptElementKind.moduleElement; - } - return result; - } - function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location) { - var typeChecker = program.getTypeChecker(); - if (typeChecker.isUndefinedSymbol(symbol)) { - return ScriptElementKind.variableElement; - } - if (typeChecker.isArgumentsSymbol(symbol)) { - return ScriptElementKind.localVariableElement; - } - if (location.kind === 97 /* ThisKeyword */ && ts.isExpression(location)) { - return ScriptElementKind.parameterElement; - } - if (flags & 3 /* Variable */) { - if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ScriptElementKind.parameterElement; - } - else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ScriptElementKind.constElement; - } - else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ScriptElementKind.letElement; - } - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement; - } - if (flags & 16 /* Function */) - return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localFunctionElement : ScriptElementKind.functionElement; - if (flags & 32768 /* GetAccessor */) - return ScriptElementKind.memberGetAccessorElement; - if (flags & 65536 /* SetAccessor */) - return ScriptElementKind.memberSetAccessorElement; - if (flags & 8192 /* Method */) - return ScriptElementKind.memberFunctionElement; - if (flags & 16384 /* Constructor */) - return ScriptElementKind.constructorImplementationElement; - if (flags & 4 /* Property */) { - if (flags & 268435456 /* SyntheticProperty */) { - // If union property is result of union of non method (property/accessors/variables), it is labeled as property - var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - var rootSymbolFlags = rootSymbol.getFlags(); - if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { - return ScriptElementKind.memberVariableElement; - } - ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); - }); - if (!unionPropertyKind) { - // If this was union of all methods, - // make sure it has call signatures before we can label it as method - var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (typeOfUnionProperty.getCallSignatures().length) { - return ScriptElementKind.memberFunctionElement; - } - return ScriptElementKind.memberVariableElement; - } - return unionPropertyKind; - } - return ScriptElementKind.memberVariableElement; - } - return ScriptElementKind.unknown; - } - function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 - ? ts.getNodeModifiers(symbol.declarations[0]) - : ScriptElementKindModifier.none; - } - // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { - if (semanticMeaning === void 0) { semanticMeaning = getMeaningFromLocation(location); } - var typeChecker = program.getTypeChecker(); - var displayParts = []; - var documentation; - var symbolFlags = symbol.flags; - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, location); - var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 /* ThisKeyword */ && ts.isExpression(location); - var type; - // Class at constructor site need to be shown as constructor apart from property,method, vars - if (symbolKind !== ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { - // If it is accessor they are allowed only if location is at name of the accessor - if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { - symbolKind = ScriptElementKind.memberVariableElement; - } - var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (type) { - if (location.parent && location.parent.kind === 172 /* PropertyAccessExpression */) { - var right = location.parent.name; - // Either the location is on the right of a property access, or on the left and the right is missing - if (right === location || (right && right.getFullWidth() === 0)) { - location = location.parent; - } - } - // try get the call/construct signature from the type if it matches - var callExpression = void 0; - if (location.kind === 174 /* CallExpression */ || location.kind === 175 /* NewExpression */) { - callExpression = location; - } - else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { - callExpression = location.parent; - } - if (callExpression) { - var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); - if (!signature && candidateSignatures.length) { - // Use the first candidate: - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpression.kind === 175 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { - // Get the first signature if there is one -- allSignatures may contain - // either the original signature or its target, so check for either - signature = allSignatures.length ? allSignatures[0] : undefined; - } - if (signature) { - if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { - // Constructor - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else if (symbolFlags & 8388608 /* Alias */) { - symbolKind = ScriptElementKind.alias; - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - addFullSymbolName(symbol); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - switch (symbolKind) { - case ScriptElementKind.memberVariableElement: - case ScriptElementKind.variableElement: - case ScriptElementKind.constElement: - case ScriptElementKind.letElement: - case ScriptElementKind.parameterElement: - case ScriptElementKind.localVariableElement: - // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); - displayParts.push(ts.spacePart()); - if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - if (!(type.flags & 65536 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); - } - addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); - break; - default: - // Just signature - addSignatureDisplayParts(signature, allSignatures); - } - hasAddedSymbolInfo = true; - } - } - else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 148 /* Constructor */)) { - // get the signature from the declaration and write it - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); - if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); - } - else { - signature = allSignatures[0]; - } - if (functionDeclaration.kind === 148 /* Constructor */) { - // show (constructor) Type(...) signature - symbolKind = ScriptElementKind.constructorImplementationElement; - addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); - } - else { - // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 /* CallSignature */ && - !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); - } - addSignatureDisplayParts(signature, allSignatures); - hasAddedSymbolInfo = true; - } - } - } - if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */)) { - // Special case for class expressions because we would like to indicate that - // the class name is local to the class body (similar to function expression) - // (local class) class - pushTypePart(ScriptElementKind.localClassElement); - } - else { - // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(73 /* ClassKeyword */)); - } - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107 /* InterfaceKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - } - if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - writeTypeParametersOfSymbol(symbol, sourceFile); - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); - } - if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); - if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74 /* ConstKeyword */)); - displayParts.push(ts.spacePart()); - } - displayParts.push(ts.keywordPart(81 /* EnumKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90 /* InKeyword */)); - displayParts.push(ts.spacePart()); - if (symbol.parent) { - // Class/Interface type parameter - addFullSymbolName(symbol.parent, enclosingDeclaration); - writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); - } - else { - // Method/function type parameter - var declaration = ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */); - ts.Debug.assert(declaration !== undefined); - declaration = declaration.parent; - if (declaration) { - if (ts.isFunctionLikeKind(declaration.kind)) { - var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); - displayParts.push(ts.spacePart()); - } - else if (declaration.kind !== 151 /* CallSignature */ && declaration.name) { - addFullSymbolName(declaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); - } - else { - // Type alias type parameter - // For example - // type list = T[]; // Both T will go through same code path - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); - } - } - } - } - if (symbolFlags & 8 /* EnumMember */) { - addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 255 /* EnumMember */) { - var constantValue = typeChecker.getConstantValue(declaration); - if (constantValue !== undefined) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral)); - } - } - } - if (symbolFlags & 8388608 /* Alias */) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229 /* ImportEqualsDeclaration */) { - var importEqualsDeclaration = declaration; - if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - } - else { - var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); - if (internalAliasSymbol) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(internalAliasSymbol, enclosingDeclaration); - } - } - return true; - } - }); - } - if (!hasAddedSymbolInfo) { - if (symbolKind !== ScriptElementKind.unknown) { - if (type) { - if (isThisExpression) { - addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97 /* ThisKeyword */)); - } - else { - addPrefixForAnyFunctionOrVar(symbol, symbolKind); - } - // For properties, variables and local vars: show the type - if (symbolKind === ScriptElementKind.memberVariableElement || - symbolFlags & 3 /* Variable */ || - symbolKind === ScriptElementKind.localVariableElement || - isThisExpression) { - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); - displayParts.push(ts.spacePart()); - // If the type is type parameter, format it specially - if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } - else { - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); - } - } - else if (symbolFlags & 16 /* Function */ || - symbolFlags & 8192 /* Method */ || - symbolFlags & 16384 /* Constructor */ || - symbolFlags & 131072 /* Signature */ || - symbolFlags & 98304 /* Accessor */ || - symbolKind === ScriptElementKind.memberFunctionElement) { - var allSignatures = type.getNonNullableType().getCallSignatures(); - addSignatureDisplayParts(allSignatures[0], allSignatures); - } - } - } - else { - symbolKind = getSymbolKind(symbol, location); - } - } - if (!documentation) { - documentation = symbol.getDocumentationComment(); - } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; - function addNewLineIfDisplayPartsExist() { - if (displayParts.length) { - displayParts.push(ts.lineBreakPart()); - } - } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); - ts.addRange(displayParts, fullSymbolDisplayParts); - } - function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); - if (symbolKind) { - pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); - } - } - function pushTypePart(symbolKind) { - switch (symbolKind) { - case ScriptElementKind.variableElement: - case ScriptElementKind.functionElement: - case ScriptElementKind.letElement: - case ScriptElementKind.constElement: - case ScriptElementKind.constructorImplementationElement: - displayParts.push(ts.textOrKeywordPart(symbolKind)); - return; - default: - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - return; - } - } - function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); - if (allSignatures.length > 1) { - displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(35 /* PlusToken */)); - displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), SymbolDisplayPartKind.numericLiteral)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); - } - documentation = signature.getDocumentationComment(); - } - function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); - }); - ts.addRange(displayParts, typeParameterParts); - } + function getCompletionEntrySymbol(fileName, position, entryName) { + synchronizeHostData(); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -55629,7 +73444,7 @@ var ts; if (node === sourceFile) { return undefined; } - if (isLabelName(node)) { + if (ts.isLabelName(node)) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -55647,228 +73462,46 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ScriptElementKind.unknown, - kindModifiers: ScriptElementKindModifier.none, + kind: ts.ScriptElementKind.unknown, + kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), - displayParts: ts.typeToDisplayParts(typeChecker, type, getContainerNode(node)), + displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined }; } } return undefined; } - var displayPartsDocumentationsAndKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, getContainerNode(node), node); + var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); return { kind: displayPartsDocumentationsAndKind.symbolKind, - kindModifiers: getSymbolModifiers(symbol), + kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, documentation: displayPartsDocumentationsAndKind.documentation }; } - function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), - kind: symbolKind, - name: symbolName, - containerKind: undefined, - containerName: containerName - }; - } - function getDefinitionFromSymbol(symbol, node) { - var typeChecker = program.getTypeChecker(); - var result = []; - var declarations = symbol.getDeclarations(); - var symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol - var symbolKind = getSymbolKind(symbol, node); - var containerSymbol = symbol.parent; - var 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. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - // 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 === 121 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, - /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } - } - return false; - } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; - } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { - var declarations = []; - var definition; - ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148 /* Constructor */) || - (!selectConstructors && (d.kind === 220 /* FunctionDeclaration */ || d.kind === 147 /* MethodDeclaration */ || d.kind === 146 /* MethodSignature */))) { - declarations.push(d); - if (d.body) - definition = d; - } - }); - if (definition) { - result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); - return true; - } - else if (declarations.length) { - result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; - } - } - function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; - if (ref.pos <= pos && pos < ref.end) { - return ref; - } - } - return undefined; - } - function getDefinitionInfoForFileReference(name, targetFileName) { - return { - fileName: targetFileName, - textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ScriptElementKind.scriptElement, - name: name, - containerName: undefined, - containerKind: undefined - }; - } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - return undefined; - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); - if (referenceFile && referenceFile.resolvedFileName) { - return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; - } - return undefined; - } - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - // Labels - if (isJumpStatementTarget(node)) { - var labelName = node.text; - var label = getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - // Could not find a symbol e.g. node is string or number keyword, - // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol) { - return undefined; - } - // If this is an alias, and the request came at the declaration location - // get the aliased symbol instead. This allows for goto def on an import e.g. - // import {A, B} from "mod"; - // to jump to the implementation directly. - if (symbol.flags & 8388608 /* Alias */) { - var declaration = symbol.declarations[0]; - // Go to the original declaration for cases: - // - // (1) when the aliased symbol was declared in the location(parent). - // (2) when the aliased symbol is originating from a named import. - // - if (node.kind === 69 /* Identifier */ && - (node.parent === declaration || - (declaration.kind === 234 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 233 /* NamedImports */))) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - } - // Because name in short-hand property assignment has two different meanings: property name and property value, - // using go-to-definition at such position should go to the variable declaration of the property value rather than - // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition - // is performed at the location of property access, we would like to go to definition of the property in the short-hand - // assignment. This case and others are handled by the following code. - if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { - var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - if (!shorthandSymbol) { - return []; - } - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); - var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); - } - return getDefinitionFromSymbol(symbol, node); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); + } + /// Goto implementation + function getImplementationAtPosition(fileName, position) { + synchronizeHostData(); + return ts.GoToImplementation.getImplementationAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); } - /// Goto type function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); - if (node === sourceFile) { - return undefined; - } - var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { - return undefined; - } - if (type.flags & 16384 /* Union */) { - var result_3 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); - } - }); - return result_3; - } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(type.symbol, node); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -55876,527 +73509,7 @@ var ts; synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingWord(sourceFile, position); - if (!node) { - return undefined; - } - return getSemanticDocumentHighlights(node) || getSyntacticDocumentHighlights(node); - function getHighlightSpanForNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - return { - fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: HighlightSpanKind.none - }; - } - function getSemanticDocumentHighlights(node) { - if (node.kind === 69 /* Identifier */ || - node.kind === 97 /* ThisKeyword */ || - node.kind === 165 /* ThisType */ || - node.kind === 95 /* SuperKeyword */ || - node.kind === 9 /* StringLiteral */ || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false); - return convertReferencedSymbols(referencedSymbols); - } - return undefined; - function convertReferencedSymbols(referencedSymbols) { - if (!referencedSymbols) { - return undefined; - } - var fileNameToDocumentHighlights = {}; - var result = []; - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var referencedSymbol = referencedSymbols_1[_i]; - for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { - var referenceEntry = _b[_a]; - var fileName_1 = referenceEntry.fileName; - var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); - if (!documentHighlights) { - documentHighlights = { fileName: fileName_1, highlightSpans: [] }; - fileNameToDocumentHighlights[fileName_1] = documentHighlights; - result.push(documentHighlights); - } - documentHighlights.highlightSpans.push({ - textSpan: referenceEntry.textSpan, - kind: referenceEntry.isWriteAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference - }); - } - } - return result; - } - } - function getSyntacticDocumentHighlights(node) { - var fileName = sourceFile.fileName; - var highlightSpans = getHighlightSpans(node); - if (!highlightSpans || highlightSpans.length === 0) { - return undefined; - } - return [{ fileName: fileName, highlightSpans: highlightSpans }]; - // returns true if 'node' is defined and has a matching 'kind'. - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - // Null-propagating 'parent' function. - function parent(node) { - return node && node.parent; - } - function getHighlightSpans(node) { - if (node) { - switch (node.kind) { - case 88 /* IfKeyword */: - case 80 /* ElseKeyword */: - if (hasKind(node.parent, 203 /* IfStatement */)) { - return getIfElseOccurrences(node.parent); - } - break; - case 94 /* ReturnKeyword */: - if (hasKind(node.parent, 211 /* ReturnStatement */)) { - return getReturnOccurrences(node.parent); - } - break; - case 98 /* ThrowKeyword */: - if (hasKind(node.parent, 215 /* ThrowStatement */)) { - return getThrowOccurrences(node.parent); - } - break; - case 72 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 216 /* TryStatement */)) { - return getTryCatchFinallyOccurrences(node.parent.parent); - } - break; - case 100 /* TryKeyword */: - case 85 /* FinallyKeyword */: - if (hasKind(parent(node), 216 /* TryStatement */)) { - return getTryCatchFinallyOccurrences(node.parent); - } - break; - case 96 /* SwitchKeyword */: - if (hasKind(node.parent, 213 /* SwitchStatement */)) { - return getSwitchCaseDefaultOccurrences(node.parent); - } - break; - case 71 /* CaseKeyword */: - case 77 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 213 /* SwitchStatement */)) { - return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); - } - break; - case 70 /* BreakKeyword */: - case 75 /* ContinueKeyword */: - if (hasKind(node.parent, 210 /* BreakStatement */) || hasKind(node.parent, 209 /* ContinueStatement */)) { - return getBreakOrContinueStatementOccurrences(node.parent); - } - break; - case 86 /* ForKeyword */: - if (hasKind(node.parent, 206 /* ForStatement */) || - hasKind(node.parent, 207 /* ForInStatement */) || - hasKind(node.parent, 208 /* ForOfStatement */)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 104 /* WhileKeyword */: - case 79 /* DoKeyword */: - if (hasKind(node.parent, 205 /* WhileStatement */) || hasKind(node.parent, 204 /* DoStatement */)) { - return getLoopBreakContinueOccurrences(node.parent); - } - break; - case 121 /* ConstructorKeyword */: - if (hasKind(node.parent, 148 /* Constructor */)) { - return getConstructorOccurrences(node.parent); - } - break; - case 123 /* GetKeyword */: - case 131 /* SetKeyword */: - if (hasKind(node.parent, 149 /* GetAccessor */) || hasKind(node.parent, 150 /* SetAccessor */)) { - return getGetAndSetOccurrences(node.parent); - } - break; - default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 200 /* VariableStatement */)) { - return getModifierOccurrences(node.kind, node.parent); - } - } - } - return undefined; - } - /** - * Aggregates all throw-statements within this node *without* crossing - * into function boundaries and try-blocks with catch-clauses. - */ - function aggregateOwnedThrowStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 215 /* ThrowStatement */) { - statementAccumulator.push(node); - } - else if (node.kind === 216 /* TryStatement */) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); - } - else { - // Exceptions thrown within a try block lacking a catch clause - // are "owned" in the current context. - aggregate(tryStatement.tryBlock); - } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); - } - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - /** - * For lack of a better name, this function takes a throw statement and returns the - * nearest ancestor that is a try-block (whose try statement has a catch clause), - * function-block, or source file. - */ - function getThrowStatementOwner(throwStatement) { - var child = throwStatement; - while (child.parent) { - var parent_20 = child.parent; - if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256 /* SourceFile */) { - return parent_20; - } - // A throw-statement is only owned by a try-statement if the try-statement has - // a catch clause, and if the throw-statement occurs within the try block. - if (parent_20.kind === 216 /* TryStatement */) { - var tryStatement = parent_20; - if (tryStatement.tryBlock === child && tryStatement.catchClause) { - return child; - } - } - child = parent_20; - } - return undefined; - } - function aggregateAllBreakAndContinueStatements(node) { - var statementAccumulator = []; - aggregate(node); - return statementAccumulator; - function aggregate(node) { - if (node.kind === 210 /* BreakStatement */ || node.kind === 209 /* ContinueStatement */) { - statementAccumulator.push(node); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, aggregate); - } - } - } - function ownsBreakOrContinueStatement(owner, statement) { - var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; - } - function getBreakOrContinueOwner(statement) { - for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) { - switch (node_1.kind) { - case 213 /* SwitchStatement */: - if (statement.kind === 209 /* ContinueStatement */) { - continue; - } - // Fall through. - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: - case 204 /* DoStatement */: - if (!statement.label || isLabeledBy(node_1, statement.label.text)) { - return node_1; - } - break; - default: - // Don't cross function boundaries. - if (ts.isFunctionLike(node_1)) { - return undefined; - } - break; - } - } - return undefined; - } - function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; - // Make sure we only highlight the keyword when it makes sense to do so. - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 221 /* ClassDeclaration */ || - container.kind === 192 /* ClassExpression */ || - (declaration.kind === 142 /* Parameter */ && hasKind(container, 148 /* Constructor */)))) { - return undefined; - } - } - else if (modifier === 113 /* StaticKeyword */) { - if (!(container.kind === 221 /* ClassDeclaration */ || container.kind === 192 /* ClassExpression */)) { - return undefined; - } - } - else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { - if (!(container.kind === 226 /* ModuleBlock */ || container.kind === 256 /* SourceFile */)) { - return undefined; - } - } - else if (modifier === 115 /* AbstractKeyword */) { - if (!(container.kind === 221 /* ClassDeclaration */ || declaration.kind === 221 /* ClassDeclaration */)) { - return undefined; - } - } - else { - // unsupported modifier - return undefined; - } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; - switch (container.kind) { - case 226 /* ModuleBlock */: - case 256 /* SourceFile */: - // Container is either a class declaration or the declaration is a classDeclaration - if (modifierFlag & 128 /* Abstract */) { - nodes = declaration.members.concat(declaration); - } - else { - nodes = container.statements; - } - break; - case 148 /* Constructor */: - nodes = container.parameters.concat(container.parent.members); - break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - nodes = container.members; - // If we're an accessibility modifier, we're in an instance member and should search - // the constructor's parameter list for instance members as well. - if (modifierFlag & 28 /* AccessibilityModifier */) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 148 /* Constructor */ && member; - }); - if (constructor) { - nodes = nodes.concat(constructor.parameters); - } - } - else if (modifierFlag & 128 /* Abstract */) { - nodes = nodes.concat(container); - } - break; - default: - ts.Debug.fail("Invalid container kind."); - } - ts.forEach(nodes, function (node) { - if (node.modifiers && node.flags & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - function getFlagFromModifier(modifier) { - switch (modifier) { - case 112 /* PublicKeyword */: - return 4 /* Public */; - case 110 /* PrivateKeyword */: - return 8 /* Private */; - case 111 /* ProtectedKeyword */: - return 16 /* Protected */; - case 113 /* StaticKeyword */: - return 32 /* Static */; - case 82 /* ExportKeyword */: - return 1 /* Export */; - case 122 /* DeclareKeyword */: - return 2 /* Ambient */; - case 115 /* AbstractKeyword */: - return 128 /* Abstract */; - default: - ts.Debug.fail(); - } - } - } - function pushKeywordIf(keywordList, token) { - var expected = []; - for (var _i = 2; _i < arguments.length; _i++) { - expected[_i - 2] = arguments[_i]; - } - if (token && ts.contains(expected, token.kind)) { - keywordList.push(token); - return true; - } - return false; - } - function getGetAndSetOccurrences(accessorDeclaration) { - var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 149 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 150 /* SetAccessor */); - return ts.map(keywords, getHighlightSpanForNode); - function tryPushAccessorKeyword(accessorSymbol, accessorKind) { - var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); - if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123 /* GetKeyword */, 131 /* SetKeyword */); }); - } - } - } - function getConstructorOccurrences(constructorDeclaration) { - var declarations = constructorDeclaration.symbol.getDeclarations(); - var keywords = []; - ts.forEach(declarations, function (declaration) { - ts.forEach(declaration.getChildren(), function (token) { - return pushKeywordIf(keywords, token, 121 /* ConstructorKeyword */); - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getLoopBreakContinueOccurrences(loopNode) { - var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { - // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 204 /* DoStatement */) { - var loopTokens = loopNode.getChildren(); - for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { - break; - } - } - } - } - var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); - } - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { - var owner = getBreakOrContinueOwner(breakOrContinueStatement); - if (owner) { - switch (owner.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - return getLoopBreakContinueOccurrences(owner); - case 213 /* SwitchStatement */: - return getSwitchCaseDefaultOccurrences(owner); - } - } - return undefined; - } - function getSwitchCaseDefaultOccurrences(switchStatement) { - var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); - // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. - ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); - var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); - ts.forEach(breaksAndContinues, function (statement) { - if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); - } - }); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getTryCatchFinallyOccurrences(tryStatement) { - var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); - if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); - } - if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getThrowOccurrences(throwStatement) { - var owner = getThrowStatementOwner(throwStatement); - if (!owner) { - return undefined; - } - var keywords = []; - ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); - }); - // If the "owner" is a function, then we equate 'return' and 'throw' statements in their - // ability to "jump out" of the function, and include occurrences for both. - if (ts.isFunctionBlock(owner)) { - ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); - }); - } - return ts.map(keywords, getHighlightSpanForNode); - } - function getReturnOccurrences(returnStatement) { - var func = ts.getContainingFunction(returnStatement); - // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 199 /* Block */))) { - return undefined; - } - var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); - }); - // Include 'throw' statements that do not occur within a try block. - ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); - }); - return ts.map(keywords, getHighlightSpanForNode); - } - function getIfElseOccurrences(ifStatement) { - var keywords = []; - // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 203 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); - // Generally the 'else' keyword is second-to-last, so we traverse backwards. - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 203 /* IfStatement */)) { - break; - } - ifStatement = ifStatement.elseStatement; - } - var result = []; - // We'd like to highlight else/ifs together if they are only separated by whitespace - // (i.e. the keywords are separated by no comments, no newlines). - for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { - var elseKeyword = keywords[i]; - var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. - var shouldCombindElseAndIf = true; - // Avoid recalculating getStart() by iterating backwards. - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { - if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; - break; - } - } - if (shouldCombindElseAndIf) { - result.push({ - fileName: fileName, - textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: HighlightSpanKind.reference - }); - i++; // skip the next keyword - continue; - } - } - // Ordinary case: just highlight the keyword. - result.push(getHighlightSpanForNode(keywords[i])); - } - return result; - } - } + return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch); } /// References and Occurrences function getOccurrencesAtPositionCore(fileName, position) { @@ -56414,7 +73527,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, isDefinition: false }); } @@ -56422,24 +73535,13 @@ var ts; return result; } } - function convertReferences(referenceSymbols) { - if (!referenceSymbols) { - return undefined; - } - var referenceEntries = []; - for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { - var referenceSymbol = referenceSymbols_1[_i]; - ts.addRange(referenceEntries, referenceSymbol.references); - } - return referenceEntries; - } function findRenameLocations(fileName, position, findInStrings, findInComments) { var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); - return convertReferences(referencedSymbols); + return ts.FindAllReferences.convertReferences(referencedSymbols); } function findReferences(fileName, position) { var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); @@ -56448,843 +73550,13 @@ var ts; } function findReferencedSymbols(fileName, position, findInStrings, findInComments) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - if (node === sourceFile) { - return undefined; - } - switch (node.kind) { - case 8 /* NumericLiteral */: - if (!isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - break; - } - // Fallthrough - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - // case SyntaxKind.SuperKeyword: TODO:GH#9268 - case 9 /* StringLiteral */: - return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); - } - return undefined; - } - function isThis(node) { - switch (node.kind) { - case 97 /* ThisKeyword */: - // case SyntaxKind.ThisType: TODO: GH#9267 - return true; - case 69 /* Identifier */: - // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; - default: - return false; - } - } - function getReferencedSymbolsForNode(node, sourceFiles, findInStrings, findInComments) { - var typeChecker = program.getTypeChecker(); - // Labels - if (isLabelName(node)) { - if (isJumpStatementTarget(node)) { - var labelDefinition = getTargetLabel(node.parent, node.text); - // if we have a label definition, look within its statement for references, if not, then - // the label is undefined and we have no results.. - return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; - } - else { - // it is a label definition and not a target, search within the parent labeledStatement - return getLabelReferencesInNode(node.parent, node); - } - } - if (isThis(node)) { - return getReferencesForThisKeyword(node, sourceFiles); - } - if (node.kind === 95 /* SuperKeyword */) { - return getReferencesForSuperKeyword(node); - } - var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles); - } - // Could not find a symbol e.g. unknown identifier - if (!symbol) { - // Can't have references to something that we have no symbol for. - return undefined; - } - var declarations = symbol.declarations; - // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!declarations || !declarations.length) { - return undefined; - } - var result; - // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); - // Get the text to search for. - // Note: if this is an external module symbol, the name doesn't include quotes. - var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - // Maps from a symbol ID to the ReferencedSymbol entry in 'result'. - var symbolToIndex = []; - if (scope) { - result = []; - getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; - cancellationToken.throwIfCancellationRequested(); - var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { - result = result || []; - getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); - } - } - } - return result; - function getDefinition(symbol) { - var info = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, node.getSourceFile(), getContainerNode(node), node); - var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); - var declarations = symbol.declarations; - if (!declarations || declarations.length === 0) { - return undefined; - } - return { - containerKind: "", - containerName: "", - name: name, - kind: info.symbolKind, - fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0) - }; - } - function getAliasSymbolForPropertyNameSymbol(symbol, location) { - if (symbol.flags & 8388608 /* Alias */) { - // Default import get alias - var defaultImport = ts.getDeclarationOfKind(symbol, 231 /* ImportClause */); - if (defaultImport) { - return typeChecker.getAliasedSymbol(symbol); - } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 /* ImportSpecifier */ || - declaration.kind === 238 /* ExportSpecifier */) ? declaration : undefined; }); - if (importOrExportSpecifier && - // export { a } - (!importOrExportSpecifier.propertyName || - // export {a as class } where a is location - importOrExportSpecifier.propertyName === location)) { - // If Import specifier -> get alias - // else Export specifier -> get local target - return importOrExportSpecifier.kind === 234 /* ImportSpecifier */ ? - typeChecker.getAliasedSymbol(symbol) : - typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); - } - } - return undefined; - } - function getPropertySymbolOfDestructuringAssignment(location) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - typeChecker.getPropertySymbolOfDestructuringAssignment(location); - } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); - return bindingElement && - bindingElement.parent.kind === 167 /* ObjectBindingPattern */ && - !bindingElement.propertyName; - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); - var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); - return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - } - return undefined; - } - function getInternedName(symbol, location, declarations) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever under the cursor. - if (ts.isImportOrExportSpecifierName(location)) { - return location.getText(); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - symbol = localExportDefaultSymbol || symbol; - return ts.stripQuotes(symbol.name); - } - /** - * Determines the smallest scope in which a symbol may have named references. - * Note that not every construct has been accounted for. This function can - * probably be improved. - * - * @returns undefined if the scope cannot be determined, implying that - * a reference to a symbol can occur anywhere. - */ - function getSymbolScope(symbol) { - // If this is the symbol of a named function expression or named class expression, - // then named references are limited to its own scope. - var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { - return valueDeclaration; - } - // If this is private property or method, the scope is the containing class - if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); - if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); - } - } - // If the symbol is an import we would like to find it if we are looking for what it imports. - // So consider it visible outside its declaration scope. - if (symbol.flags & 8388608 /* Alias */) { - return undefined; - } - // If symbol is of object binding pattern element without property name we would want to - // look for property too and that could be anywhere - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - return undefined; - } - // if this symbol is visible from its parent container, e.g. exported, then bail out - // if symbol correspond to the union property - bail out - if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { - return undefined; - } - var scope; - var declarations = symbol.getDeclarations(); - if (declarations) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - var container = getContainerNode(declaration); - if (!container) { - return undefined; - } - if (scope && scope !== container) { - // Different declarations have different containers, bail out - return undefined; - } - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { - // This is a global variable and not an external module, any declaration defined - // within this scope is visible outside the file - return undefined; - } - // The search scope is the container node - scope = container; - } - } - return scope; - } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { - var positions = []; - /// TODO: Cache symbol existence for files to save text search - // Also, need to make this work for unicode escapes. - // Be resilient in the face of a symbol with no name or zero length name - if (!symbolName || !symbolName.length) { - return positions; - } - var text = sourceFile.text; - var sourceLength = text.length; - var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); - while (position >= 0) { - cancellationToken.throwIfCancellationRequested(); - // If we are past the end, stop looking - if (position > end) - break; - // We found a match. Make sure it's not part of a larger word (i.e. the char - // before and after it have to be a non-identifier char). - var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { - // Found a real match. Keep searching. - positions.push(position); - } - position = text.indexOf(symbolName, position + symbolNameLength + 1); - } - return positions; - } - function getLabelReferencesInNode(container, targetLabel) { - var references = []; - var sourceFile = container.getSourceFile(); - var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.getWidth() !== labelName.length) { - return; - } - // Only pick labels that are either the target label, or have a target that is the target label - if (node === targetLabel || - (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = { - containerKind: "", - containerName: "", - fileName: targetLabel.getSourceFile().fileName, - kind: ScriptElementKind.label, - name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) - }; - return [{ definition: definition, references: references }]; - } - function isValidReferencePosition(node, searchSymbolName) { - if (node) { - // Compare the length so we filter out strict superstrings of the symbol we are looking for - switch (node.kind) { - case 69 /* Identifier */: - return node.getWidth() === searchSymbolName.length; - case 9 /* StringLiteral */: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isNameOfExternalModuleImportOrDeclaration(node)) { - // For string literals we have two additional chars for the quotes - return node.getWidth() === searchSymbolName.length + 2; - } - break; - case 8 /* NumericLiteral */: - if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - return node.getWidth() === searchSymbolName.length; - } - break; - } - } - return false; - } - /** Search within node "container" for references for a search value, where the search value is defined as a - * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). - * searchLocation: a node where the search value - */ - function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { - var sourceFile = container.getSourceFile(); - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0) { - var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); - referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); - } - } - }); - } - return; - function getReferencedSymbol(symbol) { - var symbolId = ts.getSymbolId(symbol); - var index = symbolToIndex[symbolId]; - if (index === undefined) { - index = result.length; - symbolToIndex[symbolId] = index; - result.push({ - definition: getDefinition(symbol), - references: [] - }); - } - return result[index]; - } - function isInNonReferenceComment(sourceFile, position) { - return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - } - function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); - if (!searchSpaceNode) { - return undefined; - } - // Whether 'super' occurs in a static context within a class. - var staticFlag = 32 /* Static */; - switch (searchSpaceNode.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class - break; - default: - return undefined; - } - var references = []; - var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95 /* SuperKeyword */) { - return; - } - var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); - // If we have a 'super' container, we must have an enclosing class. - // Now make sure the owning class is the same as the search-space - // and has the same static qualifier as the original 'super's owner. - if (container && (32 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { - references.push(getReferenceEntryFromNode(node)); - } - }); - var definition = getDefinition(searchSpaceNode.symbol); - return [{ definition: definition, references: references }]; - } - function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { - var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); - // Whether 'this' occurs in a static context within a class. - var staticFlag = 32 /* Static */; - switch (searchSpaceNode.kind) { - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - if (ts.isObjectLiteralMethod(searchSpaceNode)) { - break; - } - // fall through - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - staticFlag &= searchSpaceNode.flags; - searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class - break; - case 256 /* SourceFile */: - if (ts.isExternalModule(searchSpaceNode)) { - return undefined; - } - // Fall through - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - break; - // Computed properties in classes are not handled here because references to this are illegal, - // so there is no point finding references to them. - default: - return undefined; - } - var references = []; - var possiblePositions; - if (searchSpaceNode.kind === 256 /* SourceFile */) { - ts.forEach(sourceFiles, function (sourceFile) { - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); - getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); - }); - } - else { - var sourceFile = searchSpaceNode.getSourceFile(); - possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); - getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: "this", - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { - ts.forEach(possiblePositions, function (position) { - cancellationToken.throwIfCancellationRequested(); - var node = ts.getTouchingWord(sourceFile, position); - if (!node || !isThis(node)) { - return; - } - var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); - switch (searchSpaceNode.kind) { - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - if (searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: - // Make sure the container belongs to the same class - // and has the appropriate static modifier from the original container. - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 32 /* Static */) === staticFlag) { - result.push(getReferenceEntryFromNode(node)); - } - break; - case 256 /* SourceFile */: - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { - result.push(getReferenceEntryFromNode(node)); - } - break; - } - }); - } - } - function getReferencesForStringLiteral(node, sourceFiles) { - var typeChecker = program.getTypeChecker(); - var type = getStringLiteralTypeForNode(node, typeChecker); - if (!type) { - // nothing to do here. moving on - return undefined; - } - var references = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); - getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); - } - return [{ - definition: { - containerKind: "", - containerName: "", - fileName: node.getSourceFile().fileName, - kind: ScriptElementKind.variableElement, - name: type.text, - textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) - }, - references: references - }]; - function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) { - for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { - var position = possiblePositions_1[_i]; - cancellationToken.throwIfCancellationRequested(); - var node_2 = ts.getTouchingWord(sourceFile, position); - if (!node_2 || node_2.kind !== 9 /* StringLiteral */) { - return; - } - var type_1 = getStringLiteralTypeForNode(node_2, typeChecker); - if (type_1 === searchType) { - references.push(getReferenceEntryFromNode(node_2)); - } - } - } - } - function populateSearchSymbolSet(symbol, location) { - // The search set contains at least the current symbol - var result = [symbol]; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254 /* ShorthandPropertyAssignment */) { - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); - if (propertySymbol) { - result.push(propertySymbol); - } - } - // If the symbol is an alias, add what it aliases to the list - // import {a} from "mod"; - // export {a} - // If the symbol is an alias to default declaration, add what it aliases to the list - // declare "mod" { export default class B { } } - // import B from "mod"; - //// For export specifiers, the exported name can be referring to a local symbol, e.g.: - //// import {a} from "mod"; - //// export {a as somethingElse} - //// We want the *local* declaration of 'a' as declared in the import, - //// *not* as declared within "mod" (or farther) - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location); - if (aliasSymbol) { - result = result.concat(populateSearchSymbolSet(aliasSymbol, location)); - } - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - if (containingObjectLiteralElement) { - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); - }); - /* Because in short-hand property assignment, location has two meaning : property name and as value of the property - * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of - * property name and variable declaration of the identifier. - * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service - * should show both 'name' in 'obj' and 'name' in variable declaration - * const name = "Foo"; - * const obj = { name }; - * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment - * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration - * will be included correctly. - */ - var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); - if (shorthandValueSymbol) { - result.push(shorthandValueSymbol); - } - } - // If the symbol.valueDeclaration is a property parameter declaration, - // we should include both parameter declaration symbol and property declaration symbol - // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. - // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 /* Parameter */ && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol); - if (bindingElementPropertySymbol) { - result.push(bindingElementPropertySymbol); - } - // If this is a union property, add all the symbols from all its source symbols in all unioned types. - // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list - ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ {}); - } - }); - return result; - } - /** - * Find symbol of the given property-name and add the symbol to the given result array - * @param symbol a symbol to start searching for the given propertyName - * @param propertyName a name of property to search for - * @param result an array of symbol of found property symbols - * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. - * The value of previousIterationSymbol is undefined when the function is first called. - */ - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { - if (!symbol) { - return; - } - // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited - // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. - // For example: - // interface C extends C { - // /*findRef*/propName: string; - // } - // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, - // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, - // the function will add any found symbol of the property-name, then its sub-routine will call - // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already - // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. - if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { - return; - } - if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === 222 /* InterfaceDeclaration */) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } - }); - } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = typeChecker.getTypeAtLocation(typeReference); - if (type) { - var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); - if (propertySymbol) { - result.push.apply(result, typeChecker.getRootSymbols(propertySymbol)); - } - // Visit the typeReference as well to see if it directly or indirectly use that property - previousIterationSymbolsCache[symbol.name] = symbol; - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); - } - } - } - } - function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation) { - if (searchSymbols.indexOf(referenceSymbol) >= 0) { - return referenceSymbol; - } - // If the reference symbol is an alias, check if what it is aliasing is one of the search - // symbols but by looking up for related symbol of this alias so it can handle multiple level of indirectness. - var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation); - if (aliasSymbol) { - return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation); - } - // If the reference location is in an object literal, try to get the contextual type for the - // object literal, lookup the property symbol in the contextual type, and use this symbol to - // compare to our searchSymbol - var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); - if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) { - return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - }); - if (contextualSymbol) { - return contextualSymbol; - } - // If the reference location is the name of property from object literal destructuring pattern - // Get the property symbol from the object literal's type and look if thats the search symbol - // In below eg. get 'property' from type of elems iterating type - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation); - if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) { - return propertySymbol; - } - } - // If the reference location is the binding element and doesn't have property name - // then include the binding element in the related symbols - // let { a } : { a }; - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol); - if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) { - return bindingElementPropertySymbol; - } - // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) - // Or a union property, use its underlying unioned symbols - return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { - // if it is in the list, then we are done - if (searchSymbols.indexOf(rootSymbol) >= 0) { - return rootSymbol; - } - // Finally, try all properties with the same name in any type the containing type extended or implemented, and - // see if any is in the list - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - var result_4 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ {}); - return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); - } - return undefined; - }); - } - function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { - return nameExpression.text; - } - return undefined; - } - return node.name.text; - } - function getPropertySymbolsFromContextualType(node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol_1 = contextualType.getProperty(name); - if (symbol_1) { - result_5.push(symbol_1); - } - if (contextualType.flags & 16384 /* Union */) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; - } - /** Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations - * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class - * then we need to widen the search to include type positions as well. - * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated - * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) - * do not intersect in any of the three spaces. - */ - function getIntersectingMeaningFromDeclarations(meaning, declarations) { - if (declarations) { - var lastIterationMeaning = void 0; - do { - // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] - // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module - // intersects with the class in the value space. - // To achieve that we will keep iterating until the result stabilizes. - // Remember the last meaning - lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; - var declarationMeaning = getMeaningFromDeclaration(declaration); - if (declarationMeaning & meaning) { - meaning |= declarationMeaning; - } - } - } while (meaning !== lastIterationMeaning); - } - return meaning; - } - } - function getReferenceEntryFromNode(node) { - var start = node.getStart(); - var end = node.getEnd(); - if (node.kind === 9 /* StringLiteral */) { - start += 1; - end -= 1; - } - return { - fileName: node.getSourceFile().fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) - }; - } - /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ - function isWriteAccess(node) { - if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { - return true; - } - var parent = node.parent; - if (parent) { - if (parent.kind === 186 /* PostfixUnaryExpression */ || parent.kind === 185 /* PrefixUnaryExpression */) { - return true; - } - else if (parent.kind === 187 /* BinaryExpression */ && parent.left === node) { - var operator = parent.operatorToken.kind; - return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; - } - } - return false; + return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount) { + function getNavigateToItems(searchValue, maxResultCount, fileName) { synchronizeHostData(); - var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); + var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -57303,134 +73575,6 @@ var ts; emitSkipped: emitOutput.emitSkipped }; } - function getMeaningFromDeclaration(node) { - switch (node.kind) { - case 142 /* Parameter */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 252 /* CatchClause */: - return 1 /* Value */; - case 141 /* TypeParameter */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 159 /* TypeLiteral */: - return 2 /* Type */; - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - return 1 /* Value */ | 2 /* Type */; - case 225 /* ModuleDeclaration */: - if (ts.isAmbientModule(node)) { - return 4 /* Namespace */ | 1 /* Value */; - } - else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { - return 4 /* Namespace */ | 1 /* Value */; - } - else { - return 4 /* Namespace */; - } - case 233 /* NamedImports */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 230 /* ImportDeclaration */: - case 235 /* ExportAssignment */: - case 236 /* ExportDeclaration */: - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - // An external module can be a Value - case 256 /* SourceFile */: - return 4 /* Namespace */ | 1 /* Value */; - } - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - } - function isTypeReference(node) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - return node.parent.kind === 155 /* TypeReference */ || - (node.parent.kind === 194 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node)) || - node.kind === 165 /* ThisType */; - } - function isNamespaceReference(node) { - return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); - } - function isPropertyAccessNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 172 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 172 /* PropertyAccessExpression */) { - root = root.parent; - } - isLastClause = root.name === node; - } - if (!isLastClause && root.parent.kind === 194 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 251 /* HeritageClause */) { - var decl = root.parent.parent.parent; - return (decl.kind === 221 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 222 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); - } - return false; - } - function isQualifiedNameNamespaceReference(node) { - var root = node; - var isLastClause = true; - if (root.parent.kind === 139 /* QualifiedName */) { - while (root.parent && root.parent.kind === 139 /* QualifiedName */) { - root = root.parent; - } - isLastClause = root.right === node; - } - return root.parent.kind === 155 /* TypeReference */ && !isLastClause; - } - function isInRightSideOfImport(node) { - while (node.parent.kind === 139 /* QualifiedName */) { - node = node.parent; - } - return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; - } - function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69 /* Identifier */); - // import a = |b|; // Namespace - // import a = |b.c|; // Value, type, namespace - // import a = |b.c|.d; // Namespace - if (node.parent.kind === 139 /* QualifiedName */ && - node.parent.right === node && - node.parent.parent.kind === 229 /* ImportEqualsDeclaration */) { - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - } - return 4 /* Namespace */; - } - function getMeaningFromLocation(node) { - if (node.parent.kind === 235 /* ExportAssignment */) { - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - } - else if (isInRightSideOfImport(node)) { - return getMeaningFromRightHandSideOfImportEquals(node); - } - else if (ts.isDeclarationName(node)) { - return getMeaningFromDeclaration(node.parent); - } - else if (isTypeReference(node)) { - return 2 /* Type */; - } - else if (isNamespaceReference(node)) { - return 4 /* Namespace */; - } - else { - return 1 /* Value */; - } - } // Signature help /** * This is a semantic operation. @@ -57444,6 +73588,9 @@ var ts; function getNonBoundSourceFile(fileName) { return syntaxTreeCache.getCurrentSourceFile(fileName); } + function getSourceFile(fileName) { + return getNonBoundSourceFile(fileName); + } function getNameOrDottedNameSpan(fileName, startPos, endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location @@ -57455,7 +73602,6 @@ var ts; case 172 /* PropertyAccessExpression */: case 139 /* QualifiedName */: case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: @@ -57470,11 +73616,11 @@ var ts; } var nodeForStartPos = node; while (true) { - if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) { + if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node nodeForStartPos = nodeForStartPos.parent; } - else if (isNameOfModuleDeclaration(nodeForStartPos)) { + else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module @@ -57505,462 +73651,20 @@ var ts; return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { - return convertClassifications(getEncodedSemanticClassifications(fileName, span)); - } - function checkForClassificationCancellation(kind) { - // We don't want to actually call back into our host on every node to find out if we've - // been canceled. That would be an enormous amount of chattyness, along with the all - // the overhead of marshalling the data to/from the host. So instead we pick a few - // reasonable node kinds to bother checking on. These node kinds represent high level - // constructs that we would expect to see commonly, but just at a far less frequent - // interval. - // - // For example, in checker.ts (around 750k) we only have around 600 of these constructs. - // That means we're calling back into the host around every 1.2k of the file we process. - // Lib.d.ts has similar numbers. - switch (kind) { - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - cancellationToken.throwIfCancellationRequested(); - } + synchronizeHostData(); + return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); - var result = []; - var classifiableNames = program.getClassifiableNames(); - processNode(sourceFile); - return { spans: result, endOfLineState: 0 /* None */ }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448 /* Classifiable */) === 0 /* None */) { - return; - } - if (flags & 32 /* Class */) { - return 11 /* className */; - } - else if (flags & 384 /* Enum */) { - return 12 /* enumName */; - } - else if (flags & 524288 /* TypeAlias */) { - return 16 /* typeAliasName */; - } - else if (meaningAtPosition & 2 /* Type */) { - if (flags & 64 /* Interface */) { - return 13 /* interfaceName */; - } - else if (flags & 262144 /* TypeParameter */) { - return 15 /* typeParameterName */; - } - } - else if (flags & 1536 /* Module */) { - // Only classify a module as such if - // - It appears in a namespace context. - // - There exists a module declaration which actually impacts the value side. - if (meaningAtPosition & 4 /* Namespace */ || - (meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) { - return 14 /* moduleName */; - } - } - return undefined; - /** - * Returns true if there exists a module that introduces entities on the value side. - */ - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 /* ModuleDeclaration */ && - ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; - }); - } - } - function processNode(node) { - // Only walk into nodes that intersect the requested span. - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(kind); - if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { - var identifier = node; - // Only bother calling into the typechecker if this is an identifier that - // could possibly resolve to a type name. This makes classification run - // in a third of the time it would normally take. - if (classifiableNames[identifier.text]) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } - } - } - function getClassificationTypeName(type) { - switch (type) { - case 1 /* comment */: return ClassificationTypeNames.comment; - case 2 /* identifier */: return ClassificationTypeNames.identifier; - case 3 /* keyword */: return ClassificationTypeNames.keyword; - case 4 /* numericLiteral */: return ClassificationTypeNames.numericLiteral; - case 5 /* operator */: return ClassificationTypeNames.operator; - case 6 /* stringLiteral */: return ClassificationTypeNames.stringLiteral; - case 8 /* whiteSpace */: return ClassificationTypeNames.whiteSpace; - case 9 /* text */: return ClassificationTypeNames.text; - case 10 /* punctuation */: return ClassificationTypeNames.punctuation; - case 11 /* className */: return ClassificationTypeNames.className; - case 12 /* enumName */: return ClassificationTypeNames.enumName; - case 13 /* interfaceName */: return ClassificationTypeNames.interfaceName; - case 14 /* moduleName */: return ClassificationTypeNames.moduleName; - case 15 /* typeParameterName */: return ClassificationTypeNames.typeParameterName; - case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; - case 17 /* parameterName */: return ClassificationTypeNames.parameterName; - case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; - case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName; - case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName; - case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName; - case 22 /* jsxAttribute */: return ClassificationTypeNames.jsxAttribute; - case 23 /* jsxText */: return ClassificationTypeNames.jsxText; - case 24 /* jsxAttributeStringLiteralValue */: return ClassificationTypeNames.jsxAttributeStringLiteralValue; - } - } - function convertClassifications(classifications) { - ts.Debug.assert(classifications.spans.length % 3 === 0); - var dense = classifications.spans; - var result = []; - for (var i = 0, n = dense.length; i < n; i += 3) { - result.push({ - textSpan: ts.createTextSpan(dense[i], dense[i + 1]), - classificationType: getClassificationTypeName(dense[i + 2]) - }); - } - return result; + return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getSyntacticClassifications(fileName, span) { - return convertClassifications(getEncodedSyntacticClassifications(fileName, span)); + // doesn't use compiler - no need to synchronize with host + return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getEncodedSyntacticClassifications(fileName, span) { // doesn't use compiler - no need to synchronize with host - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var spanStart = span.start; - var spanLength = span.length; - // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var result = []; - processElement(sourceFile); - return { spans: result, endOfLineState: 0 /* None */ }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifyLeadingTriviaAndGetTokenStart(token) { - triviaScanner.setTextPos(token.pos); - while (true) { - var start = triviaScanner.getTextPos(); - // only bother scanning if we have something that could be trivia. - if (!ts.couldStartTrivia(sourceFile.text, start)) { - return start; - } - var kind = triviaScanner.scan(); - var end = triviaScanner.getTextPos(); - var width = end - start; - // The moment we get something that isn't trivia, then stop processing. - if (!ts.isTrivia(kind)) { - return start; - } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); - continue; - } - // for the ======== add a comment for the first line, and then lex all - // subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); - } - } - } - function classifyComment(token, kind, start, width) { - if (kind === 3 /* MultiLineCommentTrivia */) { - // See if this is a doc comment. If so, we'll classify certain portions of it - // specially. - var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); - if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { - docCommentAndDiagnostics.jsDocComment.parent = token; - classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); - return; - } - } - // Simple comment. Just add as is. - pushCommentRange(start, width); - } - function pushCommentRange(start, width) { - pushClassification(start, width, 1 /* comment */); - } - function classifyJSDocComment(docComment) { - var pos = docComment.pos; - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - // As we walk through each tag, classify the portion of text from the end of - // the last tag (or the start of the entire doc comment) as 'comment'. - if (tag.pos !== pos) { - pushCommentRange(pos, tag.pos - pos); - } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); - pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); - pos = tag.tagName.end; - switch (tag.kind) { - case 275 /* JSDocParameterTag */: - processJSDocParameterTag(tag); - break; - case 278 /* JSDocTemplateTag */: - processJSDocTemplateTag(tag); - break; - case 277 /* JSDocTypeTag */: - processElement(tag.typeExpression); - break; - case 276 /* JSDocReturnTag */: - processElement(tag.typeExpression); - break; - } - pos = tag.end; - } - if (pos !== docComment.end) { - pushCommentRange(pos, docComment.end - pos); - } - return; - function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); - pos = tag.preParameterName.end; - } - if (tag.typeExpression) { - pushCommentRange(pos, tag.typeExpression.pos - pos); - processElement(tag.typeExpression); - pos = tag.typeExpression.end; - } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); - pos = tag.postParameterName.end; - } - } - } - function processJSDocTemplateTag(tag) { - for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { - var child = _a[_i]; - processElement(child); - } - } - function classifyDisabledMergeCode(text, start, end) { - // Classify the line that the ======= marker is on as a comment. Then just lex - // all further tokens and add them to the result. - var i; - for (i = start; i < end; i++) { - if (ts.isLineBreak(text.charCodeAt(i))) { - break; - } - } - pushClassification(start, i - start, 1 /* comment */); - mergeConflictScanner.setTextPos(i); - while (mergeConflictScanner.getTextPos() < end) { - classifyDisabledCodeToken(); - } - } - function classifyDisabledCodeToken() { - var start = mergeConflictScanner.getTextPos(); - var tokenKind = mergeConflictScanner.scan(); - var end = mergeConflictScanner.getTextPos(); - var type = classifyTokenType(tokenKind); - if (type) { - pushClassification(start, end - start, type); - } - } - /** - * Returns true if node should be treated as classified and no further processing is required. - * False will mean that node is not classified and traverse routine should recurse into node contents. - */ - function tryClassifyNode(node) { - if (ts.nodeIsMissing(node)) { - return true; - } - var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { - return false; - } - var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); - var tokenWidth = node.end - tokenStart; - ts.Debug.assert(tokenWidth >= 0); - if (tokenWidth > 0) { - var type = classifiedElementName || classifyTokenType(node.kind, node); - if (type) { - pushClassification(tokenStart, tokenWidth, type); - } - } - return true; - } - function tryClassifyJsxElementName(token) { - switch (token.parent && token.parent.kind) { - case 243 /* JsxOpeningElement */: - if (token.parent.tagName === token) { - return 19 /* jsxOpenTagName */; - } - break; - case 245 /* JsxClosingElement */: - if (token.parent.tagName === token) { - return 20 /* jsxCloseTagName */; - } - break; - case 242 /* JsxSelfClosingElement */: - if (token.parent.tagName === token) { - return 21 /* jsxSelfClosingTagName */; - } - break; - case 246 /* JsxAttribute */: - if (token.parent.name === token) { - return 22 /* jsxAttribute */; - } - break; - } - return undefined; - } - // 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, token) { - if (ts.isKeyword(tokenKind)) { - return 3 /* keyword */; - } - // Special case < and > If they appear in a generic context they are punctuation, - // not operators. - if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { - // 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 && ts.getTypeArgumentOrTypeParameterList(token.parent)) { - return 10 /* punctuation */; - } - } - if (ts.isPunctuation(tokenKind)) { - if (token) { - if (tokenKind === 56 /* EqualsToken */) { - // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 218 /* VariableDeclaration */ || - token.parent.kind === 145 /* PropertyDeclaration */ || - token.parent.kind === 142 /* Parameter */ || - token.parent.kind === 246 /* JsxAttribute */) { - return 5 /* operator */; - } - } - if (token.parent.kind === 187 /* BinaryExpression */ || - token.parent.kind === 185 /* PrefixUnaryExpression */ || - token.parent.kind === 186 /* PostfixUnaryExpression */ || - token.parent.kind === 188 /* ConditionalExpression */) { - return 5 /* operator */; - } - } - return 10 /* punctuation */; - } - else if (tokenKind === 8 /* NumericLiteral */) { - return 4 /* numericLiteral */; - } - else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 166 /* StringLiteralType */) { - return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; - } - else if (tokenKind === 10 /* RegularExpressionLiteral */) { - // TODO: we should get another classification type for these literals. - return 6 /* stringLiteral */; - } - else if (ts.isTemplateLiteralKind(tokenKind)) { - // TODO (drosen): we should *also* get another classification type for these literals. - return 6 /* stringLiteral */; - } - else if (tokenKind === 244 /* JsxText */) { - return 23 /* jsxText */; - } - else if (tokenKind === 69 /* Identifier */) { - if (token) { - switch (token.parent.kind) { - case 221 /* ClassDeclaration */: - if (token.parent.name === token) { - return 11 /* className */; - } - return; - case 141 /* TypeParameter */: - if (token.parent.name === token) { - return 15 /* typeParameterName */; - } - return; - case 222 /* InterfaceDeclaration */: - if (token.parent.name === token) { - return 13 /* interfaceName */; - } - return; - case 224 /* EnumDeclaration */: - if (token.parent.name === token) { - return 12 /* enumName */; - } - return; - case 225 /* ModuleDeclaration */: - if (token.parent.name === token) { - return 14 /* moduleName */; - } - return; - case 142 /* Parameter */: - if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; - } - return; - } - } - return 2 /* identifier */; - } - } - function processElement(element) { - if (!element) { - return; - } - // Ignore nodes that don't intersect the original span to classify. - if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { - checkForClassificationCancellation(element.kind); - var children = element.getChildren(sourceFile); - for (var i = 0, n = children.length; i < n; i++) { - var child = children[i]; - if (!tryClassifyNode(child)) { - // Recurse into our child nodes. - processElement(child); - } - } - } - } + return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getOutliningSpans(fileName) { // doesn't use compiler - no need to synchronize with host @@ -58010,12 +73714,12 @@ var ts; } } function getIndentationAtPosition(fileName, position, editorOptions) { - var start = new Date().getTime(); + var start = ts.timestamp(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); - start = new Date().getTime(); + log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); + start = ts.timestamp(); var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); - log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); + log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { @@ -58039,93 +73743,8 @@ var ts; } return []; } - /** - * Checks if position points to a valid position to add JSDoc comments, and if so, - * returns the appropriate template. Otherwise returns an empty string. - * Valid positions are - * - outside of comments, statements, and expressions, and - * - preceding a: - * - function/constructor/method declaration - * - class declarations - * - variable statements - * - namespace declarations - * - * Hosts should ideally check that: - * - The line is all whitespace up to 'position' before performing the insertion. - * - If the keystroke sequence "/\*\*" induced the call, we also check that the next - * non-whitespace character is '*', which (approximately) indicates whether we added - * the second '*' to complete an existing (JSDoc) comment. - * @param fileName The file in which to perform the check. - * @param position The (character-indexed) position in the file where the check should - * be performed. - */ function getDocCommentTemplateAtPosition(fileName, position) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { - return undefined; - } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); - var tokenStart = tokenAtPos.getStart(); - if (!tokenAtPos || tokenStart < position) { - return undefined; - } - // TODO: add support for: - // - enums/enum members - // - interfaces - // - property declarations - // - potentially property assignments - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - case 221 /* ClassDeclaration */: - case 200 /* VariableStatement */: - break findOwner; - case 256 /* SourceFile */: - return undefined; - case 225 /* ModuleDeclaration */: - // If in walking up the tree, we hit a a nested namespace declaration, - // then we must be somewhere within a dotted namespace name; however we don't - // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 225 /* ModuleDeclaration */) { - return undefined; - } - break findOwner; - } - } - if (!commentOwner || commentOwner.getStart() < position) { - return undefined; - } - var parameters = getParametersForJsDocOwningNode(commentOwner); - var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); - var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; - var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); - var newLine = ts.getNewLineOrDefaultFromHost(host); - var docParams = ""; - for (var i = 0, numParams = parameters.length; i < numParams; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 69 /* Identifier */ ? - currentName.text : - "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; - } - // A doc comment consists of the following - // * The opening comment line - // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) - // * the '@param'-tagged lines - // * TODO: other tags. - // * the closing comment line - // * if the caret was directly in front of the object, then we add an extra line and indentation. - var preamble = "/**" + newLine + - indentationStr + " * "; - var result = preamble + newLine + - docParams + - indentationStr + " */" + - (tokenStart === position ? newLine + indentationStr : ""); - return { newText: result, caretOffset: preamble.length }; + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -58150,46 +73769,6 @@ var ts; } return true; } - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 200 /* VariableStatement */) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); - } - } - return emptyArray; - } - /** - * Digs into an an initializer or RHS operand of an assignment operation - * to get the parameters of an apt signature corresponding to a - * function expression or a class expression. - * - * @param rightHandSide the expression which may contain an appropriate set of parameters - * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. - */ - function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178 /* ParenthesizedExpression */) { - rightHandSide = rightHandSide.expression; - } - switch (rightHandSide.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - return rightHandSide.parameters; - case 192 /* ClassExpression */: - for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148 /* Constructor */) { - return member.parameters; - } - } - break; - } - return emptyArray; - } function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually // treat it as a semantic operation here. This is because we expect our host to call @@ -58231,7 +73810,7 @@ var ts; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (!isInsideComment(sourceFile, token, matchPosition)) { + if (!ts.isInsideComment(sourceFile, token, matchPosition)) { continue; } var descriptor = undefined; @@ -58314,104 +73893,10 @@ var ts; (char >= 48 /* _0 */ && char <= 57 /* _9 */); } } - function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* StringLiteralType */ ? node.parent : node; - var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256 /* StringLiteral */) { - return type; - } - return undefined; - } function getRenameInfo(fileName, position) { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var typeChecker = program.getTypeChecker(); var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); - var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - if (node) { - if (node.kind === 69 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - isThis(node)) { - var symbol = typeChecker.getSymbolAtLocation(node); - // Only allow a symbol to be renamed if it actually has at least one declaration. - if (symbol) { - var declarations = symbol.getDeclarations(); - if (declarations && declarations.length > 0) { - // Disallow rename for elements that are defined in the standard TypeScript library. - if (ts.forEach(declarations, isDefinedInLibraryFile)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); - var kind = getSymbolKind(symbol, node); - if (kind) { - return { - canRename: true, - kind: kind, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), - kindModifiers: getSymbolModifiers(symbol), - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - else if (node.kind === 9 /* StringLiteral */) { - var type = getStringLiteralTypeForNode(node, typeChecker); - if (type) { - if (isDefinedInLibraryFile(node)) { - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); - } - else { - var displayName = ts.stripQuotes(type.text); - return { - canRename: true, - kind: ScriptElementKind.variableElement, - displayName: displayName, - localizedErrorMessage: undefined, - fullDisplayName: displayName, - kindModifiers: ScriptElementKindModifier.none, - triggerSpan: createTriggerSpanForNode(node, sourceFile) - }; - } - } - } - } - } - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); - function getRenameInfoError(localizedErrorMessage) { - return { - canRename: false, - localizedErrorMessage: localizedErrorMessage, - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; - } - function isDefinedInLibraryFile(declaration) { - if (defaultLibFileName) { - var sourceFile_2 = declaration.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (canonicalName === canonicalDefaultLibName) { - return true; - } - } - return false; - } - function createTriggerSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var width = node.getWidth(sourceFile); - if (node.kind === 9 /* StringLiteral */) { - // Exclude the quotes - start += 1; - width -= 2; - } - return ts.createTextSpan(start, width); - } + return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); } return { dispose: dispose, @@ -58425,9 +73910,11 @@ var ts; getEncodedSemanticClassifications: getEncodedSemanticClassifications, getCompletionsAtPosition: getCompletionsAtPosition, getCompletionEntryDetails: getCompletionEntryDetails, + getCompletionEntrySymbol: getCompletionEntrySymbol, getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, findReferences: findReferences, @@ -58450,6 +73937,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, + getSourceFile: getSourceFile, getProgram: getProgram }; } @@ -58463,7 +73951,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -58501,426 +73989,6 @@ var ts; node.parent.kind === 173 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } - /// Classifier - function createClassifier() { - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false); - /// We do not have a full parser support to know when we should parse a regex or not - /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where - /// we have a series of divide operator. this list allows us to be more accurate by ruling out - /// locations where a regexp cannot exist. - var noRegexTable = []; - noRegexTable[69 /* Identifier */] = true; - noRegexTable[9 /* StringLiteral */] = true; - noRegexTable[8 /* NumericLiteral */] = true; - noRegexTable[10 /* RegularExpressionLiteral */] = true; - noRegexTable[97 /* ThisKeyword */] = true; - noRegexTable[41 /* PlusPlusToken */] = true; - noRegexTable[42 /* MinusMinusToken */] = true; - noRegexTable[18 /* CloseParenToken */] = true; - noRegexTable[20 /* CloseBracketToken */] = true; - noRegexTable[16 /* CloseBraceToken */] = true; - noRegexTable[99 /* TrueKeyword */] = true; - noRegexTable[84 /* FalseKeyword */] = true; - // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) - // classification on template strings. Because of the context free nature of templates, - // the only precise way to classify a template portion would be by propagating the stack across - // lines, just as we do with the end-of-line state. However, this is a burden for implementers, - // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead - // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. - // Situations in which this fails are - // 1) When template strings are nested across different lines: - // `hello ${ `world - // ` }` - // - // Where on the second line, you will get the closing of a template, - // a closing curly, and a new template. - // - // 2) When substitution expressions have curly braces and the curly brace falls on the next line: - // `hello ${ () => { - // return "world" } } ` - // - // Where on the second line, you will get the 'return' keyword, - // a string literal, and a template end consisting of '} } `'. - var templateStack = []; - /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 /* GetKeyword */ || - keyword2 === 131 /* SetKeyword */ || - keyword2 === 121 /* ConstructorKeyword */ || - keyword2 === 113 /* StaticKeyword */) { - // Allow things like "public get", "public constructor" and "public static". - // These are all legal. - return true; - } - // Any other keyword following "public" is actually an identifier an not a real - // keyword. - return false; - } - // Assume any other keyword combination is legal. This can be refined in the future - // if there are more cases we want the classifier to be better at. - return true; - } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0, n = dense.length; i < n; i += 3) { - var start = dense[i]; - var length_3 = dense[i + 1]; - var type = dense[i + 2]; - // Make a whitespace entry between the last item and this one. - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); - } - } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1 /* comment */: return TokenClass.Comment; - case 3 /* keyword */: return TokenClass.Keyword; - case 4 /* numericLiteral */: return TokenClass.NumberLiteral; - case 5 /* operator */: return TokenClass.Operator; - case 6 /* stringLiteral */: return TokenClass.StringLiteral; - case 8 /* whiteSpace */: return TokenClass.Whitespace; - case 10 /* punctuation */: return TokenClass.Punctuation; - case 2 /* identifier */: - case 11 /* className */: - case 12 /* enumName */: - case 13 /* interfaceName */: - case 14 /* moduleName */: - case 15 /* typeParameterName */: - case 16 /* typeAliasName */: - case 9 /* text */: - case 17 /* parameterName */: - default: - return TokenClass.Identifier; - } - } - function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - 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 getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; - var token = 0 /* Unknown */; - var lastNonTriviaToken = 0 /* Unknown */; - // Empty out the template stack for reuse. - while (templateStack.length > 0) { - templateStack.pop(); - } - // If we're in a string literal, then prepend: "\ - // (and a newline). That way when we lex we'll think we're still in a string literal. - // - // If we're in a multiline comment, then prepend: /* - // (and a newline). That way when we lex we'll think we're still in a multiline comment. - switch (lexState) { - case 3 /* InDoubleQuoteStringLiteral */: - text = "\"\\\n" + text; - offset = 3; - break; - case 2 /* InSingleQuoteStringLiteral */: - text = "'\\\n" + text; - offset = 3; - break; - case 1 /* InMultiLineCommentTrivia */: - text = "/*\n" + text; - offset = 3; - break; - case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: - text = "`\n" + text; - offset = 2; - break; - case 5 /* InTemplateMiddleOrTail */: - text = "}\n" + text; - offset = 2; - // fallthrough - case 6 /* InTemplateSubstitutionPosition */: - templateStack.push(12 /* TemplateHead */); - break; - } - scanner.setText(text); - var result = { - endOfLineState: 0 /* None */, - spans: [] - }; - // We can run into an unfortunate interaction between the lexical and syntactic classifier - // when the user is typing something generic. Consider the case where the user types: - // - // Foo tokens. It's a weak heuristic, but should - // work well enough in practice. - var angleBracketStack = 0; - do { - token = scanner.scan(); - if (!ts.isTrivia(token)) { - if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { - token = 10 /* RegularExpressionLiteral */; - } - } - else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { - token = 69 /* Identifier */; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - // We have two keywords in a row. Only treat the second as a keyword if - // it's a sequence that could legally occur in the language. Otherwise - // treat it as an identifier. This way, if someone writes "private var" - // we recognize that 'var' is actually an identifier here. - token = 69 /* Identifier */; - } - else if (lastNonTriviaToken === 69 /* Identifier */ && - token === 25 /* LessThanToken */) { - // Could be the start of something generic. Keep track of that by bumping - // up the current count of generic contexts we may be in. - angleBracketStack++; - } - else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { - // If we think we're currently in something generic, then mark that that - // generic entity is complete. - angleBracketStack--; - } - else if (token === 117 /* AnyKeyword */ || - token === 132 /* StringKeyword */ || - token === 130 /* NumberKeyword */ || - token === 120 /* BooleanKeyword */ || - token === 133 /* SymbolKeyword */) { - if (angleBracketStack > 0 && !syntacticClassifierAbsent) { - // If it looks like we're could be in something generic, don't classify this - // as a keyword. We may just get overwritten by the syntactic classifier, - // causing a noisy experience for the user. - token = 69 /* Identifier */; - } - } - else if (token === 12 /* TemplateHead */) { - templateStack.push(token); - } - else if (token === 15 /* OpenBraceToken */) { - // If we don't have anything on the template stack, - // then we aren't trying to keep track of a previously scanned template head. - if (templateStack.length > 0) { - templateStack.push(token); - } - } - else if (token === 16 /* CloseBraceToken */) { - // If we don't have anything on the template stack, - // then we aren't trying to keep track of a previously scanned template head. - if (templateStack.length > 0) { - var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12 /* TemplateHead */) { - token = scanner.reScanTemplateToken(); - // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 14 /* TemplateTail */) { - templateStack.pop(); - } - else { - ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); - } - } - else { - ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); - templateStack.pop(); - } - } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1 /* EndOfFileToken */); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9 /* StringLiteral */ || token === 166 /* StringLiteralType */) { - // Check to see if we finished up on a multiline string literal. - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { - numBackslashes++; - } - // If we have an odd number of backslashes, then the multiline string is unclosed - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 /* doubleQuote */ - ? 3 /* InDoubleQuoteStringLiteral */ - : 2 /* InSingleQuoteStringLiteral */; - } - } - } - else if (token === 3 /* MultiLineCommentTrivia */) { - // Check to see if the multiline comment was unclosed. - if (scanner.isUnterminated()) { - result.endOfLineState = 1 /* InMultiLineCommentTrivia */; - } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 14 /* TemplateTail */) { - result.endOfLineState = 5 /* InTemplateMiddleOrTail */; - } - else if (token === 11 /* NoSubstitutionTemplateLiteral */) { - result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } - } - } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { - result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; - } - } - } - function addResult(start, end, classification) { - if (classification === 8 /* whiteSpace */) { - // Don't bother with whitespace classifications. They're not needed. - return; - } - 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; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); - } - } - } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: - case 91 /* InstanceOfKeyword */: - case 90 /* InKeyword */: - case 116 /* AsKeyword */: - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: - case 46 /* AmpersandToken */: - case 48 /* CaretToken */: - case 47 /* BarToken */: - case 51 /* AmpersandAmpersandToken */: - case 52 /* BarBarToken */: - case 67 /* BarEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 56 /* EqualsToken */: - case 24 /* CommaToken */: - return true; - default: - return false; - } - } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: - return true; - default: - return false; - } - } - function isKeyword(token) { - return token >= 70 /* FirstKeyword */ && token <= 138 /* LastKeyword */; - } - function classFromKind(token) { - if (isKeyword(token)) { - return 3 /* keyword */; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5 /* operator */; - } - else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { - return 10 /* punctuation */; - } - switch (token) { - case 8 /* NumericLiteral */: - return 4 /* numericLiteral */; - case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: - return 6 /* stringLiteral */; - case 10 /* RegularExpressionLiteral */: - return 7 /* regularExpressionLiteral */; - case 7 /* ConflictMarkerTrivia */: - case 3 /* MultiLineCommentTrivia */: - case 2 /* SingleLineCommentTrivia */: - return 1 /* comment */; - case 5 /* WhitespaceTrivia */: - case 4 /* NewLineTrivia */: - return 8 /* whiteSpace */; - case 69 /* Identifier */: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6 /* stringLiteral */; - } - return 2 /* identifier */; - } - } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; - } - ts.createClassifier = createClassifier; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript * node package. @@ -58935,13 +74003,7 @@ var ts; } ts.getDefaultLibFilePath = getDefaultLibFilePath; function initializeServices() { - ts.objectAllocator = { - getNodeConstructor: function () { return NodeObject; }, - getSourceFileConstructor: function () { return SourceFileObject; }, - getSymbolConstructor: function () { return SymbolObject; }, - getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } - }; + ts.objectAllocator = getServicesObjectAllocator(); } initializeServices(); })(ts || (ts = {})); @@ -59184,7 +74246,7 @@ var ts; return spanInNode(binaryExpression.left); } } - if (ts.isExpression(node)) { + if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { case 204 /* DoStatement */: // Set span as if on while keyword @@ -59269,7 +74331,7 @@ var ts; // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' if (variableDeclaration.initializer || - (variableDeclaration.flags & 1 /* Export */) || + ts.hasModifier(variableDeclaration, 1 /* Export */) || variableDeclaration.parent.parent.kind === 208 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } @@ -59285,7 +74347,7 @@ var ts; function canHaveSpanInParameterDeclaration(parameter) { // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 4 /* Public */) || !!(parameter.flags & 8 /* Private */); + ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */); } function spanInParameterDeclaration(parameter) { if (ts.isBindingPattern(parameter.name)) { @@ -59309,7 +74371,7 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1 /* Export */) || + return ts.hasModifier(functionDeclaration, 1 /* Export */) || (functionDeclaration.parent.kind === 221 /* ClassDeclaration */ && functionDeclaration.kind !== 148 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { @@ -59562,7 +74624,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = this; +var debugObjectHost = new Function("return this")(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -59615,7 +74677,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.lookUp(resolutionsInFile, name); + var result = ts.getProperty(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -59626,7 +74688,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); }; } } @@ -59701,11 +74763,21 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return this.shimHost.getDirectories(path); + return JSON.parse(this.shimHost.getDirectories(path)); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; + LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); + }; + LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { + return this.shimHost.readFile(path, encoding); + }; + LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { + return this.shimHost.fileExists(path); + }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -59719,7 +74791,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = Date.now(); + var time = ts.timestamp(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { // Check no more than once every 10 ms. @@ -59772,6 +74844,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; + CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { + return JSON.parse(this.shimHost.getDirectories(path)); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -59779,11 +74854,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = Date.now(); + start = ts.timestamp(); } var result = action(); if (logPerformance) { - var end = Date.now(); + var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -59975,6 +75050,15 @@ var ts; var _this = this; return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); @@ -60064,9 +75148,9 @@ var ts; }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ - LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; @@ -60169,6 +75253,13 @@ var ts; }; }); }; + CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); + }); + }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -60304,5 +75395,5 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "1.9"; +var toolsVersion = "2.1"; /* tslint:enable:no-unused-variable */